id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,100 | settings.py | gabrielfalcao_lettuce/tests/integration/django/grocery/settings.py | # Django settings for grocery project.
from os.path import dirname, abspath, join
LOCAL_FILE = lambda *path: abspath(join(dirname(__file__), *path))
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'grocery-db.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'gw$-1dpq0k8xc+fqkywqr0$c3^fg)x!ym*^46=jmc@ql&z)pr8'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
ROOT_URLCONF = 'grocery.urls'
TEMPLATE_DIRS = (
LOCAL_FILE('templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'lettuce.django',
)
LETTUCE_SERVER_PORT = 7000
STATIC_FILES_AT = LOCAL_FILE('static-files')
STATICFILES_DIRS = [
STATIC_FILES_AT,
]
| 3,366 | Python | .py | 81 | 39.08642 | 122 | 0.704532 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,101 | urls.py | gabrielfalcao_lettuce/tests/integration/django/grocery/urls.py | import django
from django.conf import settings
from django.contrib import admin
from django.conf.urls.defaults import *
admin.autodiscover()
django_version = django.get_version()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
)
if django_version.startswith('1.3'):
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += (url(
r'^static/(?P<path>.*)$',
'django.views.static.serve',
{
'document_root': settings.STATIC_FILES_AT,
},
),)
| 596 | Python | .py | 20 | 25.4 | 71 | 0.692308 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,102 | settings_without_admin.py | gabrielfalcao_lettuce/tests/integration/django/grocery/settings_without_admin.py | from settings import *
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'lettuce.django',
)
LETTUCE_SERVE_ADMIN_MEDIA = True
| 222 | Python | .py | 9 | 21.222222 | 34 | 0.71564 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,103 | terrain.py | gabrielfalcao_lettuce/tests/integration/django/grocery/terrain.py | # -*- coding: utf-8 -*-
from lettuce import before
from django.core.management import call_command
@before.harvest
def create_db(variables):
call_command('syncdb', interactive=False, verbosity=0)
| 202 | Python | .py | 6 | 31.666667 | 58 | 0.773196 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,104 | manage.py | gabrielfalcao_lettuce/tests/integration/django/grocery/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| 546 | Python | .py | 10 | 51.5 | 299 | 0.738318 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,105 | grocery_steps.py | gabrielfalcao_lettuce/tests/integration/django/grocery/features/step_definitions/grocery_steps.py | # -*- coding: utf-8 -*-
import urllib2
from lettuce import step, before, world
from lettuce.django import django_url
from nose.tools import assert_equals
from django.conf import settings
from lxml import html as lhtml
@world.absorb
def get_url(url):
if not url.startswith('http'):
url = django_url(url)
try:
world.last_response = urllib2.urlopen(url)
except Exception as e:
world.last_response = e
return world.last_response
@before.each_scenario
def prepare_the_world(scenario):
world.statuses = []
world.content_types = []
world.last_response = None
@step(u'my settings.py has "(.*)" set to "(.*)"')
def given_my_settings_py_has_group1_set_to_group2(step, key, value):
assert hasattr(settings, key), 'settings.%s is not set' % key
assert_equals(getattr(settings, key), int(value))
@step(u'I see that requesting "(.*)" gets "(.*)"')
def then_i_see_that_requesting_group1_gets_group2(step, url, status):
world.get_url(url)
assert_equals(int(world.last_response.code), int(status))
@step(u'Given I fetch the urls:')
def given_i_fetch_the_urls(step):
urls = map(lambda i: django_url(i['url']), step.hashes)
for url in urls:
http = world.get_url(url)
world.statuses.append((url, http.code))
world.content_types.append((url, http.headers.dict['content-type']))
http.close()
@step(u'When all the responses have status code 200')
def when_all_the_responses_have_status_code_200(step):
assert len(world.statuses) > 0, \
"I can't check the status codes, it seems no requests were made"
for url, status in world.statuses:
assert status is 200, \
"for %s the status code should be 200 but is %d" % (url, status)
@step(u'Then all the responses have mime type "(.*)"')
def then_all_the_responses_have_mime_type_group1(step, group1):
for url, content_type in world.content_types:
assert_equals(content_type, group1, 'failed at %s' % url)
@step(u'I navigate to "(.*)"')
def given_i_navigate_to_group1(step, url):
world.get_url(url)
@step(u'try to resolve the assets provided by given HTML')
def when_i_try_to_resolve_the_assets_provided_by_given_html(step):
dom = lhtml.fromstring(world.last_response.read())
elements = dom.cssselect('link[href],script[src]')
for e in elements:
url = django_url(e.attrib.get('href', e.attrib.get('src')))
http = world.get_url(url)
world.statuses.append((url, http.code))
world.content_types.append((url, http.headers.dict['content-type']))
http.close()
@step(u'all the responses have are between one of those mime types:')
def then_all_the_responses_have_are_between_one_of_those_mime_types(step):
expected_mimetypes = [d['mime-type'] for d in step.hashes]
for url, content_type in world.content_types:
assert content_type in expected_mimetypes, \
'the url %s got an unexpected mimetype' % content_type
@step(u'should be an (\S+)')
def should_be_an_image(step, expected):
got = world.last_response.headers['content-type']
assert expected in got, \
u'fetching the url %s, the content-type header should contain "%s", ' \
'but it is actually %s' % (world.last_response.geturl(), expected, got)
| 3,302 | Python | .py | 73 | 40.260274 | 79 | 0.686856 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,106 | settings.py | gabrielfalcao_lettuce/tests/integration/django/dill/settings.py | DEBUG = True
ROOT_URLCONF = 'urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'garden-db.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
INSTALLED_APPS = (
'lettuce.django',
'leaves',
)
SECRET_KEY = 'secret'
STATIC_URL = '/static/'
| 719 | Python | .py | 18 | 35.333333 | 122 | 0.542857 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,107 | urls.py | gabrielfalcao_lettuce/tests/integration/django/dill/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'', 'leaves.views.index'),
)
| 106 | Python | .py | 4 | 24.25 | 39 | 0.70297 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,108 | manage.py | gabrielfalcao_lettuce/tests/integration/django/dill/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| 546 | Python | .py | 10 | 51.5 | 299 | 0.738318 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,109 | models.py | gabrielfalcao_lettuce/tests/integration/django/dill/leaves/models.py | from django.db import models
class Garden(models.Model):
name = models.CharField(max_length=100)
area = models.IntegerField()
raining = models.BooleanField()
@property
def howbig(self):
if self.area < 50:
return 'small'
elif self.area < 150:
return 'medium'
else:
return 'big'
class Field(models.Model):
name = models.CharField(max_length=100)
class Fruit(models.Model):
name = models.CharField(max_length=100)
garden = models.ForeignKey(Garden)
ripe_by = models.DateField()
fields = models.ManyToManyField(Field)
class Bee(models.Model):
name = models.CharField(max_length=100)
pollinated_fruit = models.ManyToManyField(Fruit,
related_name='pollinated_by')
class Goose(models.Model):
name = models.CharField(max_length=100)
class Meta:
verbose_name_plural = "geese"
class Harvester(models.Model):
make = models.CharField(max_length=100)
rego = models.CharField(max_length=100)
class Panda(models.Model):
"""
Not part of a garden, but still an important part of any good application
"""
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
| 1,285 | Python | .py | 37 | 27.945946 | 77 | 0.668019 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,110 | views.py | gabrielfalcao_lettuce/tests/integration/django/dill/leaves/views.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.http import HttpResponse
def index(request):
return HttpResponse('OK')
| 872 | Python | .py | 19 | 44.631579 | 71 | 0.768779 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,111 | steps.py | gabrielfalcao_lettuce/tests/integration/django/dill/leaves/features/steps.py | import json
from django.core.management import call_command
from leaves.models import *
from lettuce import after, step
from lettuce.django.steps.models import *
from nose.tools import assert_equals
after.each_scenario(clean_db)
max_rego = 0
@creates_models(Harvester)
def create_with_rego(step):
data = hashes_data(step)
for hash_ in data:
hash_['rego'] = hash_['make'][:3].upper() + "001"
create_models(Harvester, data)
@checks_existence(Harvester)
def check_with_rego(step):
data = hashes_data(step)
for hash_ in data:
try:
hash_['rego'] = hash_['rego'].upper()
except KeyError:
pass
models_exist(Harvester, data)
@step(r'The database dump is as follows')
def database_dump(step):
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
output = StringIO()
call_command('dumpdata', stdout=output, indent=2)
output = output.getvalue()
assert_equals(json.loads(output), json.loads(step.multiline))
@step(r'I have populated the database')
def database_populated(step):
pass
@step(r'I count the harvesters')
def count_harvesters(step):
print "Harvester count: %d" % Harvester.objects.count()
@creates_models(Panda)
def create_pandas(step):
data = hashes_data(step)
if 'name' in data:
data['name'] += ' Panda'
return create_models(Panda, data)
| 1,432 | Python | .py | 45 | 27.266667 | 65 | 0.700073 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,112 | settings.py | gabrielfalcao_lettuce/tests/integration/django/cucumber/settings.py | # Django settings for cucumber project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Make this unique, and don't share it with anybody.
SECRET_KEY = '3c=9-_@gug3+!j*o*b$1!g8e7037(ghrns8pqygog1gs1f^zqu'
ROOT_URLCONF = 'cucumber.urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
INSTALLED_APPS = (
'lettuce.django',
'first',
'second',
)
| 879 | Python | .py | 21 | 37.47619 | 122 | 0.567251 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,113 | urls.py | gabrielfalcao_lettuce/tests/integration/django/cucumber/urls.py | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^cucumber/', include('cucumber.foo.urls')),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/', include(admin.site.urls)),
)
| 546 | Python | .py | 13 | 38.461538 | 76 | 0.710775 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,114 | terrain.py | gabrielfalcao_lettuce/tests/integration/django/cucumber/terrain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import before, after
from lettuce.django.server import ThreadedServer
from django.core.servers.basehttp import WSGIServer
from nose.tools import assert_equals
@before.harvest
def before_harvest(variables):
print "before harvest"
@after.harvest
def after_harvest(results):
assert_equals(len(results), 2)
assert_equals(results[0].steps_passed, 1)
assert_equals(results[1].steps_passed, 1)
print "after harvest"
@before.each_app
def before_app(module):
assert module.__name__ in [
'first',
'second',
], '%r should be one of these app modules: "first", "seconds"' % module
print "before each app"
@after.each_app
def after_app(module, result):
assert module.__name__ in [
'first',
'second',
], '%r should be one of these app modules: "first", "seconds"' % module
assert_equals(result.steps_passed, 1)
print "after each app"
@before.runserver
def before_runserver(server):
assert isinstance(server, ThreadedServer), '%s should be an instance of lettuce.django.server.ThreadedServer' % server
assert_equals(server.address, '0.0.0.0')
assert_equals(server.port, 8000)
print "before within runserver"
@after.runserver
def after_runserver(server):
assert isinstance(server, ThreadedServer), '%r should be an instance of lettuce.django.server.ThreadedServer' % server
assert_equals(server.address, '0.0.0.0')
assert_equals(server.port, 8000)
print "after within runserver"
@before.handle_request
def before_handle_request(httpd, server):
assert isinstance(httpd, WSGIServer), '%r should be an instance of WSGIServer' % server
assert isinstance(server, ThreadedServer), '%r should be an instance of lettuce.django.server.ThreadedServer' % server
print "before within handle_request"
@after.handle_request
def after_handle_request(httpd, server):
assert isinstance(httpd, WSGIServer), '%r should be an instance of WSGIServer' % server
assert isinstance(server, ThreadedServer), '%r should be an instance of lettuce.django.server.ThreadedServer' % server
print "after within handle_request"
| 2,183 | Python | .py | 52 | 38.173077 | 122 | 0.738802 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,115 | manage.py | gabrielfalcao_lettuce/tests/integration/django/cucumber/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| 546 | Python | .py | 10 | 51.5 | 299 | 0.738318 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,116 | second.py | gabrielfalcao_lettuce/tests/integration/django/cucumber/second/features/step_definitions/second.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Given this app is the second app')
def given_this_app_is_the_second_app(step):
pass
| 146 | Python | .py | 5 | 27.2 | 43 | 0.707143 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,117 | first.py | gabrielfalcao_lettuce/tests/integration/django/cucumber/first/features/step_definitions/first.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Given this app is the first app')
def given_this_app_is_the_second_app(step):
pass
| 145 | Python | .py | 5 | 27 | 43 | 0.705036 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,118 | test_feature_loader.py | gabrielfalcao_lettuce/tests/functional/test_feature_loader.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from nose.tools import assert_equals
from os.path import dirname, join, abspath
from lettuce.fs import FeatureLoader
from lettuce.core import Feature, fs
current_dir = abspath(dirname(__file__))
cjoin = lambda *x: join(current_dir, 'simple_features', *x)
def test_feature_finder_finds_all_feature_files_within_a_dir():
"FeatureLoader finds all feature files within a directory"
ff = FeatureLoader(cjoin())
files = ff.find_feature_files()
assert_equals(
sorted(files),
sorted([
cjoin('1st_feature_dir', 'one_more.feature'),
cjoin('1st_feature_dir', 'some.feature'),
cjoin('1st_feature_dir', 'more_features_here', 'another.feature'),
cjoin('2nd_feature_dir', 'before_and_after_all.feature'),
cjoin('2nd_feature_dir', 'with_defined_steps.feature'),
cjoin('3rd_feature_dir', 'my_steps_are_anywhere.feature'),
])
)
def test_feature_finder_loads_feature_objects():
"Feature.from_file loads feature by filename"
feature_file = cjoin('1st_feature_dir', 'more_features_here', 'another.feature')
feature = Feature.from_file(feature_file)
assert_equals(type(feature), Feature)
expected_scenario_names = ["Regular numbers", "Fractions"]
got_scenario_names = [s.name for s in feature.scenarios]
assert_equals(expected_scenario_names, got_scenario_names)
assert_equals(len(feature.scenarios[0].steps), 4)
step1, step2, step3, step4 = feature.scenarios[0].steps
assert_equals(step1.sentence, '* I have entered 3 into the calculator')
assert_equals(step2.sentence, '* I have entered 2 into the calculator')
assert_equals(step3.sentence, '* I press divide')
assert_equals(step4.sentence, '* the result should be 1.5 on the screen')
def test_feature_loaded_from_file_has_feature_line_and_feature_filename():
"Feature.from_file sets FeatureDescription into Feature objects, " \
"giving line number and filename as well"
feature_file = cjoin('1st_feature_dir', 'more_features_here', 'another.feature')
feature = Feature.from_file(feature_file)
assert_equals(feature.described_at.file, fs.relpath(feature_file))
assert_equals(feature.described_at.line, 2)
assert_equals(feature.name, 'Division')
assert_equals(feature.described_at.description_at, (3, 4))
def test_feature_loaded_from_file_has_description_at():
"Feature.from_file sets FeatureDescription with line numbers of its description"
feature_file = cjoin('1st_feature_dir', 'some.feature')
feature = Feature.from_file(feature_file)
assert_equals(feature.described_at.file, fs.relpath(feature_file))
assert_equals(feature.described_at.line, 5)
assert_equals(feature.name, 'Addition')
assert_equals(feature.described_at.description_at, (6, 7, 8))
assert_equals(
feature.description,
"In order to avoid silly mistakes\n"
"As a math idiot\n"
"I want to be told the sum of two numbers"
)
def test_feature_loaded_from_file_sets_scenario_line_and_scenario_filename():
"Feature.from_file sets ScenarioDescription into Scenario objects, " \
"giving line number and filename as well"
feature_file = cjoin('1st_feature_dir', 'more_features_here', 'another.feature')
feature = Feature.from_file(feature_file)
scenario1, scenario2 = feature.scenarios
assert_equals(scenario1.described_at.file, fs.relpath(feature_file))
assert_equals(scenario1.described_at.line, 6)
assert_equals(scenario2.described_at.file, fs.relpath(feature_file))
assert_equals(scenario2.described_at.line, 12)
def test_feature_loaded_from_file_sets_step_line_and_step_filenames():
"Feature.from_file sets StepDescription into Scenario objects, " \
"giving line number and filename as well"
feature_file = cjoin('1st_feature_dir', 'one_more.feature')
feature = Feature.from_file(feature_file)
(scenario, ) = feature.scenarios
step1, step2, step3, step4 = scenario.steps
for step in scenario.steps:
assert_equals(step.described_at.file, fs.relpath(feature_file))
assert_equals(step1.sentence, "* I have entered 10 into the calculator")
assert_equals(step1.described_at.line, 7)
assert_equals(step2.sentence, "* I have entered 4 into the calculator")
assert_equals(step2.described_at.line, 8)
assert_equals(step3.sentence, "* I press multiply")
assert_equals(step3.described_at.line, 9)
assert_equals(step4.sentence, "* the result should be 40 on the screen")
assert_equals(step4.described_at.line, 10)
| 5,382 | Python | .py | 101 | 48.306931 | 84 | 0.726719 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,119 | test_behave_as_handling.py | gabrielfalcao_lettuce/tests/functional/test_behave_as_handling.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from nose.tools import with_setup
from os.path import dirname, join, abspath
from lettuce import Runner
import lettuce
from lettuce.core import fs, StepDefinition
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from tests.asserts import assert_stdout_lines_with_traceback
current_dir = abspath(dirname(__file__))
lettuce_dir = abspath(dirname(lettuce.__file__))
lettuce_path = lambda *x: fs.relpath(join(lettuce_dir, *x))
call_line = StepDefinition.__call__.im_func.func_code.co_firstlineno + 5
def path_to_feature(name):
return join(abspath(dirname(__file__)), 'behave_as_features', name, "%s.feature" % name)
@with_setup(prepare_stdout)
def test_simple_behave_as_feature():
"Basic step.behave_as behaviour is working"
Runner(path_to_feature('1st_normal_steps'), verbosity=3, no_color=True).run()
assert_stdout_lines(
"\n"
"Feature: Multiplication # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:2\n"
" In order to avoid silly mistakes # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:3\n"
" Cashiers must be able to multiplicate numbers :) # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:4\n"
"\n"
" Scenario: Regular numbers # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:6\n"
" Given I have entered 10 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:11\n"
" And I have entered 4 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:11\n"
" When I press multiply # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:15\n"
" Then the result should be 40 on the screen # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:19\n"
"\n"
" Scenario: Shorter version of the scenario above # tests/functional/behave_as_features/1st_normal_steps/1st_normal_steps.feature:12\n"
" Given I multiply 10 and 4 into the calculator # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:23\n"
" Then the result should be 40 on the screen # tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py:19\n"
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"6 steps (6 passed)\n"
)
@with_setup(prepare_stdout)
def test_simple_tables_behave_as_feature():
"Basic step.behave_as behaviour is working"
Runner(path_to_feature('2nd_table_steps'), verbosity=3, no_color=True).run()
assert_stdout_lines(
"\n"
"Feature: Multiplication # tests/functional/behave_as_features/2nd_table_steps/2nd_table_steps.feature:2\n"
" In order to avoid silly mistakes # tests/functional/behave_as_features/2nd_table_steps/2nd_table_steps.feature:3\n"
" Cashiers must be able to multiplicate numbers :) # tests/functional/behave_as_features/2nd_table_steps/2nd_table_steps.feature:4\n"
"\n"
" Scenario: Regular numbers # tests/functional/behave_as_features/2nd_table_steps/2nd_table_steps.feature:6\n"
" Given I multiply these numbers: # tests/functional/behave_as_features/2nd_table_steps/simple_tables_step_definitions.py:31\n"
" | number |\n"
" | 55 |\n"
" | 2 |\n"
" Then the result should be 110 on the screen # tests/functional/behave_as_features/2nd_table_steps/simple_tables_step_definitions.py:19\n"
"\n"
" Scenario: Shorter version of the scenario above # tests/functional/behave_as_features/2nd_table_steps/2nd_table_steps.feature:13\n"
" Given I multiply 55 and 2 into the calculator # tests/functional/behave_as_features/2nd_table_steps/simple_tables_step_definitions.py:23\n"
" Then the result should be 110 on the screen # tests/functional/behave_as_features/2nd_table_steps/simple_tables_step_definitions.py:19\n"
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"4 steps (4 passed)\n"
)
@with_setup(prepare_stdout)
def test_failing_tables_behave_as_feature():
"Basic step.behave_as behaviour is working"
Runner(path_to_feature('3rd_failing_steps'), verbosity=3, no_color=True).run()
assert_stdout_lines_with_traceback(
'\n'
'Feature: Multiplication # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:2\n'
' In order to avoid silly mistakes # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:3\n'
' Cashiers must be able to multiplicate numbers :) # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:4\n'
'\n'
' Scenario: Regular numbers # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:6\n'
' Given I have entered 10 into the calculator # tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py:11\n'
' Traceback (most recent call last):\n'
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
' ret = self.function(self.step, *args, **kw)\n'
' File "%(step_file)s", line 13, in i_have_entered_NUM_into_the_calculator\n'
' assert False, \'Die, die, die my darling!\'\n'
' AssertionError: Die, die, die my darling!\n'
' And I have entered 4 into the calculator # tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py:11\n'
' When I press multiply # tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py:16\n'
' Then the result should be 40 on the screen # tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py:20\n'
'\n'
' Scenario: Shorter version of the scenario above # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:12\n'
' Given I multiply 10 and 4 into the calculator # tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py:24\n'
' Traceback (most recent call last):\n'
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
' ret = self.function(self.step, *args, **kw)\n'
' File "%(step_file)s", line 29, in multiply_X_and_Y_into_the_calculator\n'
' \'\'\'.format(x, y))\n'
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
' assert not steps_failed, steps_failed[0].why.exception\n'
' AssertionError: Die, die, die my darling!\n'
' Then the result should be 40 on the screen # tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py:20\n'
'\n'
'1 feature (0 passed)\n'
'2 scenarios (0 passed)\n'
'6 steps (2 failed, 4 skipped, 0 passed)\n'
'\n'
'List of failed scenarios:\n'
' Scenario: Regular numbers # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:6\n'
' Scenario: Shorter version of the scenario above # tests/functional/behave_as_features/3rd_failing_steps/3rd_failing_steps.feature:12\n'
'\n' % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'behave_as_features', '3rd_failing_steps', 'failing_step_definitions.py')),
'call_line':call_line,
}
)
| 8,708 | Python | .py | 126 | 63.793651 | 153 | 0.675531 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,120 | test_jsonreport_output.py | gabrielfalcao_lettuce/tests/functional/test_jsonreport_output.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# REMOVE THIS
from __future__ import unicode_literals
from contextlib import contextmanager
import json
import os
import lettuce
from mock import patch
from nose.tools import assert_equals, assert_true, with_setup
from lettuce import registry
from lettuce import Runner
from tests.functional.test_runner import feature_name, bg_feature_name
from tests.asserts import prepare_stdout
@contextmanager
def check_jsonreport(feature, filename=None):
filename = filename or "lettucetests.json"
with patch.object(json, "dump") as json_dump:
yield
os.remove(filename)
assert_true(json_dump.called, "Function not called")
content, file_handle = json_dump.mock_calls[0][1]
assert_equals(content, OUTPUTS[feature])
assert_equals(file_handle.name, filename)
# check that we can dump it
try:
json.dumps(content)
except (TypeError, ValueError):
raise AssertionError('JSON report is not valid JSON:\n\n%s' % content)
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_no_errors():
'Test jsonreport output with no errors'
with check_jsonreport('commented_feature'):
runner = Runner(feature_name('commented_feature'), enable_jsonreport=True)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_one_error():
'Test jsonreport output with one errors'
with check_jsonreport('error_traceback'):
runner = Runner(feature_name('error_traceback'), enable_jsonreport=True)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_different_filename():
'Test jsonreport output with different filename'
with check_jsonreport('error_traceback', "custom_filename.json"):
runner = Runner(
feature_name('error_traceback'), enable_jsonreport=True,
jsonreport_filename="custom_filename.json"
)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_unicode_characters_in_error_messages():
with check_jsonreport('unicode_traceback'):
runner = Runner(feature_name('unicode_traceback'), enable_jsonreport=True)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_xunit_does_not_throw_exception_when_missing_step_definition():
with check_jsonreport('missing_steps'):
runner = Runner(feature_name('missing_steps'), enable_jsonreport=True)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_no_steps():
'Test jsonreport output with no steps'
with check_jsonreport('missing_steps'):
runner = Runner(feature_name('missing_steps'), enable_jsonreport=True)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_background_section():
'Test jsonreport output with a background section in the feature'
@lettuce.step(ur'the variable "(\w+)" holds (\d+)')
@lettuce.step(ur'the variable "(\w+)" is equal to (\d+)')
def just_pass(step, *args):
pass
with check_jsonreport('background_simple'):
runner = Runner(bg_feature_name('simple'), enable_jsonreport=True)
runner.run()
@with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_unicode_and_bytestring():
'Test jsonreport output with unicode and bytestring'
with check_jsonreport('xunit_unicode_and_bytestring_mixing'):
runner = Runner(feature_name('xunit_unicode_and_bytestring_mixing'), enable_jsonreport=True)
runner.run()
BASE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
OUTPUTS = {
"commented_feature": {
'features': [
{'meta': {
'steps': {
'failures': 0,
'skipped': 0,
'success': 1,
'total': 1,
'undefined': 0
},
'scenarios': {
'failures': 0,
'skipped': 0,
'success': 1,
'total': 1,
'undefined': 0
}
},
'name': u'one commented scenario',
'duration': 0,
"background": None,
'scenarios': [
{'meta': {
'failures': 0,
'skipped': 0,
'success': 1,
'total': 1,
'undefined': 0
},
'name': u'Do nothing',
'duration': 0,
'outline': None,
'steps': [
{'failure': {},
'meta': {
'failed': False,
'skipped': False,
'success': True,
'undefined': False
},
'duration': 0,
'name': u'Given I do nothing'
}]
}]
}],
'duration': 0,
'meta': {
'features': {
'failures': 0,
'success': 1,
'total': 1
},
'is_success': True,
'scenarios': {
'failures': 0,
'success': 1,
'total': 1
},
'steps': {
'failures': 0,
'skipped': 0,
'success': 1,
'total': 1,
'undefined': 0
}
}
},
'error_traceback': {
"meta": {
"scenarios": {
"failures": 1,
"total": 2,
"success": 1
},
"is_success": False,
"steps": {
"failures": 1,
"skipped": 0,
"total": 2,
"undefined": 0,
"success": 1
},
"features": {
"failures": 1,
"total": 1,
"success": 0
}
},
"duration": 0,
"features": [
{
"scenarios": [
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": False,
"success": True
},
'duration': 0,
"name": "Given my step that passes"
}
],
"duration": 0,
"name": "It should pass",
"outline": None
},
{
"meta": {
"failures": 1,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 0
},
"steps": [
{
"failure": {
"exception": "RuntimeError()",
"traceback": "Traceback (most recent call last):\n File \"{path}/lettuce/core.py\", line 144, in __call__\n ret = self.function(self.step, *args, **kw)\n File \"{path}/tests/functional/output_features/error_traceback/error_traceback_steps.py\", line 10, in given_my_step_that_blows_a_exception\n raise RuntimeError\nRuntimeError\n".format(path=BASE_PATH)
},
"meta": {
"failed": True,
"skipped": False,
"undefined": False,
"success": False
},
'duration': 0,
"name": "Given my step that blows a exception"
}
],
"duration": 0,
"name": "It should raise an exception different of AssertionError",
"outline": None
}
],
'meta': {
'steps': {
"failures": 1,
"skipped": 0,
"total": 2,
"undefined": 0,
"success": 1
},
'scenarios': {
"failures": 1,
"skipped": 0,
"total": 2,
"undefined": 0,
"success": 1
}
},
"name": "Error traceback for output testing",
"duration": 0,
"background": None
}
]
},
'unicode_traceback': {
"meta": {
"scenarios": {
"failures": 1,
"total": 2,
"success": 1
},
"is_success": False,
"steps": {
"failures": 1,
"skipped": 0,
"total": 2,
"undefined": 0,
"success": 1
},
"features": {
"failures": 1,
"total": 1,
"success": 0
}
},
"duration": 0,
"features": [
{
"scenarios": [
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": False,
"success": True
},
'duration': 0,
"name": "Given my dæmi that passes"
}
],
"name": "It should pass",
"duration": 0,
"outline": None
},
{
"meta": {
"failures": 1,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 0
},
"steps": [
{
"failure": {
"exception": "AssertionError()",
"traceback": "Traceback (most recent call last):\n File \"{path}/lettuce/core.py\", line 144, in __call__\n ret = self.function(self.step, *args, **kw)\n File \"{path}/tests/functional/output_features/unicode_traceback/unicode_traceback_steps.py\", line 10, in given_my_daemi_that_blows_a_exception\n assert False\nAssertionError\n".format(path=BASE_PATH)
},
"meta": {
"failed": True,
"skipped": False,
"undefined": False,
"success": False
},
'duration': 0,
"name": "Given my \"dæmi\" that blows an exception"
}
],
"name": "It should raise an exception different of AssertionError",
"duration": 0,
"outline": None
}
],
"meta": {
"steps": {
"failures": 1,
"skipped": 0,
"total": 2,
"undefined": 0,
"success": 1
},
"scenarios": {
"failures": 1,
"skipped": 0,
"total": 2,
"undefined": 0,
"success": 1
}
},
"name": "Unicode characters in the error traceback",
"duration": 0,
"background": None
}
]
},
"missing_steps": {
"meta": {
"scenarios": {
"failures": 1,
"total": 1,
"success": 0
},
"is_success": True,
"steps": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
},
"features": {
"failures": 1,
"total": 1,
"success": 0
}
},
"duration": 0,
"features": [
{
"scenarios": [
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": True,
"success": False
},
'duration': None, # undefined
"name": "Given my sdfsdf sdfsdf sdfs df sdfsdf"
}
],
"name": "It should pass",
"duration": 0,
"outline": None
}
],
"meta": {
"steps": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
},
"scenarios": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
}
},
"name": "Missing steps do not cause the xunit plugin to throw",
"duration": 0,
"background": None
}
]
},
'no_steps_defined': {
"meta": {
"scenarios": {
"failures": 1,
"total": 1,
"success": 0
},
"is_success": True,
"steps": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
},
"features": {
"failures": 1,
"total": 1,
"success": 0
}
},
"duration": 0,
"features": [
{
"scenarios": [
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": True,
"success": False
},
'duration': 0,
"name": "Given I do nothing"
}
],
"name": "Do nothing",
"duration": 0,
"outline": None
}
],
"meta": {
"steps": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
},
"scenarios": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 1,
"success": 0
}
},
"name": "Scenario with no steps",
"duration": 0,
"background": None
}
]
},
'xunit_unicode_and_bytestring_mixing': {
"meta": {
"scenarios": {
"failures": 1,
"total": 3,
"success": 2
},
"is_success": False,
"steps": {
"failures": 1,
"skipped": 0,
"total": 3,
"undefined": 0,
"success": 2
},
"features": {
"failures": 1,
"total": 1,
"success": 0
}
},
"duration": 0,
"features": [
{
"scenarios": [
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": False,
"success": True
},
'duration': 0,
"name": "Given non ascii characters \"Значение\" in outline"
}
],
"name": "It should pass",
"duration": 0,
"outline": {
"value": "Значение"
}
},
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": False,
"success": True
},
'duration': 0,
"name": "Given non ascii characters \"\u0422\u0435\u0441\u0442\" in step"
}
],
"name": "It should pass too",
"duration": 0,
"outline": None
},
{
"meta": {
"failures": 1,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 0
},
"steps": [
{
"failure": {
"exception": "Exception(u'\\u0422\\u0435\\u0441\\u0442',)",
"traceback": "Traceback (most recent call last):\n File \"{path}/lettuce/core.py\", line 144, in __call__\n ret = self.function(self.step, *args, **kw)\n File \"{path}/tests/functional/output_features/xunit_unicode_and_bytestring_mixing/xunit_unicode_and_bytestring_mixing_steps.py\", line 16, in raise_nonascii_chars\n raise Exception(word)\nException: \\u0422\\u0435\\u0441\\u0442\n".format(path=BASE_PATH)
},
"meta": {
"failed": True,
"skipped": False,
"undefined": False,
"success": False
},
'duration': 0,
"name": "Given non ascii characters \"\u0422\u0435\u0441\u0442\" in exception"
}
],
"name": "Exception should not raise an UnicodeDecodeError",
"duration": 0,
"outline": None
}
],
"meta": {
"steps": {
"failures": 1,
"skipped": 0,
"total": 3,
"undefined": 0,
"success": 2
},
"scenarios": {
"failures": 1,
"skipped": 0,
"total": 3,
"undefined": 0,
"success": 2
}
},
"name": "Mixing of Unicode & bytestrings in xunit xml output",
"duration": 0,
"background": None
}
]
},
'background_simple': {
"meta": {
"scenarios": {
"failures": 0,
"total": 1,
"success": 1
},
"is_success": True,
"steps": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"features": {
"failures": 0,
"total": 1,
"success": 1
}
},
"duration": 0,
"features": [
{
"scenarios": [
{
"meta": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": False,
"success": True
},
'duration': 0,
"name": "Given the variable \"X\" is equal to 2"
}
],
"name": "multiplication changing the value",
"duration": 0,
"outline": None
}
],
"meta": {
"steps": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
},
"scenarios": {
"failures": 0,
"skipped": 0,
"total": 1,
"undefined": 0,
"success": 1
}
},
"name": "Simple and successful",
"duration": 0,
"background": {
"meta": {
"total": 1,
"success": 1,
"failures": 0,
"skipped": 0,
"undefined": 0,
},
"steps": [
{
"failure": {},
"meta": {
"failed": False,
"skipped": False,
"undefined": False,
"success": True
},
'duration': 0,
"name": "Given the variable \"X\" holds 2"
}
]
}
}
]
}
}
| 27,445 | Python | .py | 737 | 17.275441 | 452 | 0.329058 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,121 | test_terrain.py | gabrielfalcao_lettuce/tests/functional/test_terrain.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import commands
from os.path import dirname, abspath, join, curdir
from nose.tools import assert_equals, with_setup
from tests.asserts import prepare_stdout
def test_imports_terrain_under_path_that_is_run():
old_path = abspath(curdir)
os.chdir(join(abspath(dirname(__file__)), 'simple_features', '1st_feature_dir'))
status, output = commands.getstatusoutput('python -c "from lettuce import world;assert hasattr(world, \'works_fine\'); print \'it passed!\'"')
assert_equals(status, 0)
assert_equals(output, "it passed!")
os.chdir(old_path)
@with_setup(prepare_stdout)
def test_after_each_all_is_executed_before_each_all():
"terrain.before.each_all and terrain.after.each_all decorators"
from lettuce import step
from lettuce import Runner
from lettuce.terrain import before, after, world
world.all_steps = []
@before.all
def set_state_to_before():
world.all_steps.append('before')
@step('append 1 in world all steps')
def append_1_in_world_all_steps(step):
world.all_steps.append("1")
@step('append 2 more')
def append_2_more(step):
world.all_steps.append("2")
@step('append 3 in world all steps')
def append_during_to_all_steps(step):
world.all_steps.append("3")
@after.all
def set_state_to_after(total):
world.all_steps.append('after')
runner = Runner(join(abspath(dirname(__file__)), 'simple_features', '2nd_feature_dir'))
runner.run()
assert_equals(
world.all_steps,
['before', '1', '2', '3', 'after']
)
| 2,374 | Python | .py | 56 | 38.303571 | 146 | 0.710995 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,122 | test_step_definition_loading.py | gabrielfalcao_lettuce/tests/functional/test_step_definition_loading.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import assert_equals
from lettuce import Runner
from lettuce.terrain import before, world, after
def test_loads_sum_steps():
"Can load step definitions from step_definitions folder"
world.ran = False
@before.each_step
def assert_is_fine(step):
world.ran = True
runner = Runner(join(abspath(dirname(__file__)), 'simple_features', '2nd_feature_dir'), verbosity=0)
runner.run()
assert world.ran
def test_recursive_fallback():
"If don't find a step_definitions folder, fallback loading all python " \
"files under given dir, recursively."
world.step_list = list()
runner = Runner(join(abspath(dirname(__file__)), 'simple_features', '3rd_feature_dir'), verbosity=0)
runner.run()
assert_equals(
world.step_list,
[
'Given I define step at look/here/step_one.py',
'And at look/and_here/step_two.py',
'Also at look/here/for_steps/step_three.py',
'And finally at look/and_here/and_any_python_file/step_four.py',
]
)
del world.step_list
def test_discard_invalid_filenames():
"If a module has a invalid file name, we just discard it"
runner = Runner(join(abspath(dirname(__file__)), 'invalid_module_name'), verbosity=0)
runner.run()
| 2,129 | Python | .py | 49 | 39.081633 | 104 | 0.709724 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,123 | test_subunit_output.py | gabrielfalcao_lettuce/tests/functional/test_subunit_output.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from cStringIO import StringIO
from nose.tools import with_setup, assert_equal
from subunit.v2 import ByteStreamToStreamResult
from testtools import StreamToDict
from lettuce import Runner, registry
from lettuce.plugins import subunit_output
from tests.asserts import prepare_stdout
from tests.functional.test_runner import feature_name
class Includes(object):
def __init__(self, d):
self.d = d
def __eq__(self, a):
return all((v == a[k] for k, v in self.d.iteritems()))
def __repr__(self):
return '{klass}({d})'.format(
klass=self.__class__.__name__,
d=self.d)
class Keys(object):
def __init__(self, *keys):
self.keys = keys
def __eq__(self, a):
return set(a.keys()) == set(self.keys)
class ContentContains(object):
def __init__(self, text):
self.text = text
def __eq__(self, a):
return self.text in a.as_text()
def __repr__(self):
return '{klass}({text})'.format(
klass=self.__class__.__name__,
text=self.text)
class State(object):
expect = []
def handle_dict(self, test):
try:
d = self.expect.pop(0)
except IndexError:
raise AssertionError("Unexpected {test}".format(test=test))
assert_equal(d, test)
def close_file(self, file_):
"""
Close and check the file
"""
file_.seek(0)
case = ByteStreamToStreamResult(file_)
result = StreamToDict(self.handle_dict)
result.startTestRun()
case.run(result)
result.stopTestRun()
file_.close()
def setup(self):
"""
Set up the for the test case
"""
prepare_stdout()
output = StringIO()
self.patch = (subunit_output.open_file, subunit_output.close_file)
subunit_output.open_file = lambda f: output
subunit_output.close_file = self.close_file
def teardown(self):
"""
Tear down the test case
"""
subunit_output.open_file, subunit_output.close_file = self.patch
assert_equal(len(self.expect), 0, "Expected results left")
registry.clear()
state = State()
@with_setup(state.setup, state.teardown)
def test_subunit_output_with_no_errors():
"""
Test Subunit output with no errors
"""
state.expect = [
Includes({
'id': 'one commented scenario: Do nothing',
'status': 'success',
'details': Keys('stdout', 'stderr', 'steps'),
}),
]
runner = Runner(feature_name('commented_feature'), enable_subunit=True)
runner.run()
@with_setup(state.setup, state.teardown)
def test_subunit_output_with_one_error():
"""
Test Subunit output with one error
"""
state.expect = [
Includes({
'status': 'success',
'details': Keys('stdout', 'stderr', 'steps'),
}),
Includes({
'status': 'fail',
'details': Keys('stdout', 'stderr', 'traceback', 'steps'),
}),
]
runner = Runner(feature_name('error_traceback'), enable_subunit=True)
runner.run()
@with_setup(state.setup, state.teardown)
def test_subunit_output_with_tags():
"""
Test Subunit output with tags
"""
state.expect = [
Includes({
'status': 'success',
'tags': set(['slow-ish']),
}),
Includes({
'status': 'success',
'tags': set(['fast-ish']),
}),
Includes({
'status': 'success',
'tags': set(),
}),
Includes({
'status': 'success',
'tags': set(),
}),
]
runner = Runner(feature_name('tagged_features'), enable_subunit=True)
runner.run()
@with_setup(state.setup, state.teardown)
def test_subunit_output_unicode():
"""
Test Subunit output with unicode traceback
"""
state.expect = [
Includes({
'status': 'success',
}),
Includes({
'status': 'fail',
'details': Includes({
'traceback': ContentContains('given_my_daemi_that_blows_a_exception'),
}),
}),
]
runner = Runner(feature_name('unicode_traceback'), enable_subunit=True)
runner.run()
@with_setup(state.setup, state.teardown)
def test_subunit_output_console():
"""
Test Subunit output to console
"""
state.expect = [
Includes({
'status': 'success',
'details': Includes({
'stdout': ContentContains('Badger'),
}),
}),
Includes({
'status': 'success',
'details': Includes({
'stderr': ContentContains('Mushroom'),
}),
}),
]
runner = Runner(feature_name('writes_to_console'), enable_subunit=True)
runner.run()
@with_setup(state.setup, state.teardown)
def test_subunit_output_undefined_steps():
"""
Test Subunit output with undefined steps
"""
state.expect = [
Includes({
'status': 'fail',
'details': Includes({
'steps': ContentContains('? When this test step is undefined\n'),
}),
}),
Includes({
'status': 'fail',
'details': Includes({
'steps': ContentContains('? When this test step is undefined\n'),
}),
}),
]
runner = Runner(feature_name('undefined_steps'), enable_subunit=True)
runner.run()
| 6,375 | Python | .py | 200 | 24.44 | 86 | 0.588235 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,124 | test_file_system.py | gabrielfalcao_lettuce/tests/functional/test_file_system.py | #!/usr/bin/env python
# -*- coding: utf-8; -*-
#
# Copyright (C) 2009 Gabriel Falc√£o <[email protected]>
# Copyright (C) 2009 Bernardo Heynemann <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
from os.path import abspath, dirname, join, split, curdir
from nose.tools import assert_equals
from lettuce.fs import FileSystem
def test_abspath():
fs = FileSystem()
p = fs.abspath(".")
p2 = abspath(".")
assert p == p2
def test_relpath():
fs = FileSystem()
p = fs.relpath(join(curdir, 'other'))
p2 = join(dirname(curdir), 'other')
assert_equals(p, p2)
def test_current_dir_with_join():
fs = FileSystem()
got = fs.current_dir("etc")
expected = join(abspath("."), "etc")
assert_equals(got, expected)
def test_current_dir_without_join():
fs = FileSystem()
got = fs.current_dir()
expected = abspath(".")
assert_equals(got, expected)
def test_join():
fs = FileSystem()
p = fs.join(fs.abspath("."), "test")
p2 = join(abspath("."), "test")
assert p == p2, "Expected:\n%r\nGot:\n%r" % (p2, p)
def test_dirname():
fs = FileSystem()
p = fs.dirname(fs.abspath("."))
p2 = dirname(abspath("."))
assert p == p2, "Expected:\n%r\nGot:\n%r" % (p2, p)
def test_recursive_locate():
fs = FileSystem()
files = fs.locate(path=abspath(join(dirname(__file__), "files_to_locate")), match="*.txt", recursive=True)
assert files
assert isinstance(files, list)
assert len(files) == 2
assert split(files[0])[-1] == "test.txt"
assert split(files[1])[-1] == "test2.txt"
assert split(split(files[1])[0])[-1] == "sub"
def test_non_recursive_locate():
fs = FileSystem()
files = fs.locate(path=abspath(join(dirname(__file__), "files_to_locate")), match="*.txt", recursive=False)
assert files
assert isinstance(files, list)
assert len(files) == 1
assert split(files[0])[-1] == "test.txt"
def test_open_non_abspath():
fs = FileSystem()
assert fs.open('tests/functional/data/some.txt', 'r').read() == 'some text here!\n'
def test_open_abspath():
fs = FileSystem()
assert fs.open(abspath('./tests/functional/data/some.txt'), 'r').read() == 'some text here!\n'
def test_open_raw_non_abspath():
fs = FileSystem()
assert fs.open_raw('tests/functional/data/some.txt', 'r').read() == 'some text here!\n'
def test_open_raw_abspath():
fs = FileSystem()
assert fs.open_raw(abspath('./tests/functional/data/some.txt'), 'r').read() == 'some text here!\n'
| 3,189 | Python | .py | 81 | 35.839506 | 111 | 0.672174 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,125 | test_runner.py | gabrielfalcao_lettuce/tests/functional/test_runner.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import random
import lettuce
from mock import Mock, patch
from sure import expect
from StringIO import StringIO
from os.path import dirname, join, abspath
from inspect import currentframe
from nose.tools import assert_equals, with_setup, assert_raises
from lettuce.fs import FeatureLoader
from lettuce.core import Feature, fs, StepDefinition
from lettuce.exceptions import LettuceRunnerError
from lettuce.terrain import world
from lettuce import Runner
from tests.asserts import assert_lines
from tests.asserts import prepare_stderr
from tests.asserts import prepare_stdout
from tests.asserts import assert_stderr_lines
from tests.asserts import assert_stdout_lines
from tests.asserts import assert_stderr_lines_with_traceback
from tests.asserts import assert_stdout_lines_with_traceback
current_dir = abspath(dirname(__file__))
lettuce_dir = abspath(dirname(lettuce.__file__))
ojoin = lambda *x: join(current_dir, 'output_features', *x)
sjoin = lambda *x: join(current_dir, 'syntax_features', *x)
tjoin = lambda *x: join(current_dir, 'tag_features', *x)
bjoin = lambda *x: join(current_dir, 'bg_features', *x)
lettuce_path = lambda *x: fs.relpath(join(lettuce_dir, *x))
call_line = StepDefinition.__call__.im_func.func_code.co_firstlineno + 5
def joiner(callback, name):
return callback(name, "%s.feature" % name)
feature_name = lambda name: joiner(ojoin, name)
syntax_feature_name = lambda name: joiner(sjoin, name)
tag_feature_name = lambda name: joiner(tjoin, name)
bg_feature_name = lambda name: joiner(bjoin, name)
@with_setup(prepare_stderr)
def test_try_to_import_terrain():
"Runner tries to import terrain, but has a nice output when it fail"
sandbox_path = ojoin('..', 'sandbox')
original_path = abspath(".")
os.chdir(sandbox_path)
try:
import lettuce
reload(lettuce)
raise AssertionError('The runner should raise ImportError !')
except LettuceRunnerError:
assert_stderr_lines_with_traceback(
'Lettuce has tried to load the conventional environment module '
'"terrain"\nbut it has errors, check its contents and '
'try to run lettuce again.\n\nOriginal traceback below:\n\n'
"Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line 44, in <module>\n'
' terrain = fs.FileSystem._import("terrain")\n'
' File "%(lettuce_fs_file)s", line 63, in _import\n'
' module = imp.load_module(name, fp, pathname, description)\n'
' File "%(terrain_file)s", line 18\n'
' it is here just to cause a syntax error\n'
" ^\n"
'SyntaxError: invalid syntax\n' % {
'lettuce_core_file': abspath(join(lettuce_dir, '__init__.py')),
'lettuce_fs_file': abspath(join(lettuce_dir, 'fs.py')),
'terrain_file': abspath(lettuce_path('..', 'tests', 'functional', 'sandbox', 'terrain.py')),
}
)
finally:
os.chdir(original_path)
def test_feature_representation_without_colors():
"Feature represented without colors"
feature_file = ojoin('..', 'simple_features', '1st_feature_dir', 'some.feature')
feature = Feature.from_file(feature_file)
assert_lines(
feature.represented(),
"Feature: Addition # tests/functional/simple_features/1st_feature_dir/some.feature:5\n"
" In order to avoid silly mistakes # tests/functional/simple_features/1st_feature_dir/some.feature:6\n"
" As a math idiot # tests/functional/simple_features/1st_feature_dir/some.feature:7\n"
" I want to be told the sum of two numbers # tests/functional/simple_features/1st_feature_dir/some.feature:8\n"
)
def test_scenario_outline_representation_without_colors():
"Scenario Outline represented without colors"
feature_file = ojoin('..', 'simple_features', '1st_feature_dir', 'some.feature')
feature = Feature.from_file(feature_file)
assert_equals(
feature.scenarios[0].represented(),
" Scenario Outline: Add two numbers # tests/functional/simple_features/1st_feature_dir/some.feature:10\n"
)
def test_scenario_representation_without_colors():
"Scenario represented without colors"
feature_file = ojoin('runner_features', 'first.feature')
feature = Feature.from_file(feature_file)
assert_equals(
feature.scenarios[0].represented(),
" Scenario: Do nothing # tests/functional/output_features/runner_features/first.feature:6\n"
)
def test_undefined_step_represent_string():
"Undefined step represented without colors"
feature_file = ojoin('runner_features', 'first.feature')
feature = Feature.from_file(feature_file)
step = feature.scenarios[0].steps[0]
assert_equals(
step.represent_string(step.sentence),
" Given I do nothing # tests/functional/output_features/runner_features/first.feature:7\n"
)
assert_equals(
step.represent_string("foo bar"),
" foo bar # tests/functional/output_features/runner_features/first.feature:7\n"
)
def test_defined_step_represent_string():
"Defined step represented without colors"
feature_file = ojoin('runner_features', 'first.feature')
feature_dir = ojoin('runner_features')
loader = FeatureLoader(feature_dir)
world._output = StringIO()
world._is_colored = False
loader.find_and_load_step_definitions()
feature = Feature.from_file(feature_file)
step = feature.scenarios[0].steps[0]
step.run(True)
assert_equals(
step.represent_string(step.sentence),
" Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n"
)
@with_setup(prepare_stdout)
def test_output_with_success_colorless2():
"Testing the colorless output of a successful feature"
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'runner_features'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
"\n"
"Feature: Dumb feature # tests/functional/output_features/runner_features/first.feature:1\n"
" In order to test success # tests/functional/output_features/runner_features/first.feature:2\n"
" As a programmer # tests/functional/output_features/runner_features/first.feature:3\n"
" I want to see that the output is green # tests/functional/output_features/runner_features/first.feature:4\n"
"\n"
" Scenario: Do nothing # tests/functional/output_features/runner_features/first.feature:6\n"
" Given I do nothing # tests/functional/output_features/runner_features/dumb_steps.py:6\n"
"\n"
"1 feature (1 passed)\n"
"1 scenario (1 passed)\n"
"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"A feature with two scenarios should separate the two scenarios with a new line (in colorless mode)."
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
"\n"
"Feature: Dumb feature # tests/functional/output_features/many_successful_scenarios/first.feature:1\n"
" In order to test success # tests/functional/output_features/many_successful_scenarios/first.feature:2\n"
" As a programmer # tests/functional/output_features/many_successful_scenarios/first.feature:3\n"
" I want to see that the output is green # tests/functional/output_features/many_successful_scenarios/first.feature:4\n"
"\n"
" Scenario: Do nothing # tests/functional/output_features/many_successful_scenarios/first.feature:6\n"
" Given I do nothing # tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\n"
"\n"
" Scenario: Do nothing (again) # tests/functional/output_features/many_successful_scenarios/first.feature:9\n"
" Given I do nothing (again) # tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\n"
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"2 steps (2 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_with_success_colorful():
"Testing the output of a successful feature"
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'runner_features'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
"\n"
"\033[1;37mFeature: Dumb feature \033[1;30m# tests/functional/output_features/runner_features/first.feature:1\033[0m\n"
"\033[1;37m In order to test success \033[1;30m# tests/functional/output_features/runner_features/first.feature:2\033[0m\n"
"\033[1;37m As a programmer \033[1;30m# tests/functional/output_features/runner_features/first.feature:3\033[0m\n"
"\033[1;37m I want to see that the output is green \033[1;30m# tests/functional/output_features/runner_features/first.feature:4\033[0m\n"
"\n"
"\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/runner_features/first.feature:6\033[0m\n"
"\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/runner_features/dumb_steps.py:6\033[0m\n"
"\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/runner_features/dumb_steps.py:6\033[0m\n"
"\n"
"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 scenario (\033[1;32m1 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 step (\033[1;32m1 passed\033[1;37m)\033[0m\n"
)
@with_setup(prepare_stdout)
def test_output_with_success_colorful_newline():
"A feature with two scenarios should separate the two scenarios with a new line (in color mode)."
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
"\n"
"\033[1;37mFeature: Dumb feature \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:1\033[0m\n"
"\033[1;37m In order to test success \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:2\033[0m\n"
"\033[1;37m As a programmer \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:3\033[0m\n"
"\033[1;37m I want to see that the output is green \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:4\033[0m\n"
"\n"
"\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:6\033[0m\n"
"\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n"
"\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n"
"\n"
"\033[1;37m Scenario: Do nothing (again) \033[1;30m# tests/functional/output_features/many_successful_scenarios/first.feature:9\033[0m\n"
"\033[1;30m Given I do nothing (again) \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n"
"\033[A\033[1;32m Given I do nothing (again) \033[1;30m# tests/functional/output_features/many_successful_scenarios/dumb_steps.py:6\033[0m\n"
"\n"
"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
"\033[1;37m2 scenarios (\033[1;32m2 passed\033[1;37m)\033[0m\n"
"\033[1;37m2 steps (\033[1;32m2 passed\033[1;37m)\033[0m\n"
)
@with_setup(prepare_stdout)
def test_output_with_success_colorless_many_features():
"Testing the output of many successful features"
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_features'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
"\n"
"Feature: First feature, of many # tests/functional/output_features/many_successful_features/one.feature:1\n"
" In order to make lettuce more robust # tests/functional/output_features/many_successful_features/one.feature:2\n"
" As a programmer # tests/functional/output_features/many_successful_features/one.feature:3\n"
" I want to test its output on many features # tests/functional/output_features/many_successful_features/one.feature:4\n"
"\n"
" Scenario: Do nothing # tests/functional/output_features/many_successful_features/one.feature:6\n"
" Given I do nothing # tests/functional/output_features/many_successful_features/dumb_steps.py:6\n"
" Then I see that the test passes # tests/functional/output_features/many_successful_features/dumb_steps.py:8\n"
"\n"
"Feature: Second feature, of many # tests/functional/output_features/many_successful_features/two.feature:1\n"
" I just want to see it green :) # tests/functional/output_features/many_successful_features/two.feature:2\n"
"\n"
" Scenario: Do nothing # tests/functional/output_features/many_successful_features/two.feature:4\n"
" Given I do nothing # tests/functional/output_features/many_successful_features/dumb_steps.py:6\n"
" Then I see that the test passes # tests/functional/output_features/many_successful_features/dumb_steps.py:8\n"
"\n"
"2 features (2 passed)\n"
"2 scenarios (2 passed)\n"
"4 steps (4 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_with_success_colorful_many_features():
"Testing the colorful output of many successful features"
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_features'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
"\n"
"\033[1;37mFeature: First feature, of many \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:1\033[0m\n"
"\033[1;37m In order to make lettuce more robust \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:2\033[0m\n"
"\033[1;37m As a programmer \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:3\033[0m\n"
"\033[1;37m I want to test its output on many features \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:4\033[0m\n"
"\n"
"\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/many_successful_features/one.feature:6\033[0m\n"
"\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n"
"\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n"
"\033[1;30m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n"
"\033[A\033[1;32m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n"
"\n"
"\033[1;37mFeature: Second feature, of many \033[1;30m# tests/functional/output_features/many_successful_features/two.feature:1\033[0m\n"
"\033[1;37m I just want to see it green :) \033[1;30m# tests/functional/output_features/many_successful_features/two.feature:2\033[0m\n"
"\n"
"\033[1;37m Scenario: Do nothing \033[1;30m# tests/functional/output_features/many_successful_features/two.feature:4\033[0m\n"
"\033[1;30m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n"
"\033[A\033[1;32m Given I do nothing \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:6\033[0m\n"
"\033[1;30m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n"
"\033[A\033[1;32m Then I see that the test passes \033[1;30m# tests/functional/output_features/many_successful_features/dumb_steps.py:8\033[0m\n"
"\n"
"\033[1;37m2 features (\033[1;32m2 passed\033[1;37m)\033[0m\n"
"\033[1;37m2 scenarios (\033[1;32m2 passed\033[1;37m)\033[0m\n"
"\033[1;37m4 steps (\033[1;32m4 passed\033[1;37m)\033[0m\n"
)
@with_setup(prepare_stdout)
def test_output_when_could_not_find_features():
"Testing the colorful output of many successful features"
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
'\033[1;31mOops!\033[0m\n'
'\033[1;37mcould not find features at \033[1;33m./%s\033[0m\n' % path
)
@with_setup(prepare_stdout)
def test_output_when_could_not_find_features_colorless():
"Testing the colorful output of many successful features colorless"
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
'Oops!\n'
'could not find features at ./%s\n' % path
)
@with_setup(prepare_stdout)
def test_output_when_could_not_find_features_verbosity_level_2():
"Testing the colorful output of many successful features colorless"
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, verbosity=2)
runner.run()
assert_stdout_lines(
'Oops!\n'
'could not find features at ./%s\n' % path
)
@with_setup(prepare_stdout)
def test_output_with_success_colorless_with_table():
"Testing the colorless output of success with table"
runner = Runner(feature_name('success_table'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
'\n'
'Feature: Table Success # tests/functional/output_features/success_table/success_table.feature:1\n'
'\n'
' Scenario: Add two numbers ♥ # tests/functional/output_features/success_table/success_table.feature:2\n'
' Given I have 0 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n'
' And that I have these items: # tests/functional/output_features/success_table/success_table_steps.py:32\n'
' | name | price |\n'
' | Porsche | 200000 |\n'
' | Ferrari | 400000 |\n'
' When I sell the "Ferrari" # tests/functional/output_features/success_table/success_table_steps.py:42\n'
' Then I have 400000 bucks # tests/functional/output_features/success_table/success_table_steps.py:28\n'
' And my garage contains: # tests/functional/output_features/success_table/success_table_steps.py:47\n'
' | name | price |\n'
' | Porsche | 200000 |\n'
'\n'
'1 feature (1 passed)\n'
'1 scenario (1 passed)\n'
'5 steps (5 passed)\n'
)
@with_setup(prepare_stdout)
def test_output_with_success_colorful_with_table():
"Testing the colorful output of success with table"
runner = Runner(feature_name('success_table'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
'\n'
'\033[1;37mFeature: Table Success \033[1;30m# tests/functional/output_features/success_table/success_table.feature:1\033[0m\n'
'\n'
'\033[1;37m Scenario: Add two numbers ♥ \033[1;30m# tests/functional/output_features/success_table/success_table.feature:2\033[0m\n'
'\033[1;30m Given I have 0 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n'
'\033[A\033[1;32m Given I have 0 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n'
'\033[1;30m And that I have these items: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:32\033[0m\n'
'\033[1;30m \033[1;37m |\033[1;30m name \033[1;37m |\033[1;30m price \033[1;37m |\033[1;30m\033[0m\n'
'\033[1;30m \033[1;37m |\033[1;30m Porsche\033[1;37m |\033[1;30m 200000\033[1;37m |\033[1;30m\033[0m\n'
'\033[1;30m \033[1;37m |\033[1;30m Ferrari\033[1;37m |\033[1;30m 400000\033[1;37m |\033[1;30m\033[0m\n'
'\033[A\033[A\033[A\033[A\033[1;32m And that I have these items: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:32\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m name \033[1;37m |\033[1;32m price \033[1;37m |\033[1;32m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m Porsche\033[1;37m |\033[1;32m 200000\033[1;37m |\033[1;32m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m Ferrari\033[1;37m |\033[1;32m 400000\033[1;37m |\033[1;32m\033[0m\n'
'\033[1;30m When I sell the "Ferrari" \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:42\033[0m\n'
'\033[A\033[1;32m When I sell the "Ferrari" \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:42\033[0m\n'
'\033[1;30m Then I have 400000 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n'
'\033[A\033[1;32m Then I have 400000 bucks \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:28\033[0m\n'
'\033[1;30m And my garage contains: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:47\033[0m\n'
'\033[1;30m \033[1;37m |\033[1;30m name \033[1;37m |\033[1;30m price \033[1;37m |\033[1;30m\033[0m\n'
'\033[1;30m \033[1;37m |\033[1;30m Porsche\033[1;37m |\033[1;30m 200000\033[1;37m |\033[1;30m\033[0m\n'
'\033[A\033[A\033[A\033[1;32m And my garage contains: \033[1;30m# tests/functional/output_features/success_table/success_table_steps.py:47\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m name \033[1;37m |\033[1;32m price \033[1;37m |\033[1;32m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m Porsche\033[1;37m |\033[1;32m 200000\033[1;37m |\033[1;32m\033[0m\n'
'\n'
"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 scenario (\033[1;32m1 passed\033[1;37m)\033[0m\n"
"\033[1;37m5 steps (\033[1;32m5 passed\033[1;37m)\033[0m\n"
)
@with_setup(prepare_stdout)
def test_output_with_failed_colorless_with_table():
"Testing the colorless output of failed with table"
runner = Runner(feature_name('failed_table'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines_with_traceback(
("\n"
"Feature: Table Fail # tests/functional/output_features/failed_table/failed_table.feature:1\n"
"\n"
" Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n"
u" Given I have a dumb step that passes ♥ # tests/functional/output_features/failed_table/failed_table_steps.py:20\n"
" And this one fails # tests/functional/output_features/failed_table/failed_table_steps.py:24\n"
" Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 25, in tof\n'
" assert False\n"
" AssertionError\n"
" Then this one will be skipped # tests/functional/output_features/failed_table/failed_table_steps.py:28\n"
" And this one will be skipped # tests/functional/output_features/failed_table/failed_table_steps.py:28\n"
" And this one does not even has definition # tests/functional/output_features/failed_table/failed_table.feature:12 (undefined)\n"
"\n"
"1 feature (0 passed)\n"
"1 scenario (0 passed)\n"
"5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\n"
"\n"
"You can implement step definitions for undefined steps with these snippets:\n"
"\n"
"# -*- coding: utf-8 -*-\n"
"from lettuce import step\n"
"\n"
"@step(u'And this one does not even has definition')\n"
"def and_this_one_does_not_even_has_definition(step):\n"
" assert False, 'This step must be implemented'\n"
"\n"
"List of failed scenarios:\n"
" Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n"
"\n") % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_with_failed_colorful_with_table():
"Testing the colorful output of failed with table"
runner = Runner(feature_name('failed_table'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines_with_traceback(
"\n"
"\033[1;37mFeature: Table Fail \033[1;30m# tests/functional/output_features/failed_table/failed_table.feature:1\033[0m\n"
"\n"
"\033[1;37m Scenario: See it fail \033[1;30m# tests/functional/output_features/failed_table/failed_table.feature:2\033[0m\n"
u"\033[1;30m Given I have a dumb step that passes ♥ \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:20\033[0m\n"
u"\033[A\033[1;32m Given I have a dumb step that passes ♥ \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:20\033[0m\n"
"\033[1;30m And this one fails \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:24\033[0m\n"
"\033[A\033[0;31m And this one fails \033[1;41;33m# tests/functional/output_features/failed_table/failed_table_steps.py:24\033[0m\n"
"\033[1;31m Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 25, in tof\n'
" assert False\n"
" AssertionError\033[0m\n"
"\033[1;30m Then this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n"
"\033[A\033[0;36m Then this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n"
"\033[1;30m And this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n"
"\033[A\033[0;36m And this one will be skipped \033[1;30m# tests/functional/output_features/failed_table/failed_table_steps.py:28\033[0m\n"
"\033[0;33m And this one does not even has definition \033[1;30m# tests/functional/output_features/failed_table/failed_table.feature:12\033[0m\n"
"\n"
"\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 scenario (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m5 steps (\033[0;31m1 failed\033[1;37m, \033[0;36m2 skipped\033[1;37m, \033[0;33m1 undefined\033[1;37m, \033[1;32m1 passed\033[1;37m)\033[0m\n"
"\n"
"\033[0;33mYou can implement step definitions for undefined steps with these snippets:\n"
"\n"
"# -*- coding: utf-8 -*-\n"
"from lettuce import step\n"
"\n"
"@step(u'And this one does not even has definition')\n"
"def and_this_one_does_not_even_has_definition(step):\n"
" assert False, 'This step must be implemented'\033[0m"
"\n"
"\n"
"\033[1;31mList of failed scenarios:\n"
"\033[0;31m Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n"
"\033[0m\n" % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_with_successful_outline_colorless():
"With colorless output, a successful outline scenario should print beautifully."
runner = Runner(feature_name('success_outline'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
'\n'
'Feature: Successful Scenario Outline # tests/functional/output_features/success_outline/success_outline.feature:1\n'
' As lettuce author # tests/functional/output_features/success_outline/success_outline.feature:2\n'
' In order to finish the first release # tests/functional/output_features/success_outline/success_outline.feature:3\n'
u' I want to make scenario outlines work ♥ # tests/functional/output_features/success_outline/success_outline.feature:4\n'
'\n'
' Scenario Outline: fill a web form # tests/functional/output_features/success_outline/success_outline.feature:6\n'
' Given I open browser at "http://www.my-website.com/" # tests/functional/output_features/success_outline/success_outline_steps.py:21\n'
' And click on "sign-up" # tests/functional/output_features/success_outline/success_outline_steps.py:25\n'
' When I fill the field "username" with "<username>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n'
' And I fill the field "password" with "<password>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n'
' And I fill the field "password-confirm" with "<password>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n'
' And I fill the field "email" with "<email>" # tests/functional/output_features/success_outline/success_outline_steps.py:29\n'
' And I click "done" # tests/functional/output_features/success_outline/success_outline_steps.py:33\n'
' Then I see the title of the page is "<title>" # tests/functional/output_features/success_outline/success_outline_steps.py:37\n'
'\n'
' Examples:\n'
' | username | password | email | title |\n'
' | john | doe-1234 | [email protected] | John \| My Website |\n'
' | mary | wee-9876 | [email protected] | Mary \| My Website |\n'
' | foo | foo-bar | [email protected] | Foo \| My Website |\n'
'\n'
'1 feature (1 passed)\n'
'3 scenarios (3 passed)\n'
'24 steps (24 passed)\n'
)
@with_setup(prepare_stdout)
def test_output_with_successful_outline_colorful():
"With colored output, a successful outline scenario should print beautifully."
runner = Runner(feature_name('success_outline'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines_with_traceback(
'\n'
'\033[1;37mFeature: Successful Scenario Outline \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:1\033[0m\n'
'\033[1;37m As lettuce author \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:2\033[0m\n'
'\033[1;37m In order to finish the first release \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:3\033[0m\n'
u'\033[1;37m I want to make scenario outlines work ♥ \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:4\033[0m\n'
'\n'
'\033[1;37m Scenario Outline: fill a web form \033[1;30m# tests/functional/output_features/success_outline/success_outline.feature:6\033[0m\n'
'\033[0;36m Given I open browser at "http://www.my-website.com/" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:21\033[0m\n'
'\033[0;36m And click on "sign-up" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:25\033[0m\n'
'\033[0;36m When I fill the field "username" with "<username>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n'
'\033[0;36m And I fill the field "password" with "<password>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n'
'\033[0;36m And I fill the field "password-confirm" with "<password>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n'
'\033[0;36m And I fill the field "email" with "<email>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:29\033[0m\n'
'\033[0;36m And I click "done" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:33\033[0m\n'
'\033[0;36m Then I see the title of the page is "<title>" \033[1;30m# tests/functional/output_features/success_outline/success_outline_steps.py:37\033[0m\n'
'\n'
'\033[1;37m Examples:\033[0m\n'
'\033[0;36m \033[1;37m |\033[0;36m username\033[1;37m |\033[0;36m password\033[1;37m |\033[0;36m email \033[1;37m |\033[0;36m title \033[1;37m |\033[0;36m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m john \033[1;37m |\033[1;32m doe-1234\033[1;37m |\033[1;32m [email protected]\033[1;37m |\033[1;32m John \| My Website\033[1;37m |\033[1;32m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m mary \033[1;37m |\033[1;32m wee-9876\033[1;37m |\033[1;32m [email protected]\033[1;37m |\033[1;32m Mary \| My Website\033[1;37m |\033[1;32m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m foo \033[1;37m |\033[1;32m foo-bar \033[1;37m |\033[1;32m [email protected] \033[1;37m |\033[1;32m Foo \| My Website \033[1;37m |\033[1;32m\033[0m\n'
'\n'
"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
"\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n"
"\033[1;37m24 steps (\033[1;32m24 passed\033[1;37m)\033[0m\n"
)
@with_setup(prepare_stdout)
def test_output_with_failful_outline_colorless():
"With colorless output, an unsuccessful outline scenario should print beautifully."
runner = Runner(feature_name('fail_outline'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines_with_traceback(
'\n'
'Feature: Failful Scenario Outline # tests/functional/output_features/fail_outline/fail_outline.feature:1\n'
' As lettuce author # tests/functional/output_features/fail_outline/fail_outline.feature:2\n'
' In order to finish the first release # tests/functional/output_features/fail_outline/fail_outline.feature:3\n'
u' I want to make scenario outlines work ♥ # tests/functional/output_features/fail_outline/fail_outline.feature:4\n'
'\n'
' Scenario Outline: fill a web form # tests/functional/output_features/fail_outline/fail_outline.feature:6\n'
' Given I open browser at "http://www.my-website.com/" # tests/functional/output_features/fail_outline/fail_outline_steps.py:21\n'
' And click on "sign-up" # tests/functional/output_features/fail_outline/fail_outline_steps.py:25\n'
' When I fill the field "username" with "<username>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n'
' And I fill the field "password" with "<password>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n'
' And I fill the field "password-confirm" with "<password>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n'
' And I fill the field "email" with "<email>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:29\n'
' And I click "done" # tests/functional/output_features/fail_outline/fail_outline_steps.py:33\n'
' Then I see the message "<message>" # tests/functional/output_features/fail_outline/fail_outline_steps.py:37\n'
'\n'
' Examples:\n'
' | username | password | email | message |\n'
' | john | doe-1234 | [email protected] | Welcome, John |\n'
' | mary | wee-9876 | [email protected] | Welcome, Mary |\n'
" Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 30, in when_i_fill_the_field_x_with_y\n'
" if field == 'password' and value == 'wee-9876': assert False\n"
" AssertionError\n"
' | foo | foo-bar | [email protected] | Welcome, Foo |\n'
'\n'
'1 feature (0 passed)\n'
'3 scenarios (2 passed)\n'
'24 steps (1 failed, 4 skipped, 19 passed)\n'
'\n'
'List of failed scenarios:\n'
' Scenario Outline: fill a web form # tests/functional/output_features/fail_outline/fail_outline.feature:6\n'
'\n' % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'fail_outline', 'fail_outline_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_with_failful_outline_colorful():
"With colored output, an unsuccessful outline scenario should print beautifully."
runner = Runner(feature_name('fail_outline'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines_with_traceback(
'\n'
'\033[1;37mFeature: Failful Scenario Outline \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:1\033[0m\n'
'\033[1;37m As lettuce author \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:2\033[0m\n'
'\033[1;37m In order to finish the first release \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:3\033[0m\n'
u'\033[1;37m I want to make scenario outlines work ♥ \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:4\033[0m\n'
'\n'
'\033[1;37m Scenario Outline: fill a web form \033[1;30m# tests/functional/output_features/fail_outline/fail_outline.feature:6\033[0m\n'
'\033[0;36m Given I open browser at "http://www.my-website.com/" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:21\033[0m\n'
'\033[0;36m And click on "sign-up" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:25\033[0m\n'
'\033[0;36m When I fill the field "username" with "<username>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n'
'\033[0;36m And I fill the field "password" with "<password>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n'
'\033[0;36m And I fill the field "password-confirm" with "<password>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n'
'\033[0;36m And I fill the field "email" with "<email>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:29\033[0m\n'
'\033[0;36m And I click "done" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:33\033[0m\n'
'\033[0;36m Then I see the message "<message>" \033[1;30m# tests/functional/output_features/fail_outline/fail_outline_steps.py:37\033[0m\n'
'\n'
'\033[1;37m Examples:\033[0m\n'
'\033[0;36m \033[1;37m |\033[0;36m username\033[1;37m |\033[0;36m password\033[1;37m |\033[0;36m email \033[1;37m |\033[0;36m message \033[1;37m |\033[0;36m\033[0m\n'
'\033[1;32m \033[1;37m |\033[1;32m john \033[1;37m |\033[1;32m doe-1234\033[1;37m |\033[1;32m [email protected]\033[1;37m |\033[1;32m Welcome, John\033[1;37m |\033[1;32m\033[0m\n'
'\033[1;31m \033[1;37m |\033[0;31m mary \033[1;37m |\033[0;31m wee-9876\033[1;37m |\033[0;31m [email protected]\033[1;37m |\033[0;31m Welcome, Mary\033[1;37m |\033[0;31m\033[0m\n'
"\033[1;31m Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 30, in when_i_fill_the_field_x_with_y\n'
" if field == 'password' and value == 'wee-9876': assert False\n"
" AssertionError\033[0m\n"
'\033[1;32m \033[1;37m |\033[1;32m foo \033[1;37m |\033[1;32m foo-bar \033[1;37m |\033[1;32m [email protected] \033[1;37m |\033[1;32m Welcome, Foo \033[1;37m |\033[1;32m\033[0m\n'
'\n'
"\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m3 scenarios (\033[1;32m2 passed\033[1;37m)\033[0m\n"
"\033[1;37m24 steps (\033[0;31m1 failed\033[1;37m, \033[0;36m4 skipped\033[1;37m, \033[1;32m19 passed\033[1;37m)\033[0m\n"
"\n"
"\033[1;31mList of failed scenarios:\n"
"\033[0;31m Scenario Outline: fill a web form # tests/functional/output_features/fail_outline/fail_outline.feature:6\n"
"\033[0m\n" % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'fail_outline', 'fail_outline_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_snippets_with_groups_within_double_quotes_colorless():
"Testing that the proposed snippet is clever enough to identify groups within double quotes. colorless"
runner = Runner(feature_name('double-quoted-snippet'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Feature: double-quoted snippet proposal # tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:1\n'
u'\n'
u' Scenario: Propose matched groups # tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:2\n'
u' Given I have "stuff here" and "more @#$%ˆ& bizar sutff h3r3" # tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:3 (undefined)\n'
u'\n'
u'1 feature (0 passed)\n'
u'1 scenario (0 passed)\n'
u'1 step (1 undefined, 0 passed)\n'
u'\n'
u'You can implement step definitions for undefined steps with these snippets:\n'
u'\n'
u"# -*- coding: utf-8 -*-\n"
u'from lettuce import step\n'
u'\n'
u'@step(u\'Given I have "([^\"]*)" and "([^\"]*)"\')\n'
u'def given_i_have_group1_and_group2(step, group1, group2):\n'
u' assert False, \'This step must be implemented\'\n'
)
@with_setup(prepare_stdout)
def test_output_snippets_with_groups_within_double_quotes_colorful():
"Testing that the proposed snippet is clever enough to identify groups within double quotes. colorful"
runner = Runner(feature_name('double-quoted-snippet'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u'\033[1;37mFeature: double-quoted snippet proposal \033[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:1\033[0m\n'
u'\n'
u'\033[1;37m Scenario: Propose matched groups \033[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:2\033[0m\n'
u'\033[0;33m Given I have "stuff here" and "more @#$%ˆ& bizar sutff h3r3" \033[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:3\033[0m\n'
u'\n'
"\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 scenario (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 step (\033[0;33m1 undefined\033[1;37m, \033[1;32m0 passed\033[1;37m)\033[0m\n"
u'\n'
u'\033[0;33mYou can implement step definitions for undefined steps with these snippets:\n'
u'\n'
u"# -*- coding: utf-8 -*-\n"
u'from lettuce import step\n'
u'\n'
u'@step(u\'Given I have "([^"]*)" and "([^"]*)"\')\n'
u'def given_i_have_group1_and_group2(step, group1, group2):\n'
u' assert False, \'This step must be implemented\'\033[0m\n'
)
@with_setup(prepare_stdout)
def test_output_snippets_with_groups_within_single_quotes_colorless():
"Testing that the proposed snippet is clever enough to identify groups within single quotes. colorless"
runner = Runner(feature_name('single-quoted-snippet'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Feature: single-quoted snippet proposal # tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:1\n'
u'\n'
u' Scenario: Propose matched groups # tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:2\n'
u' Given I have \'stuff here\' and \'more @#$%ˆ& bizar sutff h3r3\' # tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:3 (undefined)\n'
u'\n'
u'1 feature (0 passed)\n'
u'1 scenario (0 passed)\n'
u'1 step (1 undefined, 0 passed)\n'
u'\n'
u'You can implement step definitions for undefined steps with these snippets:\n'
u'\n'
u"# -*- coding: utf-8 -*-\n"
u'from lettuce import step\n'
u'\n'
u'@step(u\'Given I have \\\'([^\\\']*)\\\' and \\\'([^\\\']*)\\\'\')\n'
u'def given_i_have_group1_and_group2(step, group1, group2):\n'
u' assert False, \'This step must be implemented\'\n'
)
@with_setup(prepare_stdout)
def test_output_snippets_with_groups_within_single_quotes_colorful():
"Testing that the proposed snippet is clever enough to identify groups within single quotes. colorful"
runner = Runner(feature_name('single-quoted-snippet'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u'\033[1;37mFeature: single-quoted snippet proposal \033[1;30m# tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:1\033[0m\n'
u'\n'
u'\033[1;37m Scenario: Propose matched groups \033[1;30m# tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:2\033[0m\n'
u'\033[0;33m Given I have \'stuff here\' and \'more @#$%ˆ& bizar sutff h3r3\' \033[1;30m# tests/functional/output_features/single-quoted-snippet/single-quoted-snippet.feature:3\033[0m\n'
u'\n'
"\033[1;37m1 feature (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 scenario (\033[0;31m0 passed\033[1;37m)\033[0m\n"
"\033[1;37m1 step (\033[0;33m1 undefined\033[1;37m, \033[1;32m0 passed\033[1;37m)\033[0m\n"
u'\n'
u'\033[0;33mYou can implement step definitions for undefined steps with these snippets:\n'
u'\n'
u"# -*- coding: utf-8 -*-\n"
u'from lettuce import step\n'
u'\n'
u'@step(u\'Given I have \\\'([^\\\']*)\\\' and \\\'([^\\\']*)\\\'\')\n'
u'def given_i_have_group1_and_group2(step, group1, group2):\n'
u' assert False, \'This step must be implemented\'\033[0m\n'
)
@with_setup(prepare_stdout)
def test_output_snippets_with_groups_within_redundant_quotes():
"Testing that the proposed snippet is clever enough to avoid duplicating the same snippet"
runner = Runner(feature_name('redundant-steps-quotes'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Feature: avoid duplicating same snippet # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:1\n'
u'\n'
u' Scenario: Propose matched groups # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:2\n'
u' Given I have "stuff here" and "more @#$%ˆ& bizar sutff h3r3" # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:3 (undefined)\n'
u' Given I have "blablabla" and "12345" # tests/functional/output_features/redundant-steps-quotes/redundant-steps-quotes.feature:4 (undefined)\n'
u'\n'
u'1 feature (0 passed)\n'
u'1 scenario (0 passed)\n'
u'2 steps (2 undefined, 0 passed)\n'
u'\n'
u'You can implement step definitions for undefined steps with these snippets:\n'
u'\n'
u"# -*- coding: utf-8 -*-\n"
u'from lettuce import step\n'
u'\n'
u'@step(u\'Given I have "([^"]*)" and "([^"]*)"\')\n'
u'def given_i_have_group1_and_group2(step, group1, group2):\n'
u' assert False, \'This step must be implemented\'\n'
)
@with_setup(prepare_stdout)
def test_output_snippets_with_normalized_unicode_names():
"Testing that the proposed snippet is clever enough normalize method names even with latin accents"
runner = Runner(feature_name('latin-accents'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"Funcionalidade: melhorar o output de snippets do lettuce # tests/functional/output_features/latin-accents/latin-accents.feature:2\n"
u" Como autor do lettuce # tests/functional/output_features/latin-accents/latin-accents.feature:3\n"
u" Eu quero ter um output refinado de snippets # tests/functional/output_features/latin-accents/latin-accents.feature:4\n"
u" Para melhorar, de uma forma geral, a vida do programador # tests/functional/output_features/latin-accents/latin-accents.feature:5\n"
u"\n"
u" Cenário: normalizar snippets com unicode # tests/functional/output_features/latin-accents/latin-accents.feature:7\n"
u" Dado que eu tenho palavrões e outras situações # tests/functional/output_features/latin-accents/latin-accents.feature:8 (undefined)\n"
u" E várias palavras acentuadas são úteis, tais como: \"(é,não,léo,chororó,chácara,epígrafo)\" # tests/functional/output_features/latin-accents/latin-accents.feature:9 (undefined)\n"
u" Então eu fico felizão # tests/functional/output_features/latin-accents/latin-accents.feature:10 (undefined)\n"
u"\n"
u"1 feature (0 passed)\n"
u"1 scenario (0 passed)\n"
u"3 steps (3 undefined, 0 passed)\n"
u"\n"
u"You can implement step definitions for undefined steps with these snippets:\n"
u"\n"
u"# -*- coding: utf-8 -*-\n"
u"from lettuce import step\n"
u"\n"
u"@step(u'Dado que eu tenho palavrões e outras situações')\n"
u"def dado_que_eu_tenho_palavroes_e_outras_situacoes(step):\n"
u" assert False, 'This step must be implemented'\n"
u"@step(u'E várias palavras acentuadas são úteis, tais como: \"([^\"]*)\"')\n"
u"def e_varias_palavras_acentuadas_sao_uteis_tais_como_group1(step, group1):\n"
u" assert False, 'This step must be implemented'\n"
u"@step(u'Então eu fico felizão')\n"
u"def entao_eu_fico_felizao(step):\n"
u" assert False, 'This step must be implemented'\n"
)
@with_setup(prepare_stdout)
def test_output_level_2_success():
'Output with verbosity 2 must show only the scenario names, followed by "... OK" in case of success'
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=2)
runner.run()
assert_stdout_lines(
"Do nothing ... OK\n"
"Do nothing (again) ... OK\n"
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"2 steps (2 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_level_2_fail():
'Output with verbosity 2 must show only the scenario names, followed by "... FAILED" in case of fail'
runner = Runner(feature_name('failed_table'), verbosity=2)
runner.run()
assert_stdout_lines_with_traceback(
"See it fail ... FAILED\n"
"\n"
"\n"
"<Step: \"And this one fails\">\n"
"Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 25, in tof\n'
" assert False\n"
"AssertionError\n"
"\n"
"1 feature (0 passed)\n"
"1 scenario (0 passed)\n"
"5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\n"
"\n"
"List of failed scenarios:\n"
" Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n"
"\n" % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_level_2_error():
'Output with verbosity 2 must show only the scenario names, followed by "... ERROR" in case of fail'
runner = Runner(feature_name('error_traceback'), verbosity=2)
runner.run()
assert_stdout_lines_with_traceback(
"It should pass ... OK\n"
"It should raise an exception different of AssertionError ... ERROR\n"
"\n"
"\n"
"<Step: \"Given my step that blows a exception\">\n"
"Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 10, in given_my_step_that_blows_a_exception\n'
" raise RuntimeError\n"
"RuntimeError\n"
"\n"
"1 feature (0 passed)\n"
"2 scenarios (1 passed)\n"
"2 steps (1 failed, 1 passed)\n"
"\n"
"List of failed scenarios:\n"
" Scenario: It should raise an exception different of AssertionError # tests/functional/output_features/error_traceback/error_traceback.feature:5\n"
"\n" % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'error_traceback', 'error_traceback_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_level_1_success():
'Output with verbosity 2 must show only the scenario names, followed by "... OK" in case of success'
runner = Runner(join(abspath(dirname(__file__)), 'output_features', 'many_successful_scenarios'), verbosity=1)
runner.run()
assert_stdout_lines(
".."
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"2 steps (2 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_level_1_fail():
'Output with verbosity 2 must show only the scenario names, followed by "... FAILED" in case of fail'
runner = Runner(feature_name('failed_table'), verbosity=1)
runner.run()
assert_stdout_lines_with_traceback(
"F\n"
"\n"
"<Step: \"And this one fails\">\n"
"Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 25, in tof\n'
" assert False\n"
"AssertionError\n"
"\n"
"1 feature (0 passed)\n"
"1 scenario (0 passed)\n"
"5 steps (1 failed, 2 skipped, 1 undefined, 1 passed)\n"
"\n"
"List of failed scenarios:\n"
" Scenario: See it fail # tests/functional/output_features/failed_table/failed_table.feature:2\n"
"\n" % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'failed_table', 'failed_table_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_output_level_1_error():
'Output with verbosity 2 must show only the scenario names, followed by "... ERROR" in case of fail'
runner = Runner(feature_name('error_traceback'), verbosity=1)
runner.run()
assert_stdout_lines_with_traceback(
".E\n"
"\n"
"<Step: \"Given my step that blows a exception\">\n"
"Traceback (most recent call last):\n"
' File "%(lettuce_core_file)s", line %(call_line)d, in __call__\n'
" ret = self.function(self.step, *args, **kw)\n"
' File "%(step_file)s", line 10, in given_my_step_that_blows_a_exception\n'
" raise RuntimeError\n"
"RuntimeError\n"
"\n"
"1 feature (0 passed)\n"
"2 scenarios (1 passed)\n"
"2 steps (1 failed, 1 passed)\n"
"\n"
"List of failed scenarios:\n"
" Scenario: It should raise an exception different of AssertionError # tests/functional/output_features/error_traceback/error_traceback.feature:5\n"
"\n" % {
'lettuce_core_file': lettuce_path('core.py'),
'step_file': abspath(lettuce_path('..', 'tests', 'functional', 'output_features', 'error_traceback', 'error_traceback_steps.py')),
'call_line': call_line,
}
)
@with_setup(prepare_stdout)
def test_commented_scenario():
'Test one commented scenario'
runner = Runner(feature_name('commented_feature'), verbosity=1)
runner.run()
assert_stdout_lines(
"."
"\n"
"1 feature (1 passed)\n"
"1 scenario (1 passed)\n"
"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_blank_step_hash_value():
"syntax checking: Blank in step hash column = empty string"
from lettuce import step
@step('ignore step')
def ignore_step(step):
pass
@step('string length calc')
def string_lenth_calc(step):
for hash in step.hashes:
if len(hash["string"]) + len(hash["string2"]) != int(hash["length"]):
raise AssertionError("fail")
filename = syntax_feature_name('blank_values_in_hash')
runner = Runner(filename, verbosity=1)
runner.run()
assert_stdout_lines(
"."
"\n"
"1 feature (1 passed)\n"
"1 scenario (1 passed)\n"
"4 steps (4 passed)\n"
)
@with_setup(prepare_stdout)
def test_run_only_fast_tests():
"Runner can filter by tags"
from lettuce import step
good_one = Mock()
bad_one = Mock()
@step('I wait for 0 seconds')
def wait_for_0_seconds(step):
good_one(step.sentence)
@step('the time passed is 0 seconds')
def time_passed_0_sec(step):
good_one(step.sentence)
@step('I wait for 60 seconds')
def wait_for_60_seconds(step):
bad_one(step.sentence)
@step('the time passed is 1 minute')
def time_passed_1_min(step):
bad_one(step.sentence)
filename = tag_feature_name('timebound')
runner = Runner(filename, verbosity=1, tags=['fast-ish'])
runner.run()
assert_stdout_lines(
"."
"\n"
"1 feature (1 passed)\n"
"1 scenario (1 passed)\n"
"2 steps (2 passed)\n"
)
def test_run_random():
"Randomise the feature order"
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, random=True)
assert_equals(True, runner.random)
with patch.object(random, 'shuffle') as pshuffle:
runner.run()
pshuffle.assert_called_once_with([])
@with_setup(prepare_stdout)
def test_background_with_header():
"Running background with header"
from lettuce import step, world
@step(ur'the variable "(\w+)" holds (\d+)')
def set_variable(step, name, value):
setattr(world, name, int(value))
@step(ur'the variable "(\w+)" is equal to (\d+)')
def check_variable(step, name, expected):
expected = int(expected)
expect(world).to.have.property(name).being.equal(expected)
@step(ur'the variable "(\w+)" times (\d+) is equal to (\d+)')
def multiply_and_verify(step, name, times, expected):
times = int(times)
expected = int(expected)
(getattr(world, name) * times).should.equal(expected)
filename = bg_feature_name('header')
runner = Runner(filename, verbosity=1)
runner.run()
assert_stdout_lines(
".."
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"7 steps (7 passed)\n"
)
@with_setup(prepare_stdout)
def test_background_without_header():
"Running background without header"
from lettuce import step, world, before, after
actions = {}
@before.each_background
def register_background_before(background):
actions['before'] = unicode(background)
@after.each_background
def register_background_after(background, results):
actions['after'] = {
'background': unicode(background),
'results': results,
}
@step(ur'the variable "(\w+)" holds (\d+)')
def set_variable(step, name, value):
setattr(world, name, int(value))
@step(ur'the variable "(\w+)" is equal to (\d+)')
def check_variable(step, name, expected):
expected = int(expected)
expect(world).to.have.property(name).being.equal(expected)
@step(ur'the variable "(\w+)" times (\d+) is equal to (\d+)')
def multiply_and_verify(step, name, times, expected):
times = int(times)
expected = int(expected)
(getattr(world, name) * times).should.equal(expected)
filename = bg_feature_name('naked')
runner = Runner(filename, verbosity=1)
runner.run()
assert_stdout_lines(
".."
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"7 steps (7 passed)\n"
)
expect(actions).to.equal({
'after': {
'results': [True],
'background': u'<Background for feature: Without Header>'
},
'before': u'<Background for feature: Without Header>'
})
@with_setup(prepare_stdout)
def test_output_background_with_success_colorless():
"A feature with background should print it accordingly under verbosity 3"
from lettuce import step
line = currentframe().f_lineno # get line number
@step(ur'the variable "(\w+)" holds (\d+)')
@step(ur'the variable "(\w+)" is equal to (\d+)')
def just_pass(step, *args):
pass
filename = bg_feature_name('simple')
runner = Runner(filename, verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
'\n'
'Feature: Simple and successful # tests/functional/bg_features/simple/simple.feature:1\n'
' As the Lettuce maintainer # tests/functional/bg_features/simple/simple.feature:2\n'
' In order to make sure the output is pretty # tests/functional/bg_features/simple/simple.feature:3\n'
' I want to automate its test # tests/functional/bg_features/simple/simple.feature:4\n'
'\n'
' Background:\n'
' Given the variable "X" holds 2 # tests/functional/test_runner.py:{line}\n'
'\n'
' Scenario: multiplication changing the value # tests/functional/bg_features/simple/simple.feature:9\n'
' Given the variable "X" is equal to 2 # tests/functional/test_runner.py:{line}\n'
'\n'
'1 feature (1 passed)\n'
'1 scenario (1 passed)\n'
'1 step (1 passed)\n'
.format(line=line+2) # increment is line number of step past line
)
@with_setup(prepare_stdout)
def test_output_background_with_success_colorful():
"A feature with background should print it accordingly under verbosity 3 and colored output"
from lettuce import step
line = currentframe().f_lineno # get line number
@step(ur'the variable "(\w+)" holds (\d+)')
@step(ur'the variable "(\w+)" is equal to (\d+)')
def just_pass(step, *args):
pass
filename = bg_feature_name('simple')
runner = Runner(filename, verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
'\n'
'\033[1;37mFeature: Simple and successful \033[1;30m# tests/functional/bg_features/simple/simple.feature:1\033[0m\n'
'\033[1;37m As the Lettuce maintainer \033[1;30m# tests/functional/bg_features/simple/simple.feature:2\033[0m\n'
'\033[1;37m In order to make sure the output is pretty \033[1;30m# tests/functional/bg_features/simple/simple.feature:3\033[0m\n'
'\033[1;37m I want to automate its test \033[1;30m# tests/functional/bg_features/simple/simple.feature:4\033[0m\n'
'\n'
'\033[1;37m Background:\033[0m\n'
'\033[1;30m Given the variable "X" holds 2 \033[1;30m# tests/functional/test_runner.py:{line}\033[0m\n'
'\033[A\033[1;32m Given the variable "X" holds 2 \033[1;30m# tests/functional/test_runner.py:{line}\033[0m\n'
'\n'
'\033[1;37m Scenario: multiplication changing the value \033[1;30m# tests/functional/bg_features/simple/simple.feature:9\033[0m\n'
'\033[1;30m Given the variable "X" is equal to 2 \033[1;30m# tests/functional/test_runner.py:{line}\033[0m\n'
'\033[A\033[1;32m Given the variable "X" is equal to 2 \033[1;30m# tests/functional/test_runner.py:{line}\033[0m\n'
'\n'
'\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n'
'\033[1;37m1 scenario (\033[1;32m1 passed\033[1;37m)\033[0m\n'
'\033[1;37m1 step (\033[1;32m1 passed\033[1;37m)\033[0m\n'
.format(line=line+2) # increment is line number of step past line
)
@with_setup(prepare_stdout)
def test_background_with_scenario_before_hook():
"Running background with before_scenario hook"
from lettuce import step, world, before
@before.each_scenario
def reset_variable(scenario):
world.X = None
@step(ur'the variable "(\w+)" holds (\d+)')
def set_variable(step, name, value):
setattr(world, name, int(value))
@step(ur'the variable "(\w+)" is equal to (\d+)')
def check_variable(step, name, expected):
expected = int(expected)
expect(world).to.have.property(name).being.equal(expected)
@step(ur'the variable "(\w+)" times (\d+) is equal to (\d+)')
def multiply_and_verify(step, name, times, expected):
times = int(times)
expected = int(expected)
(getattr(world, name) * times).should.equal(expected)
filename = bg_feature_name('header')
runner = Runner(filename, verbosity=1)
runner.run()
assert_stdout_lines(
".."
"\n"
"1 feature (1 passed)\n"
"2 scenarios (2 passed)\n"
"7 steps (7 passed)\n"
)
@with_setup(prepare_stderr)
def test_many_features_a_file():
"syntax checking: Fail if a file has more than one feature"
filename = syntax_feature_name('many_features_a_file')
runner = Runner(filename)
assert_raises(LettuceRunnerError, runner.run)
assert_stderr_lines(
'Syntax error at: %s\n'
'A feature file must contain ONLY ONE feature!\n' % filename
)
@with_setup(prepare_stderr)
def test_feature_without_name():
"syntax checking: Fail on features without name"
filename = syntax_feature_name('feature_without_name')
runner = Runner(filename)
assert_raises(LettuceRunnerError, runner.run)
assert_stderr_lines(
'Syntax error at: %s\n'
'Features must have a name. e.g: "Feature: This is my name"\n'
% filename
)
@with_setup(prepare_stderr)
def test_feature_missing_scenarios():
"syntax checking: Fail on features missing scenarios"
filename = syntax_feature_name("feature_missing_scenarios")
runner = Runner(filename)
assert_raises(LettuceRunnerError, runner.run)
assert_stderr_lines(
u"Syntax error at: %s\n"
"Features must have scenarios.\nPlease refer to the documentation "
"available at http://lettuce.it for more information.\n" % filename
)
@with_setup(prepare_stdout)
def test_output_with_undefined_steps_colorful():
"With colored output, an undefined step should be printed in sequence."
runner = Runner(feature_name('undefined_steps'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines_with_traceback(
'\n'
'\x1b[1;37mFeature: Test undefined steps are displayed on console \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:1\x1b[0m\n'
'\n'
'\x1b[1;37m Scenario: Scenario with undefined step \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:3\x1b[0m\n'
'\x1b[1;30m Given this test step passes \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:4\x1b[0m\n'
'\x1b[A\x1b[1;32m Given this test step passes \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:4\x1b[0m\n'
'\x1b[0;33m When this test step is undefined \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:5\x1b[0m\n'
'\n'
'\x1b[1;37m Scenario Outline: Outline scenario with general undefined step \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:7\x1b[0m\n'
'\x1b[0;36m Given this test step passes \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:4\x1b[0m\n'
'\x1b[0;33m When this test step is undefined \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.feature:5\x1b[0m\n'
'\x1b[0;36m Then <in> squared is <out> \x1b[1;30m# tests/functional/output_features/undefined_steps/undefined_steps.py:8\x1b[0m\n'
'\n'
'\x1b[1;37m Examples:\x1b[0m\n'
'\x1b[0;36m \x1b[1;37m |\x1b[0;36m in\x1b[1;37m |\x1b[0;36m out\x1b[1;37m |\x1b[0;36m\x1b[0m\n'
'\x1b[1;32m \x1b[1;37m |\x1b[1;32m 1 \x1b[1;37m |\x1b[1;32m 1 \x1b[1;37m |\x1b[1;32m\x1b[0m\n'
'\x1b[1;32m \x1b[1;37m |\x1b[1;32m 2 \x1b[1;37m |\x1b[1;32m 4 \x1b[1;37m |\x1b[1;32m\x1b[0m\n'
'\n'
'\x1b[1;37m1 feature (\x1b[0;31m0 passed\x1b[1;37m)\x1b[0m\n'
'\x1b[1;37m3 scenarios (\x1b[0;31m0 passed\x1b[1;37m)\x1b[0m\n'
'\x1b[1;37m8 steps (\x1b[0;36m2 skipped\x1b[1;37m, \x1b[0;33m3 undefined\x1b[1;37m, \x1b[1;32m3 passed\x1b[1;37m)\x1b[0m\n'
'\n'
'\x1b[0;33mYou can implement step definitions for undefined steps with these snippets:\n'
'\n'
'# -*- coding: utf-8 -*-\n'
'from lettuce import step\n'
'\n'
"@step(u'When this test step is undefined')\n"
'def when_this_test_step_is_undefined(step):\n'
" assert False, 'This step must be implemented'\x1b[0m\n"
)
| 76,027 | Python | .py | 1,218 | 55.004105 | 197 | 0.628839 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,126 | test_xunit_output.py | gabrielfalcao_lettuce/tests/functional/test_xunit_output.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# REMOVE THIS
import sys
import os
import lettuce
from StringIO import StringIO
from nose.tools import assert_equals, assert_true, with_setup
from sure import expect
from lettuce import registry
from lettuce import Runner
from lettuce import xunit_output
from lxml import etree
from tests.functional.test_runner import feature_name, bg_feature_name
from tests.asserts import prepare_stdout
def assert_xsd_valid(filename, content):
xmlschema = etree.XMLSchema(etree.parse(
open('tests/functional/xunit.xsd')
))
xmlschema.assertValid(etree.parse(StringIO(content)))
@with_setup(prepare_stdout, registry.clear)
def test_xunit_output_with_no_errors():
'Test xunit output with no errors'
called = []
def assert_correct_xml(filename, content):
called.append(True)
assert_xsd_valid(filename, content)
root = etree.fromstring(content)
assert_equals(root.get("tests"), "1")
assert_equals(len(root.getchildren()), 1)
assert_equals(root.find("testcase").get("name"), "Given I do nothing")
assert_true(float(root.find("testcase").get("time")) > 0)
old = xunit_output.wrt_output
xunit_output.wrt_output = assert_correct_xml
runner = Runner(feature_name('commented_feature'), enable_xunit=True)
runner.run()
assert_equals(1, len(called), "Function not called")
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_output_with_one_error():
'Test xunit output with one errors'
called = []
def assert_correct_xml(filename, content):
called.append(True)
assert_xsd_valid(filename, content)
root = etree.fromstring(content)
assert_equals(root.get("tests"), "2")
assert_equals(root.get("failures"), "1")
assert_equals(len(root.getchildren()), 2)
passed, failed = root.findall("testcase")
assert_equals(passed.get("name"), "Given my step that passes")
assert_true(float(passed.get("time")) > 0)
assert_equals(failed.get("name"), "Given my step that blows a exception")
assert_true(float(failed.get("time")) > 0)
assert_true(failed.find("failure") is not None)
old = xunit_output.wrt_output
xunit_output.wrt_output = assert_correct_xml
runner = Runner(feature_name('error_traceback'), enable_xunit=True)
runner.run()
assert_equals(1, len(called), "Function not called")
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_output_with_different_filename():
'Test xunit output with different filename'
called = []
def assert_correct_xml(filename, content):
called.append(True)
assert_xsd_valid(filename, content)
assert_equals(filename, "custom_filename.xml")
old = xunit_output.wrt_output
xunit_output.wrt_output = assert_correct_xml
runner = Runner(feature_name('error_traceback'), enable_xunit=True,
xunit_filename="custom_filename.xml")
runner.run()
assert_equals(1, len(called), "Function not called")
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_output_with_unicode_characters_in_error_messages():
called = []
def assert_correct_xml(filename, content):
called.append(True)
assert_xsd_valid(filename, content)
old = xunit_output.wrt_output
xunit_output.wrt_output = assert_correct_xml
runner = Runner(feature_name('unicode_traceback'), enable_xunit=True,
xunit_filename="custom_filename.xml")
runner.run()
assert_equals(1, len(called), "Function not called")
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_does_not_throw_exception_when_missing_step_definition():
def dummy_write(filename, content):
pass
old = xunit_output.wrt_output
xunit_output.wrt_output = dummy_write
runner = Runner(feature_name('missing_steps'), enable_xunit=True,
xunit_filename="mising_steps.xml")
runner.run()
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_output_with_no_steps():
'Test xunit output with no steps'
called = []
def assert_correct_xml(filename, content):
print filename
print content
called.append(True)
assert_xsd_valid(filename, content)
root = etree.fromstring(content)
assert_equals(root.get("tests"), "1")
assert_equals(root.find("testcase").get("name"), "Given I do nothing")
assert_equals(len(root.getchildren()), 1)
assert_equals(root.find("testcase/skipped").get("type"), "UndefinedStep(Given I do nothing)")
assert_equals(float(root.find("testcase").get("time")), 0)
old = xunit_output.wrt_output
xunit_output.wrt_output = assert_correct_xml
runner = Runner(feature_name('no_steps_defined'), enable_xunit=True)
runner.run()
assert_equals(1, len(called), "Function not called")
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_output_with_background_section():
'Test xunit output with a background section in the feature'
called = []
def assert_correct_xml(filename, content):
called.append(True)
assert_xsd_valid(filename, content)
root = etree.fromstring(content)
assert_equals(root.get("tests"), "1")
assert_equals(root.get("failures"), "0")
assert_equals(len(root.getchildren()), 2)
passed1, passed2 = root.findall("testcase")
assert_equals(passed1.get("name"), 'Given the variable "X" holds 2')
assert_true(float(passed1.get("time")) > 0)
assert_equals(passed2.get("name"), 'Given the variable "X" is equal to 2')
assert_true(float(passed2.get("time")) > 0)
from lettuce import step
@step(ur'the variable "(\w+)" holds (\d+)')
@step(ur'the variable "(\w+)" is equal to (\d+)')
def just_pass(step, *args):
pass
filename = bg_feature_name('simple')
old = xunit_output.wrt_output
xunit_output.wrt_output = assert_correct_xml
runner = Runner(filename, enable_xunit=True)
runner.run()
assert_equals(1, len(called), "Function not called")
xunit_output.wrt_output = old
@with_setup(prepare_stdout, registry.clear)
def test_xunit_xml_output_with_no_errors():
'Test xunit doc xml output'
called = []
def assert_correct_xml_output(filename, doc):
called.append(True)
expect(doc.toxml).when.called.doesnt.throw(UnicodeDecodeError)
old = xunit_output.write_xml_doc
xunit_output.write_xml_doc = assert_correct_xml_output
runner = Runner(feature_name('xunit_unicode_and_bytestring_mixing'), enable_xunit=True)
try:
runner.run()
finally:
xunit_output.write_xml_doc = old
| 7,702 | Python | .py | 177 | 37.80791 | 101 | 0.696974 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,127 | test_after_hooks.py | gabrielfalcao_lettuce/tests/functional/test_after_hooks.py | """Make sure after.each_step, after.outline, after.each_scenario, and
after_each feature hooks are invoked, regardless of whether a test passes.
"""
from mock import MagicMock
from lettuce import Runner, after
from nose.tools import assert_equals, assert_raises, with_setup
from os.path import dirname, join, abspath
from tests.asserts import prepare_stdout, prepare_stderr
def define_hooks(mock):
@after.each_feature
def after_each_feature(feature):
mock.after_each_feature()
@after.each_scenario
def after_each_scenario(scenario):
mock.after_each_scenario()
@after.each_step
def after_each_step(step):
mock.after_each_step()
@after.outline
def after_outline(scenario, order, outline, reasons_to_fail):
mock.after_outline()
def get_after_hook_mock():
mock = MagicMock()
mock.after_each_feature = MagicMock()
mock.after_each_scenario = MagicMock()
mock.after_each_step = MagicMock()
mock.after_outline = MagicMock()
return mock
current_dir = abspath(dirname(__file__))
ojoin = lambda *x: join(current_dir, 'output_features', *x)
def joiner(callback, name):
return callback(name, "%s.feature" % name)
feature_name = lambda name: joiner(ojoin, name)
def run_feature(feature, feature_will_fail, failfast,
after_each_feature_count, after_each_scenario_count,
after_each_step_count, after_outline_count):
mock = get_after_hook_mock()
define_hooks(mock)
runner = Runner(feature_name(feature), failfast=failfast)
if feature_will_fail:
try:
runner.run()
except:
pass
else:
runner.run()
assert_equals(mock.after_each_feature.call_count, after_each_feature_count)
assert_equals(mock.after_each_scenario.call_count, after_each_scenario_count)
assert_equals(mock.after_each_step.call_count, after_each_step_count)
assert_equals(mock.after_outline.call_count, after_outline_count)
@with_setup(prepare_stdout)
def test_success_outline():
run_feature('success_outline', False, False, 1, 1, 24, 3)
@with_setup(prepare_stdout)
def test_success_outline_failfast():
run_feature('success_outline', False, True, 1, 1, 24, 3)
@with_setup(prepare_stdout)
def test_fail_outline():
run_feature('fail_outline', True, False, 1, 1, 24, 3)
@with_setup(prepare_stdout)
def test_fail_outline_failfast():
run_feature('fail_outline', True, True, 1, 1, 12, 2)
@with_setup(prepare_stdout)
def test_success_non_outline():
run_feature('success_table', False, False, 1, 1, 5, 0)
@with_setup(prepare_stdout)
def test_success_non_outline_failfast():
run_feature('success_table', False, True, 1, 1, 5, 0)
@with_setup(prepare_stdout)
def test_fail_non_outline():
run_feature('failed_table', True, False, 1, 1, 5, 0)
@with_setup(prepare_stdout)
def test_fail_non_outline_failfast():
run_feature('failed_table', True, True, 1, 1, 2, 0)
@with_setup(prepare_stderr)
@with_setup(prepare_stdout)
def test_fail_system_exiting_non_outline():
run_feature('system_exiting_error', True, False, 1, 1, 1, 0)
@with_setup(prepare_stdout)
def test_fail_system_exiting_failfast_non_outline():
run_feature('system_exiting_error', True, True, 1, 1, 1, 0)
| 3,272 | Python | .py | 81 | 35.962963 | 81 | 0.709962 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,128 | steps.py | gabrielfalcao_lettuce/tests/functional/tag_features/steps.py | """
Blank steps file to prevent looking in parent directories
"""
| 66 | Python | .py | 3 | 21 | 57 | 0.777778 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,129 | step_one.py | gabrielfalcao_lettuce/tests/functional/simple_features/3rd_feature_dir/look/here/step_one.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
from lettuce.terrain import world
@step(r'at look/here/step_one.py')
def step_one(step):
world.step_list.append(step.sentence)
| 942 | Python | .py | 21 | 43.571429 | 71 | 0.769314 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,130 | step_three.py | gabrielfalcao_lettuce/tests/functional/simple_features/3rd_feature_dir/look/here/for_steps/step_three.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
from lettuce.terrain import world
@step(r'at look/here/for_steps/step_three.py')
def step_three(step):
world.step_list.append(step.sentence)
| 956 | Python | .py | 21 | 44.238095 | 71 | 0.770632 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,131 | step_two.py | gabrielfalcao_lettuce/tests/functional/simple_features/3rd_feature_dir/look/and_here/step_two.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
from lettuce.terrain import world
@step(r'at look/and_here/step_two.py')
def step_two(step):
world.step_list.append(step.sentence)
| 946 | Python | .py | 21 | 43.761905 | 71 | 0.769231 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,132 | step_four.py | gabrielfalcao_lettuce/tests/functional/simple_features/3rd_feature_dir/look/and_here/and_any_python_file/step_four.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
from lettuce.terrain import world
@step(r'at look/and_here/and_any_python_file/step_four.py')
def step_four(step):
world.step_list.append(step.sentence)
| 968 | Python | .py | 21 | 44.809524 | 71 | 0.77037 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,133 | terrain.py | gabrielfalcao_lettuce/tests/functional/simple_features/1st_feature_dir/terrain.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce.terrain import world
world.works_fine = True
| 844 | Python | .py | 18 | 45.777778 | 71 | 0.770631 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,134 | sum_steps.py | gabrielfalcao_lettuce/tests/functional/simple_features/2nd_feature_dir/step_definitions/sum_steps.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from nose.tools import assert_equals
from lettuce import step
from lettuce.terrain import world
from lettuce import after
@step('I sum (\d+) and (\d+)')
def i_sum_x_and_y(step, x, y):
world.sum = int(x) + int(y)
@step('it should result in (\d+)')
def it_should_result_in_z(step, z):
assert_equals(world.sum, int(z))
@after.all
def clear_sum(total_results):
if hasattr(world, 'sum'):
del world.sum
| 1,207 | Python | .py | 30 | 38.366667 | 71 | 0.740393 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,135 | .#invalid_name.py | gabrielfalcao_lettuce/tests/functional/invalid_module_name/.#invalid_name.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import world
world.invalid_passed = True
| 840 | Python | .py | 18 | 45.555556 | 71 | 0.770732 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,136 | #invalid_name.py | gabrielfalcao_lettuce/tests/functional/invalid_module_name/#invalid_name.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import world
world.invalid_passed = True
| 840 | Python | .py | 18 | 45.555556 | 71 | 0.770732 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,137 | terrain.py | gabrielfalcao_lettuce/tests/functional/invalid_module_name/terrain.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import world
world.invalid_passed = True
| 840 | Python | .py | 18 | 45.555556 | 71 | 0.770732 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,138 | steps.py | gabrielfalcao_lettuce/tests/functional/bg_features/header/steps.py | """
Blank steps file to prevent looking in parent directories
"""
| 66 | Python | .py | 3 | 21 | 57 | 0.777778 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,139 | steps.py | gabrielfalcao_lettuce/tests/functional/bg_features/naked/steps.py | """
Blank steps file to prevent looking in parent directories
"""
| 66 | Python | .py | 3 | 21 | 57 | 0.777778 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,140 | steps.py | gabrielfalcao_lettuce/tests/functional/bg_features/simple/steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Given the variable "([^"]*)" is equal to 2')
def given_the_variable_group1_is_equal_to_2(step, group1):
pass
@step(u'When the variable "([^"]*)" holds 10')
def when_the_variable_group1_holds_10(step, group1):
pass
@step(u'Then the variable "([^"]*)" times 5 is equal to 50')
def then_the_variable_group1_times_5_is_equal_to_50(step, group1):
pass
@step(u'And the variable "([^"]*)" is equal to 10')
def and_the_variable_group1_is_equal_to_10(step, group1):
pass
@step(u'Then the variable "([^"]*)" times 5 is equal to 10')
def then_the_variable_group1_times_5_is_equal_to_10(step, group1):
pass
@step(u'And the variable "([^"]*)" is equal to 2')
def and_the_variable_group1_is_equal_to_2(step, group1):
pass
| 795 | Python | .py | 20 | 37.25 | 66 | 0.677503 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,141 | test_ptbr.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/test_ptbr.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_setup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: pt-br -> sucess colorless"
runner = Runner(join_path('pt-br', 'success', 'dumb.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"Funcionalidade: feature burra # tests/functional/language_specific_features/pt-br/success/dumb.feature:3\n"
u" Como um programador # tests/functional/language_specific_features/pt-br/success/dumb.feature:4\n"
u" Eu quero que este teste passe # tests/functional/language_specific_features/pt-br/success/dumb.feature:5\n"
u" Para testar um cenário de sucesso # tests/functional/language_specific_features/pt-br/success/dumb.feature:6\n"
u"\n"
u" Cenário: Fazer nada # tests/functional/language_specific_features/pt-br/success/dumb.feature:8\n"
u" Dado que eu faço nada # tests/functional/language_specific_features/pt-br/success/dumb_steps.py:6\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_of_table_with_success_colorless():
"Language: pt-br -> sucess table colorless"
runner = Runner(join_path('pt-br', 'success', 'table.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"Funcionalidade: feature burra, com tabela # tests/functional/language_specific_features/pt-br/success/table.feature:3\n"
u" Como um programador # tests/functional/language_specific_features/pt-br/success/table.feature:4\n"
u" Eu quero testar steps com tabelas # tests/functional/language_specific_features/pt-br/success/table.feature:5\n"
u" Para ver o output em pt-br # tests/functional/language_specific_features/pt-br/success/table.feature:6\n"
u"\n"
u" Cenário: Fazer nada, com tabelas :) # tests/functional/language_specific_features/pt-br/success/table.feature:8\n"
u" Dado que eu brinco com os seguintes itens: # tests/functional/language_specific_features/pt-br/success/table_steps.py:6\n"
u" | id | description |\n"
u" | 12 | some desc |\n"
u" | 64 | another desc |\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorless():
"Language: pt-br -> sucess outlines colorless"
runner = Runner(join_path('pt-br', 'success', 'outlines.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Funcionalidade: outlines em português # tests/functional/language_specific_features/pt-br/success/outlines.feature:3\n'
u' Como um programador # tests/functional/language_specific_features/pt-br/success/outlines.feature:4\n'
u' Eu quero testar cenários esquemáticos # tests/functional/language_specific_features/pt-br/success/outlines.feature:5\n'
u' Para ver o output em pt-br # tests/functional/language_specific_features/pt-br/success/outlines.feature:6\n'
u'\n'
u' Esquema do Cenário: Fazer nada, repetidas vezes, através de esquemas # tests/functional/language_specific_features/pt-br/success/outlines.feature:8\n'
u' Dado que tenho o <dado1> # tests/functional/language_specific_features/pt-br/success/outlines_steps.py:13\n'
u' Quando eu faço algo com <isso> # tests/functional/language_specific_features/pt-br/success/outlines_steps.py:22\n'
u' Então eu fico feliz em ver <aquilo> # tests/functional/language_specific_features/pt-br/success/outlines_steps.py:31\n'
u'\n'
u' Exemplos:\n'
u' | dado1 | isso | aquilo |\n'
u' | algo | assim | funcional |\n'
u' | outro | aqui | também |\n'
u' | dados | funcionarão | com unicode ! |\n'
u'\n'
u'1 feature (1 passed)\n'
u'3 scenarios (3 passed)\n'
u'9 steps (9 passed)\n'
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorful():
"Language: pt-br -> sucess outlines colorful"
runner = Runner(join_path('pt-br', 'success', 'outlines.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u'\033[1;37mFuncionalidade: outlines em português \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines.feature:3\033[0m\n'
u'\033[1;37m Como um programador \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines.feature:4\033[0m\n'
u'\033[1;37m Eu quero testar cenários esquemáticos \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines.feature:5\033[0m\n'
u'\033[1;37m Para ver o output em pt-br \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines.feature:6\033[0m\n'
u'\n'
u'\033[1;37m Esquema do Cenário: Fazer nada, repetidas vezes, através de esquemas \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines.feature:8\033[0m\n'
u'\033[0;36m Dado que tenho o <dado1> \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines_steps.py:13\033[0m\n'
u'\033[0;36m Quando eu faço algo com <isso> \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines_steps.py:22\033[0m\n'
u'\033[0;36m Então eu fico feliz em ver <aquilo> \033[1;30m# tests/functional/language_specific_features/pt-br/success/outlines_steps.py:31\033[0m\n'
u'\n'
u'\033[1;37m Exemplos:\033[0m\n'
u'\033[0;36m \033[1;37m |\033[0;36m dado1\033[1;37m |\033[0;36m isso \033[1;37m |\033[0;36m aquilo \033[1;37m |\033[0;36m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m algo \033[1;37m |\033[1;32m assim \033[1;37m |\033[1;32m funcional \033[1;37m |\033[1;32m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m outro\033[1;37m |\033[1;32m aqui \033[1;37m |\033[1;32m também \033[1;37m |\033[1;32m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m dados\033[1;37m |\033[1;32m funcionarão\033[1;37m |\033[1;32m com unicode !\033[1;37m |\033[1;32m\033[0m\n'
u'\n'
u"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n" \
u"\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n" \
u"\033[1;37m9 steps (\033[1;32m9 passed\033[1;37m)\033[0m\n"
)
| 8,314 | Python | .py | 118 | 63.915254 | 191 | 0.626624 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,142 | test_ru.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/test_ru.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_setup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: ru -> sucess colorless"
runner = Runner(join_path('ru', 'success', 'dumb.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Функционал: тупая фича # tests/functional/language_specific_features/ru/success/dumb.feature:3\n'
u' Чтобы lettuce был более надежным # tests/functional/language_specific_features/ru/success/dumb.feature:4\n'
u' Как программист # tests/functional/language_specific_features/ru/success/dumb.feature:5\n'
u' Я хочу что бы тест был зеленый # tests/functional/language_specific_features/ru/success/dumb.feature:6\n'
u'\n'
u' Сценарий: Ничего не делать # tests/functional/language_specific_features/ru/success/dumb.feature:8\n'
u' Пуская я ничего не делаю # tests/functional/language_specific_features/ru/success/dumb_steps.py:6\n'
u' Тогда я вижу что тест выполняется # tests/functional/language_specific_features/ru/success/dumb_steps.py:10\n'
u'\n'
u'1 feature (1 passed)\n'
u'1 scenario (1 passed)\n'
u'2 steps (2 passed)\n'
)
@with_setup(prepare_stdout)
def test_output_of_table_with_success_colorless():
"Language: ru -> sucess table colorless"
runner = Runner(join_path('ru', 'success', 'table.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"Функционал: фича с табличкой # tests/functional/language_specific_features/ru/success/table.feature:3\n"
u" Для того, что бы lettuce был надежным # tests/functional/language_specific_features/ru/success/table.feature:4\n"
u" Как программист # tests/functional/language_specific_features/ru/success/table.feature:5\n"
u" Я хочу, что бы тесты с таблицами работали отлично и на русском # tests/functional/language_specific_features/ru/success/table.feature:6\n"
u"\n"
u" Сценарий: Проверить таблички # tests/functional/language_specific_features/ru/success/table.feature:8\n"
u" Пускай имеем таблицу пациентов: # tests/functional/language_specific_features/ru/success/table_steps.py:5\n"
u" | ФИО | Диагноз |\n"
u" | Петров ПП | диарея |\n"
u" | Сидоров НА | хронический снобизм |\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorless():
"Language: ru -> sucess outlines colorless"
runner = Runner(join_path('ru', 'success', 'outlines.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Функционал: Проверить вывод структурного сценария # tests/functional/language_specific_features/ru/success/outlines.feature:3\n'
u' Как программист # tests/functional/language_specific_features/ru/success/outlines.feature:4\n'
u' Для того чобы lettuce был надежным # tests/functional/language_specific_features/ru/success/outlines.feature:5\n'
u' Я хочу, что бы сценарии со структурой работали на русском # tests/functional/language_specific_features/ru/success/outlines.feature:6\n'
u'\n'
u' Структура сценария: Заполнить форму # tests/functional/language_specific_features/ru/success/outlines.feature:8\n'
u' Пускай я открываю в браузере "http://sona-studio.com/contacts/" # tests/functional/language_specific_features/ru/success/outlines_steps.py:12\n'
u' Когда я заполняю в поле "Имя" "<имя>" # tests/functional/language_specific_features/ru/success/outlines_steps.py:16\n'
u' И я заполняю в поле "Email" "<email>" # tests/functional/language_specific_features/ru/success/outlines_steps.py:24\n'
u' И я заполняю в поле "Сообщение" "<сообщение>" # tests/functional/language_specific_features/ru/success/outlines_steps.py:32\n'
u' И я нажимаю "Отправить" # tests/functional/language_specific_features/ru/success/outlines_steps.py:40\n'
u' Тогда я получаю сообщение "Спасибо за ваше сообщение" # tests/functional/language_specific_features/ru/success/outlines_steps.py:43\n'
u'\n'
u' Примеры:\n'
u' | имя | email | сообщение |\n'
u' | Виталий Игоревич | [email protected] | Есть интересный проект, нужно обсудить |\n'
u' | Марина Банраул | [email protected] | Мне нравятся ваши дизайны, хочу сайт |\n'
u'\n'
u'1 feature (1 passed)\n'
u'2 scenarios (2 passed)\n'
u'12 steps (12 passed)\n'
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorful():
"Language: ru -> sucess outlines colorful"
runner = Runner(join_path('ru', 'success', 'outlines.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u'\x1b[1;37m\u0424\u0443\u043d\u043a\u0446\u0438\u043e\u043d\u0430\u043b: \u041f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c \u0432\u044b\u0432\u043e\u0434 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u043d\u043e\u0433\u043e \u0441\u0446\u0435\u043d\u0430\u0440\u0438\u044f \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines.feature:3\x1b[0m\n'
u'\x1b[1;37m \u041a\u0430\u043a \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0441\u0442 \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines.feature:4\x1b[0m\n'
u'\x1b[1;37m \u0414\u043b\u044f \u0442\u043e\u0433\u043e \u0447\u043e\u0431\u044b lettuce \u0431\u044b\u043b \u043d\u0430\u0434\u0435\u0436\u043d\u044b\u043c \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines.feature:5\x1b[0m\n'
u'\x1b[1;37m \u042f \u0445\u043e\u0447\u0443, \u0447\u0442\u043e \u0431\u044b \u0441\u0446\u0435\u043d\u0430\u0440\u0438\u0438 \u0441\u043e \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u043e\u0439 \u0440\u0430\u0431\u043e\u0442\u0430\u043b\u0438 \u043d\u0430 \u0440\u0443\u0441\u0441\u043a\u043e\u043c \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines.feature:6\x1b[0m\n'
u'\n'
u'\x1b[1;37m \u0421\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u0430 \u0441\u0446\u0435\u043d\u0430\u0440\u0438\u044f: \u0417\u0430\u043f\u043e\u043b\u043d\u0438\u0442\u044c \u0444\u043e\u0440\u043c\u0443 \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines.feature:8\x1b[0m\n'
u'\x1b[0;36m \u041f\u0443\u0441\u043a\u0430\u0439 \u044f \u043e\u0442\u043a\u0440\u044b\u0432\u0430\u044e \u0432 \u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435 "http://sona-studio.com/contacts/" \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines_steps.py:12\x1b[0m\n'
u'\x1b[0;36m \u041a\u043e\u0433\u0434\u0430 \u044f \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u044e \u0432 \u043f\u043e\u043b\u0435 "\u0418\u043c\u044f" "<\u0438\u043c\u044f>" \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines_steps.py:16\x1b[0m\n'
u'\x1b[0;36m \u0418 \u044f \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u044e \u0432 \u043f\u043e\u043b\u0435 "Email" "<email>" \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines_steps.py:24\x1b[0m\n'
u'\x1b[0;36m \u0418 \u044f \u0437\u0430\u043f\u043e\u043b\u043d\u044f\u044e \u0432 \u043f\u043e\u043b\u0435 "\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435" "<\u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435>" \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines_steps.py:32\x1b[0m\n'
u'\x1b[0;36m \u0418 \u044f \u043d\u0430\u0436\u0438\u043c\u0430\u044e "\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c" \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines_steps.py:40\x1b[0m\n'
u'\x1b[0;36m \u0422\u043e\u0433\u0434\u0430 \u044f \u043f\u043e\u043b\u0443\u0447\u0430\u044e \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 "\u0421\u043f\u0430\u0441\u0438\u0431\u043e \u0437\u0430 \u0432\u0430\u0448\u0435 \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435" \x1b[1;30m# tests/functional/language_specific_features/ru/success/outlines_steps.py:43\x1b[0m\n'
u'\n'
u'\x1b[1;37m \u041f\u0440\u0438\u043c\u0435\u0440\u044b:\x1b[0m\n'
u'\x1b[0;36m \x1b[1;37m |\x1b[0;36m \u0438\u043c\u044f \x1b[1;37m |\x1b[0;36m email \x1b[1;37m |\x1b[0;36m \u0441\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \x1b[1;37m |\x1b[0;36m\x1b[0m\n'
u'\x1b[1;32m \x1b[1;37m |\x1b[1;32m \u0412\u0438\u0442\u0430\u043b\u0438\u0439 \u0418\u0433\u043e\u0440\u0435\u0432\u0438\u0447\x1b[1;37m |\x1b[1;32m [email protected]\x1b[1;37m |\x1b[1;32m \u0415\u0441\u0442\u044c \u0438\u043d\u0442\u0435\u0440\u0435\u0441\u043d\u044b\u0439 \u043f\u0440\u043e\u0435\u043a\u0442, \u043d\u0443\u0436\u043d\u043e \u043e\u0431\u0441\u0443\u0434\u0438\u0442\u044c\x1b[1;37m |\x1b[1;32m\x1b[0m\n'
u'\x1b[1;32m \x1b[1;37m |\x1b[1;32m \u041c\u0430\u0440\u0438\u043d\u0430 \u0411\u0430\u043d\u0440\u0430\u0443\u043b \x1b[1;37m |\x1b[1;32m [email protected]\x1b[1;37m |\x1b[1;32m \u041c\u043d\u0435 \u043d\u0440\u0430\u0432\u044f\u0442\u0441\u044f \u0432\u0430\u0448\u0438 \u0434\u0438\u0437\u0430\u0439\u043d\u044b, \u0445\u043e\u0447\u0443 \u0441\u0430\u0439\u0442 \x1b[1;37m |\x1b[1;32m\x1b[0m\n'
u'\n'
u'\x1b[1;37m1 feature (\x1b[1;32m1 passed\x1b[1;37m)\x1b[0m\n'
u'\x1b[1;37m2 scenarios (\x1b[1;32m2 passed\x1b[1;37m)\x1b[0m\n'
u'\x1b[1;37m12 steps (\x1b[1;32m12 passed\x1b[1;37m)\x1b[0m\n'
)
| 12,569 | Python | .py | 123 | 90.674797 | 425 | 0.6557 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,143 | test_fr.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/test_fr.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falcão <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_setup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: fr -> sucess colorless"
runner = Runner(join_path('fr', 'success', 'dumb.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"Fonctionnalité: Test complet # tests/functional/language_specific_features/fr/success/dumb.feature:3\n"
u" En tant que programmeur # tests/functional/language_specific_features/fr/success/dumb.feature:4\n"
u" Je veux valider les tests # tests/functional/language_specific_features/fr/success/dumb.feature:5\n"
u"\n"
u" Scénario: On ne fait rien # tests/functional/language_specific_features/fr/success/dumb.feature:7\n"
u" Quand je ne fait rien # tests/functional/language_specific_features/fr/success/dumb_steps.py:6\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_of_table_with_success_colorless():
"Language: fr -> sucess table colorless"
runner = Runner(join_path('fr', 'success', 'table.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"Fonctionnalité: Test des sorties, avec table # tests/functional/language_specific_features/fr/success/table.feature:4\n"
u" En tant que programmeur # tests/functional/language_specific_features/fr/success/table.feature:5\n"
u" Je veux tester les sorties de scénario avec table # tests/functional/language_specific_features/fr/success/table.feature:6\n"
u"\n"
u" Scénario: NE rien faire, mais avec des tables # tests/functional/language_specific_features/fr/success/table.feature:8\n"
u" Soit les éléments suivant # tests/functional/language_specific_features/fr/success/table_steps.py:6\n"
u" | id | élément |\n"
u" | 50 | Un |\n"
u" | 59 | 42 |\n"
u" | 29 | sieste |\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorless():
"Language: fr -> sucess outlines colorless"
runner = Runner(join_path('fr', 'success', 'outlines.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u'\n'
u'Fonctionnalité: Plan de scénario en français # tests/functional/language_specific_features/fr/success/outlines.feature:4\n'
u' En tant que programmeur # tests/functional/language_specific_features/fr/success/outlines.feature:5\n'
u' Je veux tester les plans de scénario # tests/functional/language_specific_features/fr/success/outlines.feature:6\n'
u' Et surtout les sorties # tests/functional/language_specific_features/fr/success/outlines.feature:7\n'
u'\n'
u' Plan de Scénario: Faire la sieste # tests/functional/language_specific_features/fr/success/outlines.feature:9\n'
u' Soit un après midi de <mois> # tests/functional/language_specific_features/fr/success/outlines_steps.py:13\n'
u' Quand je veux faire la sieste # tests/functional/language_specific_features/fr/success/outlines_steps.py:22\n'
u' Je peux aller <lieux> # tests/functional/language_specific_features/fr/success/outlines_steps.py:26\n'
u'\n'
u' Exemples:\n'
u' | mois | lieux |\n'
u' | janvier | près de la cheminé |\n'
u' | aôut | dans le transat |\n'
u' | octobre | dans le canapé |\n'
u'\n'
u'1 feature (1 passed)\n'
u'3 scenarios (3 passed)\n'
u'9 steps (9 passed)\n'
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorful():
"Language: fr -> sucess outlines colorful"
runner = Runner(join_path('fr', 'success', 'outlines.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u'\033[1;37mFonctionnalité: Plan de scénario en français \033[1;30m# tests/functional/language_specific_features/fr/success/outlines.feature:4\033[0m\n'
u'\033[1;37m En tant que programmeur \033[1;30m# tests/functional/language_specific_features/fr/success/outlines.feature:5\033[0m\n'
u'\033[1;37m Je veux tester les plans de scénario \033[1;30m# tests/functional/language_specific_features/fr/success/outlines.feature:6\033[0m\n'
u'\033[1;37m Et surtout les sorties \033[1;30m# tests/functional/language_specific_features/fr/success/outlines.feature:7\033[0m\n'
u'\n'
u'\033[1;37m Plan de Scénario: Faire la sieste \033[1;30m# tests/functional/language_specific_features/fr/success/outlines.feature:9\033[0m\n'
u'\033[0;36m Soit un après midi de <mois> \033[1;30m# tests/functional/language_specific_features/fr/success/outlines_steps.py:13\033[0m\n'
u'\033[0;36m Quand je veux faire la sieste \033[1;30m# tests/functional/language_specific_features/fr/success/outlines_steps.py:22\033[0m\n'
u'\033[0;36m Je peux aller <lieux> \033[1;30m# tests/functional/language_specific_features/fr/success/outlines_steps.py:26\033[0m\n'
u'\n'
u'\033[1;37m Exemples:\033[0m\n'
u'\033[0;36m \033[1;37m |\033[0;36m mois \033[1;37m |\033[0;36m lieux \033[1;37m |\033[0;36m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m janvier\033[1;37m |\033[1;32m près de la cheminé\033[1;37m |\033[1;32m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m aôut \033[1;37m |\033[1;32m dans le transat \033[1;37m |\033[1;32m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m octobre\033[1;37m |\033[1;32m dans le canapé \033[1;37m |\033[1;32m\033[0m\n'
u'\n'
u'\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n'
u'\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n'
u'\033[1;37m9 steps (\033[1;32m9 passed\033[1;37m)\033[0m\n'
)
@with_setup(prepare_stdout)
def test_output_outlines2_success_colorful():
"Language: fr -> sucess outlines colorful, alternate name"
runner = Runner(join_path('fr', 'success', 'outlines2.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u'\033[1;37mFonctionnalité: Plan de scénario en français \033[1;30m# tests/functional/language_specific_features/fr/success/outlines2.feature:4\033[0m\n'
u'\033[1;37m En tant que programmeur \033[1;30m# tests/functional/language_specific_features/fr/success/outlines2.feature:5\033[0m\n'
u'\033[1;37m Je veux tester les plans de scénario \033[1;30m# tests/functional/language_specific_features/fr/success/outlines2.feature:6\033[0m\n'
u'\033[1;37m Et surtout les sorties \033[1;30m# tests/functional/language_specific_features/fr/success/outlines2.feature:7\033[0m\n'
u'\n'
u'\033[1;37m Plan de Scénario: Faire la sieste \033[1;30m# tests/functional/language_specific_features/fr/success/outlines2.feature:9\033[0m\n'
u'\033[0;36m Soit un après midi de <mois> \033[1;30m# tests/functional/language_specific_features/fr/success/outlines_steps.py:13\033[0m\n'
u'\033[0;36m Quand je veux faire la sieste \033[1;30m# tests/functional/language_specific_features/fr/success/outlines_steps.py:22\033[0m\n'
u'\033[0;36m Je peux aller <lieux> \033[1;30m# tests/functional/language_specific_features/fr/success/outlines_steps.py:26\033[0m\n'
u'\n'
u'\033[1;37m Exemples:\033[0m\n'
u'\033[0;36m \033[1;37m |\033[0;36m mois \033[1;37m |\033[0;36m lieux \033[1;37m |\033[0;36m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m janvier\033[1;37m |\033[1;32m près de la cheminé\033[1;37m |\033[1;32m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m aôut \033[1;37m |\033[1;32m dans le transat \033[1;37m |\033[1;32m\033[0m\n'
u'\033[1;32m \033[1;37m |\033[1;32m octobre\033[1;37m |\033[1;32m dans le canapé \033[1;37m |\033[1;32m\033[0m\n'
u'\n'
u'\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n'
u'\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n'
u'\033[1;37m9 steps (\033[1;32m9 passed\033[1;37m)\033[0m\n'
)
| 9,827 | Python | .py | 144 | 61.375 | 162 | 0.651673 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,144 | language_helper.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/language_helper.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import lettuce
from StringIO import StringIO
from os.path import dirname, abspath, join
from nose.tools import assert_equals, with_setup, assert_raises
from lettuce import Runner, CALLBACK_REGISTRY, STEP_REGISTRY
from lettuce.fs import FeatureLoader
from lettuce.core import Feature, fs, StepDefinition
from lettuce.terrain import world
current_dir = abspath(dirname(__file__))
lettuce_dir = abspath(dirname(lettuce.__file__))
join_path = lambda *x: join(current_dir, *x)
lettuce_path = lambda *x: abspath(join(lettuce_dir, *x))
call_line = StepDefinition.__call__.im_func.func_code.co_firstlineno + 5
def prepare_stdout():
CALLBACK_REGISTRY.clear()
if isinstance(sys.stdout, StringIO):
del sys.stdout
std = StringIO()
sys.stdout = std
def assert_stdout(expected):
string = sys.stdout.getvalue()
assert_equals(string, expected)
def prepare_stderr():
CALLBACK_REGISTRY.clear()
STEP_REGISTRY.clear()
if isinstance(sys.stderr, StringIO):
del sys.stderr
std = StringIO()
sys.stderr = std
def assert_stderr(expected):
string = sys.stderr.getvalue()
assert_equals(string, expected)
def assert_lines(one, other):
lines_one = one.splitlines()
lines_other = other.splitlines()
for line1, line2 in zip(lines_one, lines_other):
assert_equals(line1, line2)
assert_equals(len(lines_one), len(lines_other))
def assert_stdout_lines(other):
assert_lines(sys.stdout.getvalue(), other)
def assert_stderr_lines(other):
assert_lines(sys.stderr.getvalue(), other)
| 2,356 | Python | .py | 59 | 36.932203 | 72 | 0.748574 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,145 | test_zh-TW.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/test_zh-TW.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc達o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_setup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: zh-TW -> sucess colorless"
runner = Runner(join_path('zh-TW', 'success', 'dumb.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"特性: 簡單測試 # tests/functional/language_specific_features/zh-TW/success/dumb.feature:3\n"
u" 什麽都不做應該運行成功 # tests/functional/language_specific_features/zh-TW/success/dumb.feature:4\n"
u"\n"
u" 場景: 什麽都不做 # tests/functional/language_specific_features/zh-TW/success/dumb.feature:6\n"
u" 如果 什麽都不做 # tests/functional/language_specific_features/zh-TW/success/dumb_steps.py:6\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_of_table_with_success_colorless():
"Language: zh-TW -> sucess table colorless"
runner = Runner(join_path('zh-TW', 'success', 'table.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"特性: 步驟中包含表格 # tests/functional/language_specific_features/zh-TW/success/table.feature:3\n"
u" 繁體中文表格步驟的成功測試 # tests/functional/language_specific_features/zh-TW/success/table.feature:4\n"
u"\n"
u" 場景: 什麽都不做的表格步驟測試 # tests/functional/language_specific_features/zh-TW/success/table.feature:6\n"
u" 如果 輸入數據如下: # tests/functional/language_specific_features/zh-TW/success/table_steps.py:6\n"
u" | id | 名稱 |\n"
u" | 12 | 名稱一 |\n"
u" | 64 | 名稱二 |\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorless():
"Language: zh-TW -> sucess outlines colorless"
runner = Runner(join_path('zh-TW', 'success', 'outlines.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"特性: 中文場景模板 # tests/functional/language_specific_features/zh-TW/success/outlines.feature:3\n"
u" 中文場景模板圖表測試 # tests/functional/language_specific_features/zh-TW/success/outlines.feature:4\n"
u"\n"
u" 場景模板: 用表格描述場景 # tests/functional/language_specific_features/zh-TW/success/outlines.feature:6\n"
u" 如果 輸入是<輸入> # tests/functional/language_specific_features/zh-TW/success/outlines_steps.py:13\n"
u" 當 執行<處理>時 # tests/functional/language_specific_features/zh-TW/success/outlines_steps.py:22\n"
u" 那麽 得到<結果> # tests/functional/language_specific_features/zh-TW/success/outlines_steps.py:31\n"
u"\n"
u" 例如:\n"
u" | 輸入 | 處理 | 結果 |\n"
u" | 什麽 | 這個 | 功能 |\n"
u" | 其他 | 這裏 | 一樣 |\n"
u" | 數據 | 動作 | unicode輸出! |\n"
u"\n"
u"1 feature (1 passed)\n"
u"3 scenarios (3 passed)\n"
u"9 steps (9 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorful():
"Language: zh-TW -> sucess outlines colorful"
runner = Runner(join_path('zh-TW', 'success', 'outlines.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u"\033[1;37m特性: 中文場景模板 \033[1;30m# tests/functional/language_specific_features/zh-TW/success/outlines.feature:3\033[0m\n"
u"\033[1;37m 中文場景模板圖表測試 \033[1;30m# tests/functional/language_specific_features/zh-TW/success/outlines.feature:4\033[0m\n"
u'\n'
u"\033[1;37m 場景模板: 用表格描述場景 \033[1;30m# tests/functional/language_specific_features/zh-TW/success/outlines.feature:6\033[0m\n"
u"\033[0;36m 如果 輸入是<輸入> \033[1;30m# tests/functional/language_specific_features/zh-TW/success/outlines_steps.py:13\033[0m\n"
u"\033[0;36m 當 執行<處理>時 \033[1;30m# tests/functional/language_specific_features/zh-TW/success/outlines_steps.py:22\033[0m\n"
u"\033[0;36m 那麽 得到<結果> \033[1;30m# tests/functional/language_specific_features/zh-TW/success/outlines_steps.py:31\033[0m\n"
u'\n'
u"\033[1;37m 例如:\033[0m\n"
u"\033[0;36m \033[1;37m |\033[0;36m 輸入\033[1;37m |\033[0;36m 處理\033[1;37m |\033[0;36m 結果 \033[1;37m |\033[0;36m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 什麽\033[1;37m |\033[1;32m 這個\033[1;37m |\033[1;32m 功能 \033[1;37m |\033[1;32m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 其他\033[1;37m |\033[1;32m 這裏\033[1;37m |\033[1;32m 一樣 \033[1;37m |\033[1;32m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 數據\033[1;37m |\033[1;32m 動作\033[1;37m |\033[1;32m unicode輸出!\033[1;37m |\033[1;32m\033[0m\n"
u'\n'
u"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
u"\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n"
u"\033[1;37m9 steps (\033[1;32m9 passed\033[1;37m)\033[0m\n"
)
| 6,592 | Python | .py | 110 | 49.554545 | 143 | 0.641846 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,146 | test_zh-CN.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/test_zh-CN.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc達o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_setup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: zh-CN -> sucess colorless"
runner = Runner(join_path('zh-CN', 'success', 'dumb.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"特性: 简单测试 # tests/functional/language_specific_features/zh-CN/success/dumb.feature:3\n"
u" 什么都不做应该运行成功 # tests/functional/language_specific_features/zh-CN/success/dumb.feature:4\n"
u"\n"
u" 场景: 什么都不做 # tests/functional/language_specific_features/zh-CN/success/dumb.feature:6\n"
u" 如果 什么都不做 # tests/functional/language_specific_features/zh-CN/success/dumb_steps.py:6\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_of_table_with_success_colorless():
"Language: zh-CN -> sucess table colorless"
runner = Runner(join_path('zh-CN', 'success', 'table.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"特性: 步骤中包含表格 # tests/functional/language_specific_features/zh-CN/success/table.feature:3\n"
u" 简体中文表格步骤的成功测试 # tests/functional/language_specific_features/zh-CN/success/table.feature:4\n"
u"\n"
u" 场景: 什么都不做的表格步骤测试 # tests/functional/language_specific_features/zh-CN/success/table.feature:6\n"
u" 如果 输入数据如下: # tests/functional/language_specific_features/zh-CN/success/table_steps.py:6\n"
u" | id | 名称 |\n"
u" | 12 | 名称一 |\n"
u" | 64 | 名称二 |\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorless():
"Language: zh-CN -> sucess outlines colorless"
runner = Runner(join_path('zh-CN', 'success', 'outlines.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"特性: 中文场景模板 # tests/functional/language_specific_features/zh-CN/success/outlines.feature:3\n"
u" 中文场景模板图表测试 # tests/functional/language_specific_features/zh-CN/success/outlines.feature:4\n"
u"\n"
u" 场景模板: 用表格描述场景 # tests/functional/language_specific_features/zh-CN/success/outlines.feature:6\n"
u" 如果 输入是<输入> # tests/functional/language_specific_features/zh-CN/success/outlines_steps.py:13\n"
u" 当 执行<处理>时 # tests/functional/language_specific_features/zh-CN/success/outlines_steps.py:22\n"
u" 那么 得到<结果> # tests/functional/language_specific_features/zh-CN/success/outlines_steps.py:31\n"
u"\n"
u" 例如:\n"
u" | 输入 | 处理 | 结果 |\n"
u" | 什么 | 这个 | 功能 |\n"
u" | 其他 | 这里 | 一样 |\n"
u" | 数据 | 动作 | unicode输出! |\n"
u"\n"
u"1 feature (1 passed)\n"
u"3 scenarios (3 passed)\n"
u"9 steps (9 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorful():
"Language: zh-CN -> sucess outlines colorful"
runner = Runner(join_path('zh-CN', 'success', 'outlines.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u"\033[1;37m特性: 中文场景模板 \033[1;30m# tests/functional/language_specific_features/zh-CN/success/outlines.feature:3\033[0m\n"
u"\033[1;37m 中文场景模板图表测试 \033[1;30m# tests/functional/language_specific_features/zh-CN/success/outlines.feature:4\033[0m\n"
u'\n'
u"\033[1;37m 场景模板: 用表格描述场景 \033[1;30m# tests/functional/language_specific_features/zh-CN/success/outlines.feature:6\033[0m\n"
u"\033[0;36m 如果 输入是<输入> \033[1;30m# tests/functional/language_specific_features/zh-CN/success/outlines_steps.py:13\033[0m\n"
u"\033[0;36m 当 执行<处理>时 \033[1;30m# tests/functional/language_specific_features/zh-CN/success/outlines_steps.py:22\033[0m\n"
u"\033[0;36m 那么 得到<结果> \033[1;30m# tests/functional/language_specific_features/zh-CN/success/outlines_steps.py:31\033[0m\n"
u'\n'
u"\033[1;37m 例如:\033[0m\n"
u"\033[0;36m \033[1;37m |\033[0;36m 输入\033[1;37m |\033[0;36m 处理\033[1;37m |\033[0;36m 结果 \033[1;37m |\033[0;36m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 什么\033[1;37m |\033[1;32m 这个\033[1;37m |\033[1;32m 功能 \033[1;37m |\033[1;32m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 其他\033[1;37m |\033[1;32m 这里\033[1;37m |\033[1;32m 一样 \033[1;37m |\033[1;32m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 数据\033[1;37m |\033[1;32m 动作\033[1;37m |\033[1;32m unicode输出!\033[1;37m |\033[1;32m\033[0m\n"
u'\n'
u"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
u"\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n"
u"\033[1;37m9 steps (\033[1;32m9 passed\033[1;37m)\033[0m\n"
)
| 6,592 | Python | .py | 110 | 49.554545 | 143 | 0.641846 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,147 | test_ja.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/test_ja.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc達o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from os.path import dirname, abspath, join
from nose.tools import with_setup
from tests.asserts import prepare_stdout
from tests.asserts import assert_stdout_lines
from lettuce import Runner
current_dir = abspath(dirname(__file__))
join_path = lambda *x: join(current_dir, *x)
@with_setup(prepare_stdout)
def test_output_with_success_colorless():
"Language: ja -> sucess colorless"
runner = Runner(join_path('ja', 'success', 'dumb.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"フィーチャ: ダムフィーチャ # tests/functional/language_specific_features/ja/success/dumb.feature:3\n"
u" テストをグリーンになればテスト成功 # tests/functional/language_specific_features/ja/success/dumb.feature:4\n"
u"\n"
u" シナリオ: 何もしない # tests/functional/language_specific_features/ja/success/dumb.feature:6\n"
u" 前提 何もしない # tests/functional/language_specific_features/ja/success/dumb_steps.py:6\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_of_table_with_success_colorless():
"Language: ja -> sucess table colorless"
runner = Runner(join_path('ja', 'success', 'table.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"フィーチャ: テーブル記法 # tests/functional/language_specific_features/ja/success/table.feature:3\n"
u" 日本語でのテーブル記法がパスするかのテスト # tests/functional/language_specific_features/ja/success/table.feature:4\n"
u"\n"
u" シナリオ: 何もしないテーブル # tests/functional/language_specific_features/ja/success/table.feature:6\n"
u" 前提 データは以下: # tests/functional/language_specific_features/ja/success/table_steps.py:6\n"
u" | id | 定義 |\n"
u" | 12 | 何かの定義 |\n"
u" | 64 | 別の定義 |\n"
u"\n"
u"1 feature (1 passed)\n"
u"1 scenario (1 passed)\n"
u"1 step (1 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorless():
"Language: ja -> sucess outlines colorless"
runner = Runner(join_path('ja', 'success', 'outlines.feature'), verbosity=3, no_color=True)
runner.run()
assert_stdout_lines(
u"\n"
u"フィーチャ: アウトラインを日本語で書く # tests/functional/language_specific_features/ja/success/outlines.feature:3\n"
u" 図表のテストをパスすること # tests/functional/language_specific_features/ja/success/outlines.feature:4\n"
u"\n"
u" シナリオアウトライン: 全てのテストで何もしない # tests/functional/language_specific_features/ja/success/outlines.feature:6\n"
u" 前提 入力値を <データ1> とし # tests/functional/language_specific_features/ja/success/outlines_steps.py:13\n"
u" もし 処理 <方法> を使って # tests/functional/language_specific_features/ja/success/outlines_steps.py:22\n"
u" ならば 表示は <結果> である # tests/functional/language_specific_features/ja/success/outlines_steps.py:31\n"
u"\n"
u" 例:\n"
u" | データ1 | 方法 | 結果 |\n"
u" | 何か | これ | 機能 |\n"
u" | その他 | ここ | 同じ |\n"
u" | データ | 動く | unicodeで! |\n"
u"\n"
u"1 feature (1 passed)\n"
u"3 scenarios (3 passed)\n"
u"9 steps (9 passed)\n"
)
@with_setup(prepare_stdout)
def test_output_outlines_success_colorful():
"Language: ja -> sucess outlines colorful"
runner = Runner(join_path('ja', 'success', 'outlines.feature'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(
u'\n'
u"\033[1;37mフィーチャ: アウトラインを日本語で書く \033[1;30m# tests/functional/language_specific_features/ja/success/outlines.feature:3\033[0m\n"
u"\033[1;37m 図表のテストをパスすること \033[1;30m# tests/functional/language_specific_features/ja/success/outlines.feature:4\033[0m\n"
u'\n'
u"\033[1;37m シナリオアウトライン: 全てのテストで何もしない \033[1;30m# tests/functional/language_specific_features/ja/success/outlines.feature:6\033[0m\n"
u"\033[0;36m 前提 入力値を <データ1> とし \033[1;30m# tests/functional/language_specific_features/ja/success/outlines_steps.py:13\033[0m\n"
u"\033[0;36m もし 処理 <方法> を使って \033[1;30m# tests/functional/language_specific_features/ja/success/outlines_steps.py:22\033[0m\n"
u"\033[0;36m ならば 表示は <結果> である \033[1;30m# tests/functional/language_specific_features/ja/success/outlines_steps.py:31\033[0m\n"
u'\n'
u"\033[1;37m 例:\033[0m\n"
u"\033[0;36m \033[1;37m |\033[0;36m データ1\033[1;37m |\033[0;36m 方法\033[1;37m |\033[0;36m 結果 \033[1;37m |\033[0;36m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m 何か \033[1;37m |\033[1;32m これ\033[1;37m |\033[1;32m 機能 \033[1;37m |\033[1;32m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m その他 \033[1;37m |\033[1;32m ここ\033[1;37m |\033[1;32m 同じ \033[1;37m |\033[1;32m\033[0m\n"
u"\033[1;32m \033[1;37m |\033[1;32m データ \033[1;37m |\033[1;32m 動く\033[1;37m |\033[1;32m unicodeで!\033[1;37m |\033[1;32m\033[0m\n"
u'\n'
u"\033[1;37m1 feature (\033[1;32m1 passed\033[1;37m)\033[0m\n"
u"\033[1;37m3 scenarios (\033[1;32m3 passed\033[1;37m)\033[0m\n"
u"\033[1;37m9 steps (\033[1;32m9 passed\033[1;37m)\033[0m\n"
)
| 6,962 | Python | .py | 110 | 51.063636 | 156 | 0.63268 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,148 | table_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/ja/success/table_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'データは以下')
def do_nothing_table(step):
pass
| 138 | Python | .py | 6 | 19.166667 | 27 | 0.689076 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,149 | outlines_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/ja/success/outlines_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
def assert_in(condition, possibilities):
assert condition in possibilities, \
u"%r は次のリストに入っている可能性がある: %r" % (
condition, possibilities
)
@step(u'入力値を (.*) とし')
def dado_que_tenho(step, group):
possibilities = [
u'何か',
u'その他',
u'データ'
]
assert_in(group, possibilities)
@step(u'処理 (.*) を使って')
def faco_algo_com(step, group):
possibilities = [
u'これ',
u'ここ',
u'動く'
]
assert_in(group, possibilities)
@step(u'表示は (.*) である')
def fico_feliz_em_ver(step, group):
possibilities = [
u'機能',
u'同じ',
u'unicodeで!'
]
assert_in(group, possibilities)
| 851 | Python | .py | 32 | 17.875 | 40 | 0.582386 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,150 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/ja/success/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'何もしない')
def nanimo_shinai(step):
pass
| 132 | Python | .py | 6 | 18.5 | 24 | 0.686957 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,151 | table_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/zh-CN/success/table_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'输入数据如下')
def do_nothing_table(step):
pass
| 138 | Python | .py | 6 | 19.166667 | 27 | 0.689076 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,152 | outlines_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/zh-CN/success/outlines_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
def assert_in(condition, possibilities):
assert condition in possibilities, \
u"%r 应该包含在: %r" % (
condition, possibilities
)
@step(u'输入是(.*)')
def shu_ru(step, group):
possibilities = [
u'什么',
u'其他',
u'数据'
]
assert_in(group, possibilities)
@step(u'执行(.*)时')
def zhi_xing(step, group):
possibilities = [
u'这个',
u'这里',
u'动作'
]
assert_in(group, possibilities)
@step(u'得到(.*)')
def de_dao(step, group):
possibilities = [
u'功能',
u'一样',
u'unicode输出!'
]
assert_in(group, possibilities)
| 749 | Python | .py | 32 | 16.1875 | 40 | 0.563077 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,153 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/zh-CN/success/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'什么都不做')
def shen_me_dou_bu_zuo(step):
pass
| 137 | Python | .py | 6 | 19.333333 | 29 | 0.675 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,154 | table_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/ru/success/table_steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Пускай имеем таблицу пациентов:')
def imeem_tablicu_pacientov(step):
pass
| 164 | Python | .py | 5 | 25.2 | 41 | 0.730769 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,155 | outlines_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/ru/success/outlines_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
def assert_in(text, variants):
assert text in variants, \
u"вариант %r не должен был тестироватся, только: %r" % (
text, variants
)
@step(u'я открываю в браузере "([^"]*)"')
def otkrivayu_v_brauzere(step, url):
pass
@step(u'я заполняю в поле "Имя" "([^"]*)"')
def zapolnyau_imya(step, name):
names=[
u"Виталий Игоревич",
u"Марина Банраул",
]
assert_in(name, names)
@step(u'я заполняю в поле "Email" "([^"]*)"')
def zapolnyau_email(step, email):
emails=[
"[email protected]",
"[email protected]",
]
assert_in(email, emails)
@step(u'я заполняю в поле "Сообщение" "([^"]*)"')
def zapolnyau_soobchenie(step, message):
messages=[
u"Есть интересный проект, нужно обсудить",
u"Мне нравятся ваши дизайны, хочу сайт",
]
assert_in(message, messages)
@step(u'я нажимаю "Отправить"')
def najimayu_otparavit(step):
pass
@step(u'я получаю сообщение "Спасибо за ваше сообщение"')
def poluchayu_soopschenie(step):
pass
| 1,352 | Python | .py | 38 | 24.5 | 64 | 0.641294 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,156 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/ru/success/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'я ничего не делаю')
def nichego_ne_delayu(step):
pass
@step(u'я вижу что тест выполняется')
def vigu_chto_test_vipolnyaetsa(step):
pass
| 266 | Python | .py | 9 | 22.888889 | 38 | 0.719626 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,157 | table_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/pt-br/success/table_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'eu brinco com os seguintes itens')
def brinco_com_os_seguintes_itens(step):
pass
| 165 | Python | .py | 6 | 25.666667 | 42 | 0.721519 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,158 | outlines_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/pt-br/success/outlines_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
def assert_in(dado, possibilidades):
assert dado in possibilidades, \
u"%r deveria estar nas possibilidades: %r" % (
dado, possibilidades
)
@step(u'tenho o (.*)')
def dado_que_tenho(step, grupo):
possibilidades = [
'algo',
'outro',
'dados'
]
assert_in(grupo, possibilidades)
@step(u'faço algo com (.*)')
def faco_algo_com(step, grupo):
possibilidades = [
'assim',
'aqui',
u'funcionarão'
]
assert_in(grupo, possibilidades)
@step(u'fico feliz em ver (.*)')
def fico_feliz_em_ver(step, grupo):
possibilidades = [
'funcional',
u'também',
'com unicode !'
]
assert_in(grupo, possibilidades)
| 796 | Python | .py | 32 | 19.5 | 54 | 0.600529 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,159 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/pt-br/success/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'Dado que eu faço nada')
def dado_que_eu_fa_o_nada(step):
pass | 146 | Python | .py | 6 | 22.666667 | 32 | 0.678571 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,160 | table_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/zh-TW/success/table_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'輸入數據如下')
def do_nothing_table(step):
pass
| 138 | Python | .py | 6 | 19.166667 | 27 | 0.689076 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,161 | outlines_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/zh-TW/success/outlines_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
def assert_in(condition, possibilities):
assert condition in possibilities, \
u"%r 應該包含在: %r" % (
condition, possibilities
)
@step(u'輸入是(.*)')
def shu_ru(step, group):
possibilities = [
u'什麽',
u'其他',
u'數據'
]
assert_in(group, possibilities)
@step(u'執行(.*)時')
def zhi_xing(step, group):
possibilities = [
u'這個',
u'這裏',
u'動作'
]
assert_in(group, possibilities)
@step(u'得到(.*)')
def de_dao(step, group):
possibilities = [
u'功能',
u'一樣',
u'unicode輸出!'
]
assert_in(group, possibilities)
| 749 | Python | .py | 32 | 16.1875 | 40 | 0.563077 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,162 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/zh-TW/success/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'什麽都不做')
def shen_me_dou_bu_zuo(step):
pass
| 137 | Python | .py | 6 | 19.333333 | 29 | 0.675 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,163 | table_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/fr/success/table_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'Soit les éléments suivant')
def brinco_com_os_seguintes_itens(step):
pass
| 160 | Python | .py | 6 | 24.5 | 40 | 0.721854 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,164 | outlines_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/fr/success/outlines_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
def assert_in(dado, possibilidades):
assert dado in possibilidades, \
u"%r deveria estar nas possibilidades: %r" % (
dado, possibilidades
)
@step(u'un après midi de (.*)')
def un_apres_midi(step, groupe):
possibilites = [
u'janvier',
u'aôut',
u'octobre'
]
assert_in(groupe, possibilites)
@step(u'je veux faire la sieste')
def je_veux_dormir(step):
pass
@step(u'je peux aller (.*)')
def lieux_de_sieste(step, groupe):
possibilites = [
u'près de la cheminé',
u'dans le transat',
u'dans le canapé'
]
assert_in(groupe, possibilites)
@step(u'fico feliz em ver (.*)')
def fico_feliz_em_ver(step, grupo):
possibilidades = [
'funcional',
u'também',
'com unicode !'
]
assert_in(grupo, possibilidades)
| 908 | Python | .py | 35 | 20.8 | 54 | 0.620209 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,165 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/language_specific_features/fr/success/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step(u'Quand Je ne fait rien')
def quand_je_ne_fait_rien(step):
pass
| 146 | Python | .py | 6 | 22.5 | 32 | 0.690647 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,166 | error.py | gabrielfalcao_lettuce/tests/functional/no_features/error.py |
# some modules have problems when loaded directly with __import__
# rather than being imported via their absolute names (e.g. django models)
# see issue #391
raise RuntimeError("please do not import this file directly")
| 221 | Python | .py | 4 | 54 | 74 | 0.787037 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,167 | steps.py | gabrielfalcao_lettuce/tests/functional/no_features/steps.py | """
Blank steps file to prevent looking in parent directories
"""
| 66 | Python | .py | 3 | 21 | 57 | 0.777778 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,168 | steps.py | gabrielfalcao_lettuce/tests/functional/syntax_features/steps.py | """
Blank steps file to prevent looking in parent directories
"""
| 66 | Python | .py | 3 | 21 | 57 | 0.777778 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,169 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/many_successful_features/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step('Given I do nothing')
def do_nothing(step): pass
@step('Then I see that the test passes')
def see_test_passes(step): pass
| 200 | Python | .py | 7 | 27.428571 | 40 | 0.71875 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,170 | simple-steps.py | gabrielfalcao_lettuce/tests/functional/output_features/commented_feature/simple-steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Given I do nothing')
def given_i_do_nothing(step):
pass
@step(u'Then I see that the test passes')
def then_i_see_that_the_test_passes(step):
pass
| 212 | Python | .py | 8 | 24.375 | 42 | 0.704433 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,171 | unicode_traceback_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/unicode_traceback/unicode_traceback_steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'my d√¶mi that passes')
def given_my_daemi_that_passes(step):
pass
@step('my "(.*)" that blows an exception')
def given_my_daemi_that_blows_a_exception(step, name):
assert False
| 244 | Python | .py | 8 | 28.25 | 54 | 0.696581 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,172 | failed_table_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/failed_table/failed_table_steps.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
@step('I have a dumb step that passes')
def hdstp(step):
pass
@step('this one fails')
def tof(step):
assert False
@step('this one will be skipped')
def wbs(step):
assert True
| 999 | Python | .py | 26 | 36.846154 | 71 | 0.756701 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,173 | system_exiting_error_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/system_exiting_error/system_exiting_error_steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'a system-exiting error is raised')
def raise_system_exiting_error(step):
raise KeyboardInterrupt
| 159 | Python | .py | 5 | 29.8 | 42 | 0.751634 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,174 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/runner_features/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step('Given I do nothing')
def do_nothing(step): pass
@step('Then I see that the test passes')
def see_test_passes(step): pass
| 200 | Python | .py | 7 | 27.428571 | 40 | 0.71875 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,175 | success_table_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/success_table/success_table_steps.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
from lettuce import world
from lettuce.terrain import before
from nose.tools import assert_equals
@before.all
def set_balance():
world.my_balance = 0
@step('I have (\d+) bucks')
def compare_bucks(step, cash):
assert_equals(world.my_balance, int(cash))
@step('I have these items')
def havetheseitems(step):
cars = {}
for data in step.hashes:
key = data['name']
value = int(data['price'])
cars[key] = value
world.cars = cars
@step('sell the "([^"]+)"')
def sell_item(step, name):
world.my_balance += world.cars[name]
del world.cars[name]
@step('my garage contains:')
def alsothese(step):
cars = {}
for data in step.hashes:
key = data['name']
value = int(data['price'])
cars[key] = value
assert_equals(cars, world.cars)
| 1,622 | Python | .py | 46 | 32.173913 | 71 | 0.709821 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,176 | simple-steps.py | gabrielfalcao_lettuce/tests/functional/output_features/tagged_features/simple-steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Given I do nothing')
def given_i_do_nothing(step):
pass
@step(u'Then I see that the test passes')
def then_i_see_that_the_test_passes(step):
pass
@step(u'Then I should not see "([^"]+)"')
def then_should_not_see(step, email):
pass
@step(u'Given some email addresses')
def given_email_addresses(step):
pass
| 383 | Python | .py | 14 | 24.928571 | 42 | 0.69863 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,177 | fail_outline_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/fail_outline/fail_outline_steps.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
@step(r'Given I open browser at "http://(.*)"')
def given_i_open_browser_at_http_address(step, address):
pass
@step(r'And click on "sign[-]up"')
def and_click_on_sign_up(step):
pass
@step(r'I fill the field "(.*)" with "(.*)"')
def when_i_fill_the_field_x_with_y(step, field, value):
if field == 'password' and value == 'wee-9876': assert False
@step(r'And I click "done"')
def and_i_click_done(step):
pass
@step(r'Then I see the message "(.*)"')
def then_i_see_the_message_message(step, message):
pass
| 1,339 | Python | .py | 32 | 40.03125 | 71 | 0.725596 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,178 | dumb_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/many_successful_scenarios/dumb_steps.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from lettuce import step
@step('Given I do nothing')
def do_nothing(step): pass
@step('Then I see that the test passes')
def see_test_passes(step): pass
| 200 | Python | .py | 7 | 27.428571 | 40 | 0.71875 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,179 | error_traceback_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/error_traceback/error_traceback_steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Given my step that passes')
def given_my_step_that_passes(step):
pass
@step(u'Given my step that blows a exception')
def given_my_step_that_blows_a_exception(step):
raise RuntimeError | 254 | Python | .py | 8 | 29.125 | 47 | 0.738589 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,180 | success_outline_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/success_outline/success_outline_steps.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lettuce import step
@step(r'Given I open browser at "http://(.*)"')
def given_i_open_browser_at_http_address(step, address):
pass
@step(r'And click on "sign[-]up"')
def and_click_on_sign_up(step):
pass
@step(r'I fill the field "(.*)" with "(.*)"')
def when_i_fill_the_field_x_with_y(step, field, value):
pass
@step(r'And I click "done"')
def and_i_click_done(step):
pass
@step(r'I see the title of the page is "(.*)"')
def then_i_see_the_message_message(step, title):
possible_titles = [
u'John | My Website',
u'Mary | My Website',
u'Foo | My Website',
]
assert title in possible_titles, \
'"%s" should be between the options [%s]' % (title, ", ".join(possible_titles))
| 1,529 | Python | .py | 38 | 37.394737 | 90 | 0.699461 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,181 | writes_to_console_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/writes_to_console/writes_to_console_steps.py | import sys
from lettuce import step
@step('When I write to stdout')
def write_stdout(step):
print >> sys.stdout, "Badger"
@step('When I write to stderr')
def write_stderr(step):
print >> sys.stderr, "Mushroom"
@step('Then I am happy')
def happy(step):
pass
| 273 | Python | .py | 11 | 22.363636 | 35 | 0.713178 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,182 | undefined_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/undefined_steps/undefined_steps.py | from lettuce import step, world
@step(u'this test step passes')
def this_test_step_passes(step):
assert True
@step(u'(.*) squared is (.*)')
def val1_squared_is_val2(step, val1, val2):
pass
| 199 | Python | .py | 7 | 26 | 43 | 0.705263 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,183 | xunit_unicode_and_bytestring_mixing_steps.py | gabrielfalcao_lettuce/tests/functional/output_features/xunit_unicode_and_bytestring_mixing/xunit_unicode_and_bytestring_mixing_steps.py | # -*- coding: utf-8 -*-
from lettuce import step
@step(u'Non ascii characters "(.*)" in outline')
def non_ascii_characters_in_outline(step, first):
assert True
@step(u'Non ascii characters "(.*)" in step')
def define_nonascii_chars(step, word):
assert True
@step(u'Non ascii characters "(.*)" in exception')
def raise_nonascii_chars(step, word):
raise Exception(word)
| 385 | Python | .py | 11 | 32.454545 | 50 | 0.710027 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,184 | terrain.py | gabrielfalcao_lettuce/tests/functional/sandbox/terrain.py | # -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012> Gabriel Falc√£o <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
it is here just to cause a syntax error
| 825 | Python | .py | 17 | 47.470588 | 71 | 0.767038 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,185 | failing_step_definitions.py | gabrielfalcao_lettuce/tests/functional/behave_as_features/3rd_failing_steps/failing_step_definitions.py | # -*- coding: utf-8 -*-
from nose.tools import assert_equals
from lettuce import step, world, before
@before.each_scenario
def set_stack_and_result(scenario):
world.stack = []
world.result = 0
@step(u'I have entered (\d+) into the calculator')
def i_have_entered_NUM_into_the_calculator(step, num):
world.stack.append(num)
assert False, 'Die, die, die my darling!'
@step(u'I press multiply')
def i_press_multiply(step):
world.result = reduce(lambda x, y: x*y, map(int, world.stack))
@step(u'the result should be (\d+) on the screen')
def the_result_should_be_NUM_on_the_screen(step, num):
assert_equals(world.result, int(num))
@step(u'I multiply (\d+) and (\d+) into the calculator')
def multiply_X_and_Y_into_the_calculator(step, x, y):
step.behave_as('''
I have entered {0} into the calculator
And I have entered {1} into the calculator
And I press multiply
'''.format(x, y))
| 928 | Python | .py | 24 | 35.583333 | 66 | 0.699332 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,186 | simple_tables_step_definitions.py | gabrielfalcao_lettuce/tests/functional/behave_as_features/2nd_table_steps/simple_tables_step_definitions.py | # -*- coding: utf-8 -*-
from nose.tools import assert_equals
from lettuce import step, world, before
@before.each_scenario
def set_stack_and_result(scenario):
world.stack = []
world.result = 0
@step(u'I have entered (\d+) into the calculator')
def i_have_entered_NUM_into_the_calculator(step, num):
world.stack.append(num)
@step(u'I press multiply')
def i_press_multiply(step):
world.result = reduce(lambda x, y: x*y, map(int, world.stack))
@step(u'the result should be (\d+) on the screen')
def the_result_should_be_NUM_on_the_screen(step, num):
assert_equals(world.result, int(num))
@step(u'I multiply (\d+) and (\d+) into the calculator')
def multiply_X_and_Y_into_the_calculator(step, x, y):
step.behave_as('''
Given I multiply these numbers:
| number |
| 55 |
| 2 |
'''.format(x, y))
@step(u'I multiply th[eo]se numbers')
def given_i_multiply_those_numbers(step):
world.stack.extend(map(int, step.hashes.values_under('number')))
world.result = reduce(lambda x, y: x*y, world.stack)
| 1,059 | Python | .py | 28 | 34.571429 | 68 | 0.682261 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,187 | simple_step_definitions.py | gabrielfalcao_lettuce/tests/functional/behave_as_features/1st_normal_steps/simple_step_definitions.py | # -*- coding: utf-8 -*-
from nose.tools import assert_equals
from lettuce import step, world, before
@before.each_scenario
def set_stack_and_result(scenario):
world.stack = []
world.result = 0
@step(u'I have entered (\d+) into the calculator')
def i_have_entered_NUM_into_the_calculator(step, num):
world.stack.append(num)
@step(u'I press multiply')
def i_press_multiply(step):
world.result = reduce(lambda x, y: x*y, map(int, world.stack))
@step(u'the result should be (\d+) on the screen')
def the_result_should_be_NUM_on_the_screen(step, num):
assert_equals(world.result, int(num))
@step(u'I multiply (\d+) and (\d+) into the calculator')
def multiply_X_and_Y_into_the_calculator(step, x, y):
step.behave_as('''
I have entered {0} into the calculator
And I have entered {1} into the calculator
And I press multiply
'''.format(x, y))
| 882 | Python | .py | 23 | 35.347826 | 66 | 0.702227 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,188 | fastcgi.txt | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/howto/deployment/fastcgi.txt | ============================================
How to use Django with FastCGI, SCGI, or AJP
============================================
.. highlight:: bash
Although the current preferred setup for running Django is :doc:`Apache with
mod_wsgi </howto/deployment/modwsgi>`, many people use shared hosting, on
which protocols such as FastCGI, SCGI or AJP are the only viable options. In
some setups, these protocols may provide better performance than mod_wsgi_.
.. admonition:: Note
This document primarily focuses on FastCGI. Other protocols, such as SCGI
and AJP, are also supported, through the ``flup`` Python package. See the
Protocols_ section below for specifics about SCGI and AJP.
Essentially, FastCGI is an efficient way of letting an external application
serve pages to a Web server. The Web server delegates the incoming Web requests
(via a socket) to FastCGI, which executes the code and passes the response back
to the Web server, which, in turn, passes it back to the client's Web browser.
Like mod_wsgi, FastCGI allows code to stay in memory, allowing requests to be
served with no startup time. While mod_wsgi can either be configured embedded
in the Apache Web server process or as a separate daemon process, a FastCGI
process never runs inside the Web server process, always in a separate,
persistent process.
.. _mod_wsgi: http://code.google.com/p/modwsgi/
.. _mod_perl: http://perl.apache.org/
.. admonition:: Why run code in a separate process?
The traditional ``mod_*`` arrangements in Apache embed various scripting
languages (most notably PHP, Python and Perl) inside the process space of
your Web server. Although this lowers startup time -- because code doesn't
have to be read off disk for every request -- it comes at the cost of
memory use.
Due to the nature of FastCGI, it's even possible to have processes that run
under a different user account than the Web server process. That's a nice
security benefit on shared systems, because it means you can secure your
code from other users.
Prerequisite: flup
==================
Before you can start using FastCGI with Django, you'll need to install flup_, a
Python library for dealing with FastCGI. Version 0.5 or newer should work fine.
.. _flup: http://www.saddi.com/software/flup/
Starting your FastCGI server
============================
FastCGI operates on a client-server model, and in most cases you'll be starting
the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or
otherwise) only contacts your Django-FastCGI process when the server needs a
dynamic page to be loaded. Because the daemon is already running with the code
in memory, it's able to serve the response very quickly.
.. admonition:: Note
If you're on a shared hosting system, you'll probably be forced to use
Web server-managed FastCGI processes. See the section below on running
Django with Web server-managed processes for more information.
A Web server can connect to a FastCGI server in one of two ways: It can use
either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a
TCP socket. What you choose is a manner of preference; a TCP socket is usually
easier due to permissions issues.
To start your server, first change into the directory of your project (wherever
your :doc:`manage.py </ref/django-admin>` is), and then run the
:djadmin:`runfcgi` command::
./manage.py runfcgi [options]
If you specify ``help`` as the only option after :djadmin:`runfcgi`, it'll
display a list of all the available options.
You'll need to specify either a :djadminopt:`socket`, a :djadminopt:`protocol`
or both :djadminopt:`host` and :djadminopt:`port`. Then, when you set up your
Web server, you'll just need to point it at the host/port or socket you
specified when starting the FastCGI server. See the examples_, below.
Protocols
---------
Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and
`AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred
protocol by using the :djadminopt:`protocol=\<protocol_name\> <protocol>` option
with ``./manage.py runfcgi`` -- where ``<protocol_name>`` may be one of:
``fcgi`` (the default), ``scgi`` or ``ajp``. For example::
./manage.py runfcgi protocol=scgi
.. _flup: http://www.saddi.com/software/flup/
.. _fastcgi: http://www.fastcgi.com/
.. _SCGI: http://python.ca/scgi/protocol.txt
.. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
Examples
--------
Running a threaded server on a TCP port::
./manage.py runfcgi method=threaded host=127.0.0.1 port=3033
Running a preforked server on a Unix domain socket::
./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
.. admonition:: Socket security
Django's default umask requires that the webserver and the Django fastcgi
process be run with the same group **and** user. For increased security,
you can run them under the same group but as different users. If you do
this, you will need to set the umask to 0002 using the ``umask`` argument
to ``runfcgi``.
Run without daemonizing (backgrounding) the process (good for debugging)::
./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock maxrequests=1
Stopping the FastCGI daemon
---------------------------
If you have the process running in the foreground, it's easy enough to stop it:
Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when
you're dealing with background processes, you'll need to resort to the Unix
``kill`` command.
If you specify the :djadminopt:`pidfile` option to :djadmin:`runfcgi`, you can
kill the running FastCGI daemon like this::
kill `cat $PIDFILE`
...where ``$PIDFILE`` is the ``pidfile`` you specified.
To easily restart your FastCGI daemon on Unix, try this small shell script::
#!/bin/bash
# Replace these three settings.
PROJDIR="/home/user/myproject"
PIDFILE="$PROJDIR/mysite.pid"
SOCKET="$PROJDIR/mysite.sock"
cd $PROJDIR
if [ -f $PIDFILE ]; then
kill `cat -- $PIDFILE`
rm -f -- $PIDFILE
fi
exec /usr/bin/env - \
PYTHONPATH="../python:.." \
./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE
Apache setup
============
To use Django with Apache and FastCGI, you'll need Apache installed and
configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache
documentation for instructions.
Once you've got that set up, point Apache at your Django FastCGI instance by
editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two
things:
* Use the ``FastCGIExternalServer`` directive to specify the location of
your FastCGI server.
* Use ``mod_rewrite`` to point URLs at FastCGI as appropriate.
.. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
Specifying the location of the FastCGI server
---------------------------------------------
The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI
server. As the `FastCGIExternalServer docs`_ explain, you can specify either a
``socket`` or a ``host``. Here are examples of both:
.. code-block:: apache
# Connect to FastCGI via a socket / named pipe.
FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock
# Connect to FastCGI via a TCP host/port.
FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033
In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't
actually have to exist. It's just a URL used by the Web server internally -- a
hook for signifying which requests at a URL should be handled by FastCGI. (More
on this in the next section.)
.. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
Using mod_rewrite to point URLs at FastCGI
------------------------------------------
The second step is telling Apache to use FastCGI for URLs that match a certain
pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to
``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer``
directive, as explained in the previous section).
In this example, we tell Apache to use FastCGI to handle any request that
doesn't represent a file on the filesystem and doesn't start with ``/media/``.
This is probably the most common case, if you're using Django's admin site:
.. code-block:: apache
<VirtualHost 12.34.56.78>
ServerName example.com
DocumentRoot /home/user/public_html
Alias /media /home/user/python/django/contrib/admin/media
RewriteEngine On
RewriteRule ^/(media.*)$ /$1 [QSA,L,PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L]
</VirtualHost>
.. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
Django will automatically use the pre-rewrite version of the URL when
constructing URLs with the ``{% url %}`` template tag (and similar methods).
lighttpd setup
==============
lighttpd_ is a lightweight Web server commonly used for serving static files. It
supports FastCGI natively and, thus, is a good choice for serving both static
and dynamic pages, if your site doesn't have any Apache-specific needs.
.. _lighttpd: http://www.lighttpd.net/
Make sure ``mod_fastcgi`` is in your modules list, somewhere after
``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll
probably want ``mod_alias`` as well, for serving admin media.
Add the following to your lighttpd config file:
.. code-block:: lua
server.document-root = "/home/user/public_html"
fastcgi.server = (
"/mysite.fcgi" => (
"main" => (
# Use host / port instead of socket for TCP fastcgi
# "host" => "127.0.0.1",
# "port" => 3033,
"socket" => "/home/user/mysite.sock",
"check-local" => "disable",
)
),
)
alias.url = (
"/media" => "/home/user/django/contrib/admin/media/",
)
url.rewrite-once = (
"^(/media.*)$" => "$1",
"^/favicon\.ico$" => "/media/favicon.ico",
"^(/.*)$" => "/mysite.fcgi$1",
)
Running multiple Django sites on one lighttpd
---------------------------------------------
lighttpd lets you use "conditional configuration" to allow configuration to be
customized per host. To specify multiple FastCGI sites, just add a conditional
block around your FastCGI config for each site::
# If the hostname is 'www.example1.com'...
$HTTP["host"] == "www.example1.com" {
server.document-root = "/foo/site1"
fastcgi.server = (
...
)
...
}
# If the hostname is 'www.example2.com'...
$HTTP["host"] == "www.example2.com" {
server.document-root = "/foo/site2"
fastcgi.server = (
...
)
...
}
You can also run multiple Django installations on the same site simply by
specifying multiple entries in the ``fastcgi.server`` directive. Add one
FastCGI host for each.
Cherokee setup
==============
Cherokee is a very fast, flexible and easy to configure Web Server. It
supports the widespread technologies nowadays: FastCGI, SCGI, PHP, CGI, SSI,
TLS and SSL encrypted connections, Virtual hosts, Authentication, on the fly
encoding, Load Balancing, Apache compatible log files, Data Base Balancer,
Reverse HTTP Proxy and much more.
The Cherokee project provides a documentation to `setting up Django`_ with Cherokee.
.. _setting up Django: http://www.cherokee-project.com/doc/cookbook_django.html
Running Django on a shared-hosting provider with Apache
=======================================================
Many shared-hosting providers don't allow you to run your own server daemons or
edit the ``httpd.conf`` file. In these cases, it's still possible to run Django
using Web server-spawned processes.
.. admonition:: Note
If you're using Web server-spawned processes, as explained in this section,
there's no need for you to start the FastCGI server on your own. Apache
will spawn a number of processes, scaling as it needs to.
In your Web root directory, add this to a file named ``.htaccess``:
.. code-block:: apache
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
Then, create a small script that tells Apache how to spawn your FastCGI
program. Create a file ``mysite.fcgi`` and place it in your Web directory, and
be sure to make it executable:
.. code-block:: python
#!/usr/bin/python
import sys, os
# Add a custom Python path.
sys.path.insert(0, "/home/user/python")
# Switch to the directory of your project. (Optional.)
# os.chdir("/home/user/myproject")
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
Restarting the spawned server
-----------------------------
If you change any Python code on your site, you'll need to tell FastCGI the
code has changed. But there's no need to restart Apache in this case. Rather,
just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the
file will change. When Apache sees the file has been updated, it will restart
your Django application for you.
If you have access to a command shell on a Unix system, you can accomplish this
easily by using the ``touch`` command::
touch mysite.fcgi
Serving admin media files
=========================
Regardless of the server and configuration you eventually decide to use, you
will also need to give some thought to how to serve the admin media files. The
advice given in the :ref:`mod_wsgi <serving-the-admin-files>` documentation
is also applicable in the setups detailed above.
Forcing the URL prefix to a particular value
============================================
Because many of these fastcgi-based solutions require rewriting the URL at
some point inside the Web server, the path information that Django sees may not
resemble the original URL that was passed in. This is a problem if the Django
application is being served from under a particular prefix and you want your
URLs from the ``{% url %}`` tag to look like the prefix, rather than the
rewritten version, which might contain, for example, ``mysite.fcgi``.
Django makes a good attempt to work out what the real script name prefix
should be. In particular, if the Web server sets the ``SCRIPT_URL`` (specific
to Apache's mod_rewrite), or ``REDIRECT_URL`` (set by a few servers, including
Apache + mod_rewrite in some situations), Django will work out the original
prefix automatically.
In the cases where Django cannot work out the prefix correctly and where you
want the original value to be used in URLs, you can set the
:setting:`FORCE_SCRIPT_NAME` setting in your main ``settings`` file. This sets the
script name uniformly for every URL served via that settings file. Thus you'll
need to use different settings files if you want different sets of URLs to
have different script names in this case, but that is a rare situation.
As an example of how to use it, if your Django configuration is serving all of
the URLs under ``'/'`` and you wanted to use this setting, you would set
``FORCE_SCRIPT_NAME = ''`` in your settings file.
| 15,551 | Python | .cgi | 293 | 49.617747 | 110 | 0.720161 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,189 | runfcgi.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/runfcgi.py | from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Runs this project as a FastCGI application. Requires flup."
args = '[various KEY=val options, use `runfcgi help` for help]'
def handle(self, *args, **options):
from django.conf import settings
from django.utils import translation
# Activate the current language, because it won't get activated later.
try:
translation.activate(settings.LANGUAGE_CODE)
except AttributeError:
pass
from django.core.servers.fastcgi import runfastcgi
runfastcgi(args)
def usage(self, subcommand):
from django.core.servers.fastcgi import FASTCGI_HELP
return FASTCGI_HELP
| 760 | Python | .cgi | 17 | 36.470588 | 78 | 0.70082 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,190 | fastcgi.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/servers/fastcgi.py | """
FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol.
Uses the flup python package: http://www.saddi.com/software/flup/
This is a adaptation of the flup package to add FastCGI server support
to run Django apps from Web servers that support the FastCGI protocol.
This module can be run standalone or from the django-admin / manage.py
scripts using the "runfcgi" directive.
Run with the extra option "help" for a list of additional options you can
pass to this server.
"""
from django.utils import importlib
import sys, os
__version__ = "0.1"
__all__ = ["runfastcgi"]
FASTCGI_HELP = r"""
Run this project as a fastcgi (or some other protocol supported
by flup) application. To do this, the flup package from
http://www.saddi.com/software/flup/ is required.
runfcgi [options] [fcgi settings]
Optional Fcgi settings: (setting=value)
protocol=PROTOCOL fcgi, scgi, ajp, ... (default fcgi)
host=HOSTNAME hostname to listen on.
port=PORTNUM port to listen on.
socket=FILE UNIX socket to listen on.
method=IMPL prefork or threaded (default prefork).
maxrequests=NUMBER number of requests a child handles before it is
killed and a new child is forked (0 = no limit).
maxspare=NUMBER max number of spare processes / threads.
minspare=NUMBER min number of spare processes / threads.
maxchildren=NUMBER hard limit number of processes / threads.
daemonize=BOOL whether to detach from terminal.
pidfile=FILE write the spawned process-id to this file.
workdir=DIRECTORY change to this directory when daemonizing.
debug=BOOL set to true to enable flup tracebacks.
outlog=FILE write stdout to this file.
errlog=FILE write stderr to this file.
umask=UMASK umask to use when daemonizing, in octal notation (default 022).
Examples:
Run a "standard" fastcgi process on a file-descriptor
(for Web servers which spawn your processes for you)
$ manage.py runfcgi method=threaded
Run a scgi server on a TCP host/port
$ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025
Run a fastcgi server on a UNIX domain socket (posix platforms only)
$ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock
Run a fastCGI as a daemon and write the spawned PID in a file
$ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \
daemonize=true pidfile=/var/run/django-fcgi.pid
"""
FASTCGI_OPTIONS = {
'protocol': 'fcgi',
'host': None,
'port': None,
'socket': None,
'method': 'fork',
'daemonize': None,
'workdir': '/',
'pidfile': None,
'maxspare': 5,
'minspare': 2,
'maxchildren': 50,
'maxrequests': 0,
'debug': None,
'outlog': None,
'errlog': None,
'umask': None,
}
def fastcgi_help(message=None):
print FASTCGI_HELP
if message:
print message
return False
def runfastcgi(argset=[], **kwargs):
options = FASTCGI_OPTIONS.copy()
options.update(kwargs)
for x in argset:
if "=" in x:
k, v = x.split('=', 1)
else:
k, v = x, True
options[k.lower()] = v
if "help" in options:
return fastcgi_help()
try:
import flup
except ImportError, e:
print >> sys.stderr, "ERROR: %s" % e
print >> sys.stderr, " Unable to load the flup package. In order to run django"
print >> sys.stderr, " as a FastCGI application, you will need to get flup from"
print >> sys.stderr, " http://www.saddi.com/software/flup/ If you've already"
print >> sys.stderr, " installed flup, then make sure you have it in your PYTHONPATH."
return False
flup_module = 'server.' + options['protocol']
if options['method'] in ('prefork', 'fork'):
wsgi_opts = {
'maxSpare': int(options["maxspare"]),
'minSpare': int(options["minspare"]),
'maxChildren': int(options["maxchildren"]),
'maxRequests': int(options["maxrequests"]),
}
flup_module += '_fork'
elif options['method'] in ('thread', 'threaded'):
wsgi_opts = {
'maxSpare': int(options["maxspare"]),
'minSpare': int(options["minspare"]),
'maxThreads': int(options["maxchildren"]),
}
else:
return fastcgi_help("ERROR: Implementation must be one of prefork or thread.")
wsgi_opts['debug'] = options['debug'] is not None
try:
module = importlib.import_module('.%s' % flup_module, 'flup')
WSGIServer = module.WSGIServer
except:
print "Can't import flup." + flup_module
return False
# Prep up and go
from django.core.handlers.wsgi import WSGIHandler
if options["host"] and options["port"] and not options["socket"]:
wsgi_opts['bindAddress'] = (options["host"], int(options["port"]))
elif options["socket"] and not options["host"] and not options["port"]:
wsgi_opts['bindAddress'] = options["socket"]
elif not options["socket"] and not options["host"] and not options["port"]:
wsgi_opts['bindAddress'] = None
else:
return fastcgi_help("Invalid combination of host, port, socket.")
if options["daemonize"] is None:
# Default to daemonizing if we're running on a socket/named pipe.
daemonize = (wsgi_opts['bindAddress'] is not None)
else:
if options["daemonize"].lower() in ('true', 'yes', 't'):
daemonize = True
elif options["daemonize"].lower() in ('false', 'no', 'f'):
daemonize = False
else:
return fastcgi_help("ERROR: Invalid option for daemonize parameter.")
daemon_kwargs = {}
if options['outlog']:
daemon_kwargs['out_log'] = options['outlog']
if options['errlog']:
daemon_kwargs['err_log'] = options['errlog']
if options['umask']:
daemon_kwargs['umask'] = int(options['umask'], 8)
if daemonize:
from django.utils.daemonize import become_daemon
become_daemon(our_home_dir=options["workdir"], **daemon_kwargs)
if options["pidfile"]:
fp = open(options["pidfile"], "w")
fp.write("%d\n" % os.getpid())
fp.close()
WSGIServer(WSGIHandler(), **wsgi_opts).run()
if __name__ == '__main__':
runfastcgi(sys.argv[1:])
| 6,402 | Python | .cgi | 153 | 35.771242 | 95 | 0.646567 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,191 | fastcgi.txt | gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/howto/deployment/fastcgi.txt | ============================================
How to use Django with FastCGI, SCGI, or AJP
============================================
.. highlight:: bash
Although the current preferred setup for running Django is :doc:`Apache with
mod_wsgi </howto/deployment/modwsgi>`, many people use shared hosting, on
which protocols such as FastCGI, SCGI or AJP are the only viable options. In
some setups, these protocols may provide better performance than mod_wsgi_.
.. admonition:: Note
This document primarily focuses on FastCGI. Other protocols, such as SCGI
and AJP, are also supported, through the ``flup`` Python package. See the
Protocols_ section below for specifics about SCGI and AJP.
Essentially, FastCGI is an efficient way of letting an external application
serve pages to a Web server. The Web server delegates the incoming Web requests
(via a socket) to FastCGI, which executes the code and passes the response back
to the Web server, which, in turn, passes it back to the client's Web browser.
Like mod_python, FastCGI allows code to stay in memory, allowing requests to be
served with no startup time. Unlike mod_python_ (or `mod_perl`_), a FastCGI
process doesn't run inside the Web server process, but in a separate,
persistent process.
.. _mod_wsgi: http://code.google.com/p/modwsgi/
.. _mod_perl: http://perl.apache.org/
.. _mod_python: http://www.modpython.org/
.. admonition:: Why run code in a separate process?
The traditional ``mod_*`` arrangements in Apache embed various scripting
languages (most notably PHP, Python and Perl) inside the process space of
your Web server. Although this lowers startup time -- because code doesn't
have to be read off disk for every request -- it comes at the cost of
memory use. For mod_python, for example, every Apache process gets its own
Python interpreter, which uses up a considerable amount of RAM.
Due to the nature of FastCGI, it's even possible to have processes that run
under a different user account than the Web server process. That's a nice
security benefit on shared systems, because it means you can secure your
code from other users.
Prerequisite: flup
==================
Before you can start using FastCGI with Django, you'll need to install flup_, a
Python library for dealing with FastCGI. Version 0.5 or newer should work fine.
.. _flup: http://www.saddi.com/software/flup/
Starting your FastCGI server
============================
FastCGI operates on a client-server model, and in most cases you'll be starting
the FastCGI process on your own. Your Web server (be it Apache, lighttpd, or
otherwise) only contacts your Django-FastCGI process when the server needs a
dynamic page to be loaded. Because the daemon is already running with the code
in memory, it's able to serve the response very quickly.
.. admonition:: Note
If you're on a shared hosting system, you'll probably be forced to use
Web server-managed FastCGI processes. See the section below on running
Django with Web server-managed processes for more information.
A Web server can connect to a FastCGI server in one of two ways: It can use
either a Unix domain socket (a "named pipe" on Win32 systems), or it can use a
TCP socket. What you choose is a manner of preference; a TCP socket is usually
easier due to permissions issues.
To start your server, first change into the directory of your project (wherever
your :doc:`manage.py </ref/django-admin>` is), and then run the
:djadmin:`runfcgi` command::
./manage.py runfcgi [options]
If you specify ``help`` as the only option after :djadmin:`runfcgi`, it'll
display a list of all the available options.
You'll need to specify either a :djadminopt:`socket`, a :djadminopt:`protocol`
or both :djadminopt:`host` and :djadminopt:`port`. Then, when you set up your
Web server, you'll just need to point it at the host/port or socket you
specified when starting the FastCGI server. See the examples_, below.
Protocols
---------
Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and
`AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred
protocol by using the :djadminopt:`protocol=\<protocol_name\> <protocol>` option
with ``./manage.py runfcgi`` -- where ``<protocol_name>`` may be one of:
``fcgi`` (the default), ``scgi`` or ``ajp``. For example::
./manage.py runfcgi protocol=scgi
.. _flup: http://www.saddi.com/software/flup/
.. _fastcgi: http://www.fastcgi.com/
.. _SCGI: http://python.ca/scgi/protocol.txt
.. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
Examples
--------
Running a threaded server on a TCP port::
./manage.py runfcgi method=threaded host=127.0.0.1 port=3033
Running a preforked server on a Unix domain socket::
./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
.. admonition:: Socket security
Django's default umask requires that the webserver and the Django fastcgi
process be run with the same group **and** user. For increased security,
you can run them under the same group but as different users. If you do
this, you will need to set the umask to 0002 using the ``umask`` argument
to ``runfcgi``.
Run without daemonizing (backgrounding) the process (good for debugging)::
./manage.py runfcgi daemonize=false socket=/tmp/mysite.sock maxrequests=1
Stopping the FastCGI daemon
---------------------------
If you have the process running in the foreground, it's easy enough to stop it:
Simply hitting ``Ctrl-C`` will stop and quit the FastCGI server. However, when
you're dealing with background processes, you'll need to resort to the Unix
``kill`` command.
If you specify the :djadminopt:`pidfile` option to :djadmin:`runfcgi`, you can
kill the running FastCGI daemon like this::
kill `cat $PIDFILE`
...where ``$PIDFILE`` is the ``pidfile`` you specified.
To easily restart your FastCGI daemon on Unix, try this small shell script::
#!/bin/bash
# Replace these three settings.
PROJDIR="/home/user/myproject"
PIDFILE="$PROJDIR/mysite.pid"
SOCKET="$PROJDIR/mysite.sock"
cd $PROJDIR
if [ -f $PIDFILE ]; then
kill `cat -- $PIDFILE`
rm -f -- $PIDFILE
fi
exec /usr/bin/env - \
PYTHONPATH="../python:.." \
./manage.py runfcgi socket=$SOCKET pidfile=$PIDFILE
Apache setup
============
To use Django with Apache and FastCGI, you'll need Apache installed and
configured, with `mod_fastcgi`_ installed and enabled. Consult the Apache
documentation for instructions.
Once you've got that set up, point Apache at your Django FastCGI instance by
editing the ``httpd.conf`` (Apache configuration) file. You'll need to do two
things:
* Use the ``FastCGIExternalServer`` directive to specify the location of
your FastCGI server.
* Use ``mod_rewrite`` to point URLs at FastCGI as appropriate.
.. _mod_fastcgi: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html
Specifying the location of the FastCGI server
---------------------------------------------
The ``FastCGIExternalServer`` directive tells Apache how to find your FastCGI
server. As the `FastCGIExternalServer docs`_ explain, you can specify either a
``socket`` or a ``host``. Here are examples of both:
.. code-block:: apache
# Connect to FastCGI via a socket / named pipe.
FastCGIExternalServer /home/user/public_html/mysite.fcgi -socket /home/user/mysite.sock
# Connect to FastCGI via a TCP host/port.
FastCGIExternalServer /home/user/public_html/mysite.fcgi -host 127.0.0.1:3033
In either case, the file ``/home/user/public_html/mysite.fcgi`` doesn't
actually have to exist. It's just a URL used by the Web server internally -- a
hook for signifying which requests at a URL should be handled by FastCGI. (More
on this in the next section.)
.. _FastCGIExternalServer docs: http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html#FastCgiExternalServer
Using mod_rewrite to point URLs at FastCGI
------------------------------------------
The second step is telling Apache to use FastCGI for URLs that match a certain
pattern. To do this, use the `mod_rewrite`_ module and rewrite URLs to
``mysite.fcgi`` (or whatever you specified in the ``FastCGIExternalServer``
directive, as explained in the previous section).
In this example, we tell Apache to use FastCGI to handle any request that
doesn't represent a file on the filesystem and doesn't start with ``/media/``.
This is probably the most common case, if you're using Django's admin site:
.. code-block:: apache
<VirtualHost 12.34.56.78>
ServerName example.com
DocumentRoot /home/user/public_html
Alias /media /home/user/python/django/contrib/admin/media
RewriteEngine On
RewriteRule ^/(media.*)$ /$1 [QSA,L,PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L]
</VirtualHost>
.. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
Django will automatically use the pre-rewrite version of the URL when
constructing URLs with the ``{% url %}`` template tag (and similar methods).
lighttpd setup
==============
lighttpd_ is a lightweight Web server commonly used for serving static files. It
supports FastCGI natively and, thus, is a good choice for serving both static
and dynamic pages, if your site doesn't have any Apache-specific needs.
.. _lighttpd: http://www.lighttpd.net/
Make sure ``mod_fastcgi`` is in your modules list, somewhere after
``mod_rewrite`` and ``mod_access``, but not after ``mod_accesslog``. You'll
probably want ``mod_alias`` as well, for serving admin media.
Add the following to your lighttpd config file:
.. code-block:: lua
server.document-root = "/home/user/public_html"
fastcgi.server = (
"/mysite.fcgi" => (
"main" => (
# Use host / port instead of socket for TCP fastcgi
# "host" => "127.0.0.1",
# "port" => 3033,
"socket" => "/home/user/mysite.sock",
"check-local" => "disable",
)
),
)
alias.url = (
"/media" => "/home/user/django/contrib/admin/media/",
)
url.rewrite-once = (
"^(/media.*)$" => "$1",
"^/favicon\.ico$" => "/media/favicon.ico",
"^(/.*)$" => "/mysite.fcgi$1",
)
Running multiple Django sites on one lighttpd
---------------------------------------------
lighttpd lets you use "conditional configuration" to allow configuration to be
customized per host. To specify multiple FastCGI sites, just add a conditional
block around your FastCGI config for each site::
# If the hostname is 'www.example1.com'...
$HTTP["host"] == "www.example1.com" {
server.document-root = "/foo/site1"
fastcgi.server = (
...
)
...
}
# If the hostname is 'www.example2.com'...
$HTTP["host"] == "www.example2.com" {
server.document-root = "/foo/site2"
fastcgi.server = (
...
)
...
}
You can also run multiple Django installations on the same site simply by
specifying multiple entries in the ``fastcgi.server`` directive. Add one
FastCGI host for each.
Cherokee setup
==============
Cherokee is a very fast, flexible and easy to configure Web Server. It
supports the widespread technologies nowadays: FastCGI, SCGI, PHP, CGI, SSI,
TLS and SSL encrypted connections, Virtual hosts, Authentication, on the fly
encoding, Load Balancing, Apache compatible log files, Data Base Balancer,
Reverse HTTP Proxy and much more.
The Cherokee project provides a documentation to `setting up Django`_ with Cherokee.
.. _setting up Django: http://www.cherokee-project.com/doc/cookbook_django.html
Running Django on a shared-hosting provider with Apache
=======================================================
Many shared-hosting providers don't allow you to run your own server daemons or
edit the ``httpd.conf`` file. In these cases, it's still possible to run Django
using Web server-spawned processes.
.. admonition:: Note
If you're using Web server-spawned processes, as explained in this section,
there's no need for you to start the FastCGI server on your own. Apache
will spawn a number of processes, scaling as it needs to.
In your Web root directory, add this to a file named ``.htaccess``:
.. code-block:: apache
AddHandler fastcgi-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
Then, create a small script that tells Apache how to spawn your FastCGI
program. Create a file ``mysite.fcgi`` and place it in your Web directory, and
be sure to make it executable:
.. code-block:: python
#!/usr/bin/python
import sys, os
# Add a custom Python path.
sys.path.insert(0, "/home/user/python")
# Switch to the directory of your project. (Optional.)
# os.chdir("/home/user/myproject")
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
Restarting the spawned server
-----------------------------
If you change any Python code on your site, you'll need to tell FastCGI the
code has changed. But there's no need to restart Apache in this case. Rather,
just reupload ``mysite.fcgi``, or edit the file, so that the timestamp on the
file will change. When Apache sees the file has been updated, it will restart
your Django application for you.
If you have access to a command shell on a Unix system, you can accomplish this
easily by using the ``touch`` command::
touch mysite.fcgi
Serving admin media files
=========================
Regardless of the server and configuration you eventually decide to use, you
will also need to give some thought to how to serve the admin media files. The
advice given in the :ref:`modpython <serving-the-admin-files>` documentation
is also applicable in the setups detailed above.
Forcing the URL prefix to a particular value
============================================
Because many of these fastcgi-based solutions require rewriting the URL at
some point inside the Web server, the path information that Django sees may not
resemble the original URL that was passed in. This is a problem if the Django
application is being served from under a particular prefix and you want your
URLs from the ``{% url %}`` tag to look like the prefix, rather than the
rewritten version, which might contain, for example, ``mysite.fcgi``.
Django makes a good attempt to work out what the real script name prefix
should be. In particular, if the Web server sets the ``SCRIPT_URL`` (specific
to Apache's mod_rewrite), or ``REDIRECT_URL`` (set by a few servers, including
Apache + mod_rewrite in some situations), Django will work out the original
prefix automatically.
In the cases where Django cannot work out the prefix correctly and where you
want the original value to be used in URLs, you can set the
:setting:`FORCE_SCRIPT_NAME` setting in your main ``settings`` file. This sets the
script name uniformly for every URL served via that settings file. Thus you'll
need to use different settings files if you want different sets of URLs to
have different script names in this case, but that is a rare situation.
As an example of how to use it, if your Django configuration is serving all of
the URLs under ``'/'`` and you wanted to use this setting, you would set
``FORCE_SCRIPT_NAME = ''`` in your settings file.
| 15,647 | Python | .cgi | 294 | 49.758503 | 110 | 0.719675 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,192 | runfcgi.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/management/commands/runfcgi.py | from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Runs this project as a FastCGI application. Requires flup."
args = '[various KEY=val options, use `runfcgi help` for help]'
def handle(self, *args, **options):
from django.conf import settings
from django.utils import translation
# Activate the current language, because it won't get activated later.
try:
translation.activate(settings.LANGUAGE_CODE)
except AttributeError:
pass
from django.core.servers.fastcgi import runfastcgi
runfastcgi(args)
def usage(self, subcommand):
from django.core.servers.fastcgi import FASTCGI_HELP
return FASTCGI_HELP
| 760 | Python | .cgi | 17 | 36.470588 | 78 | 0.70082 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,193 | fastcgi.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/servers/fastcgi.py | """
FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol.
Uses the flup python package: http://www.saddi.com/software/flup/
This is a adaptation of the flup package to add FastCGI server support
to run Django apps from Web servers that support the FastCGI protocol.
This module can be run standalone or from the django-admin / manage.py
scripts using the "runfcgi" directive.
Run with the extra option "help" for a list of additional options you can
pass to this server.
"""
from django.utils import importlib
import sys, os
__version__ = "0.1"
__all__ = ["runfastcgi"]
FASTCGI_HELP = r"""
Run this project as a fastcgi (or some other protocol supported
by flup) application. To do this, the flup package from
http://www.saddi.com/software/flup/ is required.
runfcgi [options] [fcgi settings]
Optional Fcgi settings: (setting=value)
protocol=PROTOCOL fcgi, scgi, ajp, ... (default fcgi)
host=HOSTNAME hostname to listen on.
port=PORTNUM port to listen on.
socket=FILE UNIX socket to listen on.
method=IMPL prefork or threaded (default prefork).
maxrequests=NUMBER number of requests a child handles before it is
killed and a new child is forked (0 = no limit).
maxspare=NUMBER max number of spare processes / threads.
minspare=NUMBER min number of spare processes / threads.
maxchildren=NUMBER hard limit number of processes / threads.
daemonize=BOOL whether to detach from terminal.
pidfile=FILE write the spawned process-id to this file.
workdir=DIRECTORY change to this directory when daemonizing.
debug=BOOL set to true to enable flup tracebacks.
outlog=FILE write stdout to this file.
errlog=FILE write stderr to this file.
umask=UMASK umask to use when daemonizing, in octal notation (default 022).
Examples:
Run a "standard" fastcgi process on a file-descriptor
(for Web servers which spawn your processes for you)
$ manage.py runfcgi method=threaded
Run a scgi server on a TCP host/port
$ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025
Run a fastcgi server on a UNIX domain socket (posix platforms only)
$ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock
Run a fastCGI as a daemon and write the spawned PID in a file
$ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \
daemonize=true pidfile=/var/run/django-fcgi.pid
"""
FASTCGI_OPTIONS = {
'protocol': 'fcgi',
'host': None,
'port': None,
'socket': None,
'method': 'fork',
'daemonize': None,
'workdir': '/',
'pidfile': None,
'maxspare': 5,
'minspare': 2,
'maxchildren': 50,
'maxrequests': 0,
'debug': None,
'outlog': None,
'errlog': None,
'umask': None,
}
def fastcgi_help(message=None):
print FASTCGI_HELP
if message:
print message
return False
def runfastcgi(argset=[], **kwargs):
options = FASTCGI_OPTIONS.copy()
options.update(kwargs)
for x in argset:
if "=" in x:
k, v = x.split('=', 1)
else:
k, v = x, True
options[k.lower()] = v
if "help" in options:
return fastcgi_help()
try:
import flup
except ImportError, e:
print >> sys.stderr, "ERROR: %s" % e
print >> sys.stderr, " Unable to load the flup package. In order to run django"
print >> sys.stderr, " as a FastCGI application, you will need to get flup from"
print >> sys.stderr, " http://www.saddi.com/software/flup/ If you've already"
print >> sys.stderr, " installed flup, then make sure you have it in your PYTHONPATH."
return False
flup_module = 'server.' + options['protocol']
if options['method'] in ('prefork', 'fork'):
wsgi_opts = {
'maxSpare': int(options["maxspare"]),
'minSpare': int(options["minspare"]),
'maxChildren': int(options["maxchildren"]),
'maxRequests': int(options["maxrequests"]),
}
flup_module += '_fork'
elif options['method'] in ('thread', 'threaded'):
wsgi_opts = {
'maxSpare': int(options["maxspare"]),
'minSpare': int(options["minspare"]),
'maxThreads': int(options["maxchildren"]),
}
else:
return fastcgi_help("ERROR: Implementation must be one of prefork or thread.")
wsgi_opts['debug'] = options['debug'] is not None
try:
module = importlib.import_module('.%s' % flup_module, 'flup')
WSGIServer = module.WSGIServer
except:
print "Can't import flup." + flup_module
return False
# Prep up and go
from django.core.handlers.wsgi import WSGIHandler
if options["host"] and options["port"] and not options["socket"]:
wsgi_opts['bindAddress'] = (options["host"], int(options["port"]))
elif options["socket"] and not options["host"] and not options["port"]:
wsgi_opts['bindAddress'] = options["socket"]
elif not options["socket"] and not options["host"] and not options["port"]:
wsgi_opts['bindAddress'] = None
else:
return fastcgi_help("Invalid combination of host, port, socket.")
if options["daemonize"] is None:
# Default to daemonizing if we're running on a socket/named pipe.
daemonize = (wsgi_opts['bindAddress'] is not None)
else:
if options["daemonize"].lower() in ('true', 'yes', 't'):
daemonize = True
elif options["daemonize"].lower() in ('false', 'no', 'f'):
daemonize = False
else:
return fastcgi_help("ERROR: Invalid option for daemonize parameter.")
daemon_kwargs = {}
if options['outlog']:
daemon_kwargs['out_log'] = options['outlog']
if options['errlog']:
daemon_kwargs['err_log'] = options['errlog']
if options['umask']:
daemon_kwargs['umask'] = int(options['umask'], 8)
if daemonize:
from django.utils.daemonize import become_daemon
become_daemon(our_home_dir=options["workdir"], **daemon_kwargs)
if options["pidfile"]:
fp = open(options["pidfile"], "w")
fp.write("%d\n" % os.getpid())
fp.close()
WSGIServer(WSGIHandler(), **wsgi_opts).run()
if __name__ == '__main__':
runfastcgi(sys.argv[1:])
| 6,402 | Python | .cgi | 153 | 35.771242 | 95 | 0.646567 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,194 | runfcgi.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/management/commands/runfcgi.py | from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Runs this project as a FastCGI application. Requires flup."
args = '[various KEY=val options, use `runfcgi help` for help]'
def handle(self, *args, **options):
from django.conf import settings
from django.utils import translation
# Activate the current language, because it won't get activated later.
try:
translation.activate(settings.LANGUAGE_CODE)
except AttributeError:
pass
from django.core.servers.fastcgi import runfastcgi
runfastcgi(args)
def usage(self, subcommand):
from django.core.servers.fastcgi import FASTCGI_HELP
return FASTCGI_HELP
| 760 | Python | .fcgi | 17 | 36.470588 | 78 | 0.70082 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,195 | runfcgi.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/django/core/management/commands/runfcgi.py | from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Runs this project as a FastCGI application. Requires flup."
args = '[various KEY=val options, use `runfcgi help` for help]'
def handle(self, *args, **options):
from django.conf import settings
from django.utils import translation
# Activate the current language, because it won't get activated later.
try:
translation.activate(settings.LANGUAGE_CODE)
except AttributeError:
pass
from django.core.servers.fastcgi import runfastcgi
runfastcgi(args)
def usage(self, subcommand):
from django.core.servers.fastcgi import FASTCGI_HELP
return FASTCGI_HELP
| 760 | Python | .fcgi | 17 | 36.470588 | 78 | 0.70082 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,196 | modpython.txt | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/howto/deployment/modpython.txt | ============================================
How to use Django with Apache and mod_python
============================================
.. warning::
Support for mod_python has been deprecated, and will be removed in
Django 1.5. If you are configuring a new deployment, you are
strongly encouraged to consider using :doc:`mod_wsgi
</howto/deployment/modwsgi>` or any of the other :doc:`supported
backends </howto/deployment/index>`.
.. highlight:: apache
The `mod_python`_ module for Apache_ can be used to deploy Django to a
production server, although it has been mostly superseded by the simpler
:doc:`mod_wsgi deployment option </howto/deployment/modwsgi>`.
mod_python is similar to (and inspired by) `mod_perl`_ : It embeds Python within
Apache and loads Python code into memory when the server starts. Code stays in
memory throughout the life of an Apache process, which leads to significant
performance gains over other server arrangements.
Django requires Apache 2.x and mod_python 3.x, and you should use Apache's
`prefork MPM`_, as opposed to the `worker MPM`_.
.. seealso::
* Apache is a big, complex animal, and this document only scratches the
surface of what Apache can do. If you need more advanced information about
Apache, there's no better source than `Apache's own official
documentation`_
* You may also be interested in :doc:`How to use Django with FastCGI, SCGI,
or AJP </howto/deployment/fastcgi>`.
.. _Apache: http://httpd.apache.org/
.. _mod_python: http://www.modpython.org/
.. _mod_perl: http://perl.apache.org/
.. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html
.. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html
.. _apache's own official documentation: http://httpd.apache.org/docs/
Basic configuration
===================
To configure Django with mod_python, first make sure you have Apache installed,
with the mod_python module activated.
Then edit your ``httpd.conf`` file and add the following::
<Location "/mysite/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonDebug On
</Location>
...and replace ``mysite.settings`` with the Python import path to your Django
project's settings file.
This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the
Django mod_python handler." It passes the value of :ref:`DJANGO_SETTINGS_MODULE
<django-settings-module>` so mod_python knows which settings to use.
Because mod_python does not know we are serving this site from underneath the
``/mysite/`` prefix, this value needs to be passed through to the mod_python
handler in Django, via the ``PythonOption django.root ...`` line. The value set
on that line (the last item) should match the string given in the ``<Location
...>`` directive. The effect of this is that Django will automatically strip the
``/mysite`` string from the front of any URLs before matching them against your
URLconf patterns. If you later move your site to live under ``/mysite2``, you
will not have to change anything except the ``django.root`` option in the config
file.
When using ``django.root`` you should make sure that what's left, after the
prefix has been removed, begins with a slash. Your URLconf patterns that are
expecting an initial slash will then work correctly. In the above example,
since we want to send things like ``/mysite/admin/`` to ``/admin/``, we need
to remove the string ``/mysite`` from the beginning, so that is the
``django.root`` value. It would be an error to use ``/mysite/`` (with a
trailing slash) in this case.
Note that we're using the ``<Location>`` directive, not the ``<Directory>``
directive. The latter is used for pointing at places on your filesystem,
whereas ``<Location>`` points at places in the URL structure of a Web site.
``<Directory>`` would be meaningless here.
Also, if your Django project is not on the default ``PYTHONPATH`` for your
computer, you'll have to tell mod_python where your project can be found:
.. parsed-literal::
<Location "/mysite/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonDebug On
**PythonPath "['/path/to/project'] + sys.path"**
</Location>
The value you use for ``PythonPath`` should include the parent directories of
all the modules you are going to import in your application. It should also
include the parent directory of the :ref:`DJANGO_SETTINGS_MODULE
<django-settings-module>` location. This is exactly the same situation as
setting the Python path for interactive usage. Whenever you try to import
something, Python will run through all the directories in ``sys.path`` in turn,
from first to last, and try to import from each directory until one succeeds.
Make sure that your Python source files' permissions are set such that the
Apache user (usually named ``apache`` or ``httpd`` on most systems) will have
read access to the files.
An example might make this clearer. Suppose you have some applications under
``/usr/local/django-apps/`` (for example, ``/usr/local/django-apps/weblog/`` and
so forth), your settings file is at ``/var/www/mysite/settings.py`` and you have
specified :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` as in the above
example. In this case, you would need to write your ``PythonPath`` directive
as::
PythonPath "['/usr/local/django-apps/', '/var/www'] + sys.path"
With this path, ``import weblog`` and ``import mysite.settings`` will both
work. If you had ``import blogroll`` in your code somewhere and ``blogroll``
lived under the ``weblog/`` directory, you would *also* need to add
``/usr/local/django-apps/weblog/`` to your ``PythonPath``. Remember: the
**parent directories** of anything you import directly must be on the Python
path.
.. note::
If you're using Windows, we still recommended that you use forward
slashes in the pathnames, even though Windows normally uses the backslash
character as its native separator. Apache knows how to convert from the
forward slash format to the native format, so this approach is portable and
easier to read. (It avoids tricky problems with having to double-escape
backslashes.)
This is valid even on a Windows system::
PythonPath "['c:/path/to/project'] + sys.path"
You can also add directives such as ``PythonAutoReload Off`` for performance.
See the `mod_python documentation`_ for a full list of options.
Note that you should set ``PythonDebug Off`` on a production server. If you
leave ``PythonDebug On``, your users would see ugly (and revealing) Python
tracebacks if something goes wrong within mod_python.
Restart Apache, and any request to ``/mysite/`` or below will be served by
Django. Note that Django's URLconfs won't trim the "/mysite/" -- they get passed
the full URL.
When deploying Django sites on mod_python, you'll need to restart Apache each
time you make changes to your Python code.
.. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html
Multiple Django installations on the same Apache
================================================
It's entirely possible to run multiple Django installations on the same Apache
instance. Just use ``VirtualHost`` for that, like so::
NameVirtualHost *
<VirtualHost *>
ServerName www.example.com
# ...
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</VirtualHost>
<VirtualHost *>
ServerName www2.example.com
# ...
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
</VirtualHost>
If you need to put two Django installations within the same ``VirtualHost``
(or in different ``VirtualHost`` blocks that share the same server name),
you'll need to take a special precaution to ensure mod_python's cache doesn't
mess things up. Use the ``PythonInterpreter`` directive to give different
``<Location>`` directives separate interpreters::
<VirtualHost *>
ServerName www.example.com
# ...
<Location "/something">
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonInterpreter mysite
</Location>
<Location "/otherthing">
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
PythonInterpreter othersite
</Location>
</VirtualHost>
The values of ``PythonInterpreter`` don't really matter, as long as they're
different between the two ``Location`` blocks.
Running a development server with mod_python
============================================
If you use mod_python for your development server, you can avoid the hassle of
having to restart the server each time you make code changes. Just set
``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload
everything for each request. But don't do that on a production server, or we'll
revoke your Django privileges.
If you're the type of programmer who debugs using scattered ``print``
statements, note that output to ``stdout`` will not appear in the Apache
log and can even `cause response errors`_.
.. _cause response errors: http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html
If you have the need to print debugging information in a mod_python setup, you
have a few options. You can print to ``stderr`` explicitly, like so::
print >> sys.stderr, 'debug text'
sys.stderr.flush()
(note that ``stderr`` is buffered, so calling ``flush`` is necessary if you wish
debugging information to be displayed promptly.)
A more compact approach is to use an assertion::
assert False, 'debug text'
Another alternative is to add debugging information to the template of your page.
Serving media files
===================
Django doesn't serve media files itself; it leaves that job to whichever Web
server you choose.
We recommend using a separate Web server -- i.e., one that's not also running
Django -- for serving media. Here are some good choices:
* lighttpd_
* Nginx_
* TUX_
* A stripped-down version of Apache_
* Cherokee_
If, however, you have no option but to serve media files on the same Apache
``VirtualHost`` as Django, here's how you can turn off mod_python for a
particular part of the site::
<Location "/media">
SetHandler None
</Location>
Just change ``Location`` to the root URL of your media files. You can also use
``<LocationMatch>`` to match a regular expression.
This example sets up Django at the site root but explicitly disables Django for
the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or
``.png``::
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</Location>
<Location "/media">
SetHandler None
</Location>
<LocationMatch "\.(jpg|gif|png)$">
SetHandler None
</LocationMatch>
.. _lighttpd: http://www.lighttpd.net/
.. _Nginx: http://wiki.nginx.org/Main
.. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
.. _Apache: http://httpd.apache.org/
.. _Cherokee: http://www.cherokee-project.com/
Serving the admin files
=======================
Note that the Django development server automagically serves admin media files,
but this is not the case when you use any other server arrangement. You're
responsible for setting up Apache, or whichever media server you're using, to
serve the admin files.
The admin files live in (:file:`django/contrib/admin/media`) of the Django
distribution.
Here are two recommended approaches:
1. Create a symbolic link to the admin media files from within your
document root. This way, all of your Django-related files -- code **and**
templates -- stay in one place, and you'll still be able to ``svn
update`` your code to get the latest admin templates, if they change.
2. Or, copy the admin media files so that they live within your Apache
document root.
Using "eggs" with mod_python
============================
If you installed Django from a Python egg_ or are using eggs in your Django
project, some extra configuration is required. Create an extra file in your
project (or somewhere else) that contains something like the following:
.. code-block:: python
import os
os.environ['PYTHON_EGG_CACHE'] = '/some/directory'
Here, ``/some/directory`` is a directory that the Apache Web server process can
write to. It will be used as the location for any unpacking of code the eggs
need to do.
Then you have to tell mod_python to import this file before doing anything
else. This is done using the PythonImport_ directive to mod_python. You need
to ensure that you have specified the ``PythonInterpreter`` directive to
mod_python as described above__ (you need to do this even if you aren't
serving multiple installations in this case). Then add the ``PythonImport``
line in the main server configuration (i.e., outside the ``Location`` or
``VirtualHost`` sections). For example::
PythonInterpreter my_django
PythonImport /path/to/my/project/file.py my_django
Note that you can use an absolute path here (or a normal dotted import path),
as described in the `mod_python manual`_. We use an absolute path in the
above example because if any Python path modifications are required to access
your project, they will not have been done at the time the ``PythonImport``
line is processed.
.. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs
.. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html
.. _mod_python manual: PythonImport_
__ `Multiple Django installations on the same Apache`_
Error handling
==============
When you use Apache/mod_python, errors will be caught by Django -- in other
words, they won't propagate to the Apache level and won't appear in the Apache
``error_log``.
The exception for this is if something is really wonky in your Django setup. In
that case, you'll see an "Internal Server Error" page in your browser and the
full Python traceback in your Apache ``error_log`` file. The ``error_log``
traceback is spread over multiple lines. (Yes, this is ugly and rather hard to
read, but it's how mod_python does things.)
If you get a segmentation fault
===============================
If Apache causes a segmentation fault, there are two probable causes, neither
of which has to do with Django itself.
1. It may be because your Python code is importing the "pyexpat" module,
which may conflict with the version embedded in Apache. For full
information, see `Expat Causing Apache Crash`_.
2. It may be because you're running mod_python and mod_php in the same
Apache instance, with MySQL as your database backend. In some cases,
this causes a known mod_python issue due to version conflicts in PHP and
the Python MySQL backend. There's full information in the
`mod_python FAQ entry`_.
If you continue to have problems setting up mod_python, a good thing to do is
get a barebones mod_python site working, without the Django framework. This is
an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_
details this procedure.
The next step should be to edit your test code and add an import of any
Django-specific code you're using -- your views, your models, your URLconf,
your RSS configuration, etc. Put these imports in your test handler function
and access your test URL in a browser. If this causes a crash, you've confirmed
it's the importing of Django code that causes the problem. Gradually reduce the
set of imports until it stops crashing, so as to find the specific module that
causes the problem. Drop down further into modules and look into their imports,
as necessary.
.. _Expat Causing Apache Crash: http://www.dscpl.com.au/wiki/ModPython/Articles/ExpatCausingApacheCrash
.. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp
.. _Getting mod_python Working: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking
If you get a UnicodeEncodeError
===============================
If you're taking advantage of the internationalization features of Django (see
:doc:`/topics/i18n/index`) and you intend to allow users to upload files, you must
ensure that the environment used to start Apache is configured to accept
non-ASCII file names. If your environment is not correctly configured, you
will trigger ``UnicodeEncodeError`` exceptions when calling functions like
``os.path()`` on filenames that contain non-ASCII characters.
To avoid these problems, the environment used to start Apache should contain
settings analogous to the following::
export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'
Consult the documentation for your operating system for the appropriate syntax
and location to put these configuration items; ``/etc/apache2/envvars`` is a
common location on Unix platforms. Once you have added these statements
to your environment, restart Apache.
| 17,253 | Python | .pyt | 312 | 52.092949 | 103 | 0.743454 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,197 | modpython.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/contrib/auth/handlers/modpython.py | from mod_python import apache
import os
def authenhandler(req, **kwargs):
"""
Authentication handler that checks against Django's auth database.
"""
# mod_python fakes the environ, and thus doesn't process SetEnv. This fixes
# that so that the following import works
os.environ.update(req.subprocess_env)
# apache 2.2 requires a call to req.get_basic_auth_pw() before
# req.user and friends are available.
req.get_basic_auth_pw()
# check for PythonOptions
_str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes')
options = req.get_options()
permission_name = options.get('DjangoPermissionName', None)
staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on"))
superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off"))
settings_module = options.get('DJANGO_SETTINGS_MODULE', None)
if settings_module:
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
from django.contrib.auth.models import User
from django import db
db.reset_queries()
# check that the username is valid
kwargs = {'username': req.user, 'is_active': True}
if staff_only:
kwargs['is_staff'] = True
if superuser_only:
kwargs['is_superuser'] = True
try:
try:
user = User.objects.get(**kwargs)
except User.DoesNotExist:
return apache.HTTP_UNAUTHORIZED
# check the password and any permission given
if user.check_password(req.get_basic_auth_pw()):
if permission_name:
if user.has_perm(permission_name):
return apache.OK
else:
return apache.HTTP_UNAUTHORIZED
else:
return apache.OK
else:
return apache.HTTP_UNAUTHORIZED
finally:
db.connection.close()
| 1,899 | Python | .pyt | 48 | 31.541667 | 85 | 0.644916 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,198 | modpython.py | gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/django/core/handlers/modpython.py | import os
from pprint import pformat
import sys
from warnings import warn
from django import http
from django.core import signals
from django.core.handlers.base import BaseHandler
from django.core.urlresolvers import set_script_prefix
from django.utils import datastructures
from django.utils.encoding import force_unicode, smart_str, iri_to_uri
from django.utils.log import getLogger
logger = getLogger('django.request')
# NOTE: do *not* import settings (or any module which eventually imports
# settings) until after ModPythonHandler has been called; otherwise os.environ
# won't be set up correctly (with respect to settings).
class ModPythonRequest(http.HttpRequest):
def __init__(self, req):
self._req = req
# FIXME: This isn't ideal. The request URI may be encoded (it's
# non-normalized) slightly differently to the "real" SCRIPT_NAME
# and PATH_INFO values. This causes problems when we compute path_info,
# below. For now, don't use script names that will be subject to
# encoding/decoding.
self.path = force_unicode(req.uri)
root = req.get_options().get('django.root', '')
self.django_root = root
# req.path_info isn't necessarily computed correctly in all
# circumstances (it's out of mod_python's control a bit), so we use
# req.uri and some string manipulations to get the right value.
if root and req.uri.startswith(root):
self.path_info = force_unicode(req.uri[len(root):])
else:
self.path_info = self.path
if not self.path_info:
# Django prefers empty paths to be '/', rather than '', to give us
# a common start character for URL patterns. So this is a little
# naughty, but also pretty harmless.
self.path_info = u'/'
self._post_parse_error = False
self._stream = self._req
self._read_started = False
def __repr__(self):
# Since this is called as part of error handling, we need to be very
# robust against potentially malformed input.
try:
get = pformat(self.GET)
except:
get = '<could not parse>'
if self._post_parse_error:
post = '<could not parse>'
else:
try:
post = pformat(self.POST)
except:
post = '<could not parse>'
try:
cookies = pformat(self.COOKIES)
except:
cookies = '<could not parse>'
try:
meta = pformat(self.META)
except:
meta = '<could not parse>'
return smart_str(u'<ModPythonRequest\npath:%s,\nGET:%s,\nPOST:%s,\nCOOKIES:%s,\nMETA:%s>' %
(self.path, unicode(get), unicode(post),
unicode(cookies), unicode(meta)))
def get_full_path(self):
# RFC 3986 requires self._req.args to be in the ASCII range, but this
# doesn't always happen, so rather than crash, we defensively encode it.
return '%s%s' % (self.path, self._req.args and ('?' + iri_to_uri(self._req.args)) or '')
def is_secure(self):
try:
return self._req.is_https()
except AttributeError:
# mod_python < 3.2.10 doesn't have req.is_https().
return self._req.subprocess_env.get('HTTPS', '').lower() in ('on', '1')
def _get_request(self):
if not hasattr(self, '_request'):
self._request = datastructures.MergeDict(self.POST, self.GET)
return self._request
def _get_get(self):
if not hasattr(self, '_get'):
self._get = http.QueryDict(self._req.args, encoding=self._encoding)
return self._get
def _set_get(self, get):
self._get = get
def _get_post(self):
if not hasattr(self, '_post'):
self._load_post_and_files()
return self._post
def _set_post(self, post):
self._post = post
def _get_cookies(self):
if not hasattr(self, '_cookies'):
self._cookies = http.parse_cookie(self._req.headers_in.get('cookie', ''))
return self._cookies
def _set_cookies(self, cookies):
self._cookies = cookies
def _get_files(self):
if not hasattr(self, '_files'):
self._load_post_and_files()
return self._files
def _get_meta(self):
"Lazy loader that returns self.META dictionary"
if not hasattr(self, '_meta'):
self._meta = {
'AUTH_TYPE': self._req.ap_auth_type,
'CONTENT_LENGTH': self._req.headers_in.get('content-length', 0),
'CONTENT_TYPE': self._req.headers_in.get('content-type'),
'GATEWAY_INTERFACE': 'CGI/1.1',
'PATH_INFO': self.path_info,
'PATH_TRANSLATED': None, # Not supported
'QUERY_STRING': self._req.args,
'REMOTE_ADDR': self._req.connection.remote_ip,
'REMOTE_HOST': None, # DNS lookups not supported
'REMOTE_IDENT': self._req.connection.remote_logname,
'REMOTE_USER': self._req.user,
'REQUEST_METHOD': self._req.method,
'SCRIPT_NAME': self.django_root,
'SERVER_NAME': self._req.server.server_hostname,
'SERVER_PORT': self._req.connection.local_addr[1],
'SERVER_PROTOCOL': self._req.protocol,
'SERVER_SOFTWARE': 'mod_python'
}
for key, value in self._req.headers_in.items():
key = 'HTTP_' + key.upper().replace('-', '_')
self._meta[key] = value
return self._meta
def _get_method(self):
return self.META['REQUEST_METHOD'].upper()
GET = property(_get_get, _set_get)
POST = property(_get_post, _set_post)
COOKIES = property(_get_cookies, _set_cookies)
FILES = property(_get_files)
META = property(_get_meta)
REQUEST = property(_get_request)
method = property(_get_method)
class ModPythonHandler(BaseHandler):
request_class = ModPythonRequest
def __call__(self, req):
warn(('The mod_python handler is deprecated; use a WSGI or FastCGI server instead.'),
PendingDeprecationWarning)
# mod_python fakes the environ, and thus doesn't process SetEnv. This fixes that
os.environ.update(req.subprocess_env)
# now that the environ works we can see the correct settings, so imports
# that use settings now can work
from django.conf import settings
# if we need to set up middleware, now that settings works we can do it now.
if self._request_middleware is None:
self.load_middleware()
set_script_prefix(req.get_options().get('django.root', ''))
signals.request_started.send(sender=self.__class__)
try:
try:
request = self.request_class(req)
except UnicodeDecodeError:
logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
exc_info=sys.exc_info(),
extra={
'status_code': 400,
'request': request
}
)
response = http.HttpResponseBadRequest()
else:
response = self.get_response(request)
finally:
signals.request_finished.send(sender=self.__class__)
# Convert our custom HttpResponse object back into the mod_python req.
req.content_type = response['Content-Type']
for key, value in response.items():
if key != 'content-type':
req.headers_out[str(key)] = str(value)
for c in response.cookies.values():
req.headers_out.add('Set-Cookie', c.output(header=''))
req.status = response.status_code
try:
for chunk in response:
req.write(chunk)
finally:
response.close()
return 0 # mod_python.apache.OK
def handler(req):
# mod_python hooks into this function.
return ModPythonHandler()(req)
| 8,279 | Python | .pyt | 185 | 34.367568 | 99 | 0.588148 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
4,199 | modpython.txt | gabrielfalcao_lettuce/tests/integration/lib/Django-1.2.5/docs/howto/deployment/modpython.txt | .. _howto-deployment-modpython:
============================================
How to use Django with Apache and mod_python
============================================
.. warning::
Support for mod_python will be deprecated in a future release of Django. If
you are configuring a new deployment, you are strongly encouraged to
consider using :doc:`mod_wsgi </howto/deployment/modwsgi>` or any of the
other :doc:`supported backends </howto/deployment/index>`.
.. highlight:: apache
The `mod_python`_ module for Apache_ can be used to deploy Django to a
production server, although it has been mostly superseded by the simpler
:doc:`mod_wsgi deployment option </howto/deployment/modwsgi>`.
mod_python is similar to (and inspired by) `mod_perl`_ : It embeds Python within
Apache and loads Python code into memory when the server starts. Code stays in
memory throughout the life of an Apache process, which leads to significant
performance gains over other server arrangements.
Django requires Apache 2.x and mod_python 3.x, and you should use Apache's
`prefork MPM`_, as opposed to the `worker MPM`_.
.. seealso::
* Apache is a big, complex animal, and this document only scratches the
surface of what Apache can do. If you need more advanced information about
Apache, there's no better source than `Apache's own official
documentation`_
* You may also be interested in :doc:`How to use Django with FastCGI, SCGI,
or AJP </howto/deployment/fastcgi>`.
.. _Apache: http://httpd.apache.org/
.. _mod_python: http://www.modpython.org/
.. _mod_perl: http://perl.apache.org/
.. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html
.. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html
.. _apache's own official documentation: http://httpd.apache.org/docs/
Basic configuration
===================
To configure Django with mod_python, first make sure you have Apache installed,
with the mod_python module activated.
Then edit your ``httpd.conf`` file and add the following::
<Location "/mysite/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonDebug On
</Location>
...and replace ``mysite.settings`` with the Python import path to your Django
project's settings file.
This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the
Django mod_python handler." It passes the value of :ref:`DJANGO_SETTINGS_MODULE
<django-settings-module>` so mod_python knows which settings to use.
Because mod_python does not know we are serving this site from underneath the
``/mysite/`` prefix, this value needs to be passed through to the mod_python
handler in Django, via the ``PythonOption django.root ...`` line. The value set
on that line (the last item) should match the string given in the ``<Location
...>`` directive. The effect of this is that Django will automatically strip the
``/mysite`` string from the front of any URLs before matching them against your
URLconf patterns. If you later move your site to live under ``/mysite2``, you
will not have to change anything except the ``django.root`` option in the config
file.
When using ``django.root`` you should make sure that what's left, after the
prefix has been removed, begins with a slash. Your URLconf patterns that are
expecting an initial slash will then work correctly. In the above example,
since we want to send things like ``/mysite/admin/`` to ``/admin/``, we need
to remove the string ``/mysite`` from the beginning, so that is the
``django.root`` value. It would be an error to use ``/mysite/`` (with a
trailing slash) in this case.
Note that we're using the ``<Location>`` directive, not the ``<Directory>``
directive. The latter is used for pointing at places on your filesystem,
whereas ``<Location>`` points at places in the URL structure of a Web site.
``<Directory>`` would be meaningless here.
Also, if your Django project is not on the default ``PYTHONPATH`` for your
computer, you'll have to tell mod_python where your project can be found:
.. parsed-literal::
<Location "/mysite/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonDebug On
**PythonPath "['/path/to/project'] + sys.path"**
</Location>
The value you use for ``PythonPath`` should include the parent directories of
all the modules you are going to import in your application. It should also
include the parent directory of the :ref:`DJANGO_SETTINGS_MODULE
<django-settings-module>` location. This is exactly the same situation as
setting the Python path for interactive usage. Whenever you try to import
something, Python will run through all the directories in ``sys.path`` in turn,
from first to last, and try to import from each directory until one succeeds.
Make sure that your Python source files' permissions are set such that the
Apache user (usually named ``apache`` or ``httpd`` on most systems) will have
read access to the files.
An example might make this clearer. Suppose you have some applications under
``/usr/local/django-apps/`` (for example, ``/usr/local/django-apps/weblog/`` and
so forth), your settings file is at ``/var/www/mysite/settings.py`` and you have
specified :ref:`DJANGO_SETTINGS_MODULE <django-settings-module>` as in the above
example. In this case, you would need to write your ``PythonPath`` directive
as::
PythonPath "['/usr/local/django-apps/', '/var/www'] + sys.path"
With this path, ``import weblog`` and ``import mysite.settings`` will both
work. If you had ``import blogroll`` in your code somewhere and ``blogroll``
lived under the ``weblog/`` directory, you would *also* need to add
``/usr/local/django-apps/weblog/`` to your ``PythonPath``. Remember: the
**parent directories** of anything you import directly must be on the Python
path.
.. note::
If you're using Windows, we still recommended that you use forward
slashes in the pathnames, even though Windows normally uses the backslash
character as its native separator. Apache knows how to convert from the
forward slash format to the native format, so this approach is portable and
easier to read. (It avoids tricky problems with having to double-escape
backslashes.)
This is valid even on a Windows system::
PythonPath "['c:/path/to/project'] + sys.path"
You can also add directives such as ``PythonAutoReload Off`` for performance.
See the `mod_python documentation`_ for a full list of options.
Note that you should set ``PythonDebug Off`` on a production server. If you
leave ``PythonDebug On``, your users would see ugly (and revealing) Python
tracebacks if something goes wrong within mod_python.
Restart Apache, and any request to ``/mysite/`` or below will be served by
Django. Note that Django's URLconfs won't trim the "/mysite/" -- they get passed
the full URL.
When deploying Django sites on mod_python, you'll need to restart Apache each
time you make changes to your Python code.
.. _mod_python documentation: http://modpython.org/live/current/doc-html/directives.html
Multiple Django installations on the same Apache
================================================
It's entirely possible to run multiple Django installations on the same Apache
instance. Just use ``VirtualHost`` for that, like so::
NameVirtualHost *
<VirtualHost *>
ServerName www.example.com
# ...
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</VirtualHost>
<VirtualHost *>
ServerName www2.example.com
# ...
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
</VirtualHost>
If you need to put two Django installations within the same ``VirtualHost``
(or in different ``VirtualHost`` blocks that share the same server name),
you'll need to take a special precaution to ensure mod_python's cache doesn't
mess things up. Use the ``PythonInterpreter`` directive to give different
``<Location>`` directives separate interpreters::
<VirtualHost *>
ServerName www.example.com
# ...
<Location "/something">
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonInterpreter mysite
</Location>
<Location "/otherthing">
SetEnv DJANGO_SETTINGS_MODULE mysite.other_settings
PythonInterpreter othersite
</Location>
</VirtualHost>
The values of ``PythonInterpreter`` don't really matter, as long as they're
different between the two ``Location`` blocks.
Running a development server with mod_python
============================================
If you use mod_python for your development server, you can avoid the hassle of
having to restart the server each time you make code changes. Just set
``MaxRequestsPerChild 1`` in your ``httpd.conf`` file to force Apache to reload
everything for each request. But don't do that on a production server, or we'll
revoke your Django privileges.
If you're the type of programmer who debugs using scattered ``print``
statements, note that output to ``stdout`` will not appear in the Apache
log and can even `cause response errors`_.
.. _cause response errors: http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html
If you have the need to print debugging information in a mod_python setup, you
have a few options. You can print to ``stderr`` explicitly, like so::
print >> sys.stderr, 'debug text'
sys.stderr.flush()
(note that ``stderr`` is buffered, so calling ``flush`` is necessary if you wish
debugging information to be displayed promptly.)
A more compact approach is to use an assertion::
assert False, 'debug text'
Another alternative is to add debugging information to the template of your page.
.. _serving-media-files:
Serving media files
===================
Django doesn't serve media files itself; it leaves that job to whichever Web
server you choose.
We recommend using a separate Web server -- i.e., one that's not also running
Django -- for serving media. Here are some good choices:
* lighttpd_
* Nginx_
* TUX_
* A stripped-down version of Apache_
* Cherokee_
If, however, you have no option but to serve media files on the same Apache
``VirtualHost`` as Django, here's how you can turn off mod_python for a
particular part of the site::
<Location "/media">
SetHandler None
</Location>
Just change ``Location`` to the root URL of your media files. You can also use
``<LocationMatch>`` to match a regular expression.
This example sets up Django at the site root but explicitly disables Django for
the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or
``.png``::
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
</Location>
<Location "/media">
SetHandler None
</Location>
<LocationMatch "\.(jpg|gif|png)$">
SetHandler None
</LocationMatch>
.. _lighttpd: http://www.lighttpd.net/
.. _Nginx: http://wiki.nginx.org/Main
.. _TUX: http://en.wikipedia.org/wiki/TUX_web_server
.. _Apache: http://httpd.apache.org/
.. _Cherokee: http://www.cherokee-project.com/
.. _serving-the-admin-files:
Serving the admin files
=======================
Note that the Django development server automagically serves admin media files,
but this is not the case when you use any other server arrangement. You're
responsible for setting up Apache, or whichever media server you're using, to
serve the admin files.
The admin files live in (:file:`django/contrib/admin/media`) of the Django
distribution.
Here are two recommended approaches:
1. Create a symbolic link to the admin media files from within your
document root. This way, all of your Django-related files -- code **and**
templates -- stay in one place, and you'll still be able to ``svn
update`` your code to get the latest admin templates, if they change.
2. Or, copy the admin media files so that they live within your Apache
document root.
Using "eggs" with mod_python
============================
If you installed Django from a Python egg_ or are using eggs in your Django
project, some extra configuration is required. Create an extra file in your
project (or somewhere else) that contains something like the following:
.. code-block:: python
import os
os.environ['PYTHON_EGG_CACHE'] = '/some/directory'
Here, ``/some/directory`` is a directory that the Apache Web server process can
write to. It will be used as the location for any unpacking of code the eggs
need to do.
Then you have to tell mod_python to import this file before doing anything
else. This is done using the PythonImport_ directive to mod_python. You need
to ensure that you have specified the ``PythonInterpreter`` directive to
mod_python as described above__ (you need to do this even if you aren't
serving multiple installations in this case). Then add the ``PythonImport``
line in the main server configuration (i.e., outside the ``Location`` or
``VirtualHost`` sections). For example::
PythonInterpreter my_django
PythonImport /path/to/my/project/file.py my_django
Note that you can use an absolute path here (or a normal dotted import path),
as described in the `mod_python manual`_. We use an absolute path in the
above example because if any Python path modifications are required to access
your project, they will not have been done at the time the ``PythonImport``
line is processed.
.. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs
.. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html
.. _mod_python manual: PythonImport_
__ `Multiple Django installations on the same Apache`_
Error handling
==============
When you use Apache/mod_python, errors will be caught by Django -- in other
words, they won't propagate to the Apache level and won't appear in the Apache
``error_log``.
The exception for this is if something is really wonky in your Django setup. In
that case, you'll see an "Internal Server Error" page in your browser and the
full Python traceback in your Apache ``error_log`` file. The ``error_log``
traceback is spread over multiple lines. (Yes, this is ugly and rather hard to
read, but it's how mod_python does things.)
If you get a segmentation fault
===============================
If Apache causes a segmentation fault, there are two probable causes, neither
of which has to do with Django itself.
1. It may be because your Python code is importing the "pyexpat" module,
which may conflict with the version embedded in Apache. For full
information, see `Expat Causing Apache Crash`_.
2. It may be because you're running mod_python and mod_php in the same
Apache instance, with MySQL as your database backend. In some cases,
this causes a known mod_python issue due to version conflicts in PHP and
the Python MySQL backend. There's full information in the
`mod_python FAQ entry`_.
If you continue to have problems setting up mod_python, a good thing to do is
get a barebones mod_python site working, without the Django framework. This is
an easy way to isolate mod_python-specific problems. `Getting mod_python Working`_
details this procedure.
The next step should be to edit your test code and add an import of any
Django-specific code you're using -- your views, your models, your URLconf,
your RSS configuration, etc. Put these imports in your test handler function
and access your test URL in a browser. If this causes a crash, you've confirmed
it's the importing of Django code that causes the problem. Gradually reduce the
set of imports until it stops crashing, so as to find the specific module that
causes the problem. Drop down further into modules and look into their imports,
as necessary.
.. _Expat Causing Apache Crash: http://www.dscpl.com.au/wiki/ModPython/Articles/ExpatCausingApacheCrash
.. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp
.. _Getting mod_python Working: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking
If you get a UnicodeEncodeError
===============================
If you're taking advantage of the internationalization features of Django (see
:doc:`/topics/i18n/index`) and you intend to allow users to upload files, you must
ensure that the environment used to start Apache is configured to accept
non-ASCII file names. If your environment is not correctly configured, you
will trigger ``UnicodeEncodeError`` exceptions when calling functions like
``os.path()`` on filenames that contain non-ASCII characters.
To avoid these problems, the environment used to start Apache should contain
settings analogous to the following::
export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'
Consult the documentation for your operating system for the appropriate syntax
and location to put these configuration items; ``/etc/apache2/envvars`` is a
common location on Unix platforms. Once you have added these statements
to your environment, restart Apache.
| 17,332 | Python | .pyt | 314 | 52.009554 | 103 | 0.743631 | gabrielfalcao/lettuce | 1,274 | 325 | 102 | GPL-3.0 | 9/5/2024, 5:08:58 PM (Europe/Amsterdam) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.