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
1,700
test_step_runner.py
gabrielfalcao_lettuce/tests/unit/test_step_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/>. from lettuce import step from lettuce import after from lettuce import core from lettuce import registry from lettuce.core import Step from lettuce.core import Feature from lettuce.exceptions import StepLoadingError from nose.tools import * FEATURE1 = """ Feature: Count steps ran Scenario: Total of steps ran Given I have a defined step When other step fails Then it won't reach here Then I have a defined step """ FEATURE2 = """ Feature: Find undefined steps Scenario: Undefined step can be pointed Given I have a defined step Then this one has no definition And this one also """ FEATURE3 = """ Feature: Lettuce can ignore case Scenario: On step definitions Given I define a step And DEFINE a STEP And also define A sTeP """ FEATURE4 = ''' Feature: My steps are rocking! Scenario: Step definition receive regex matched groups as parameters Given a person called "John Doe" ''' FEATURE5 = ''' Feature: My steps are rocking! Scenario: Step definition receive regex matched named groups as parameters When a foreign at "Rio de Janeiro" ''' FEATURE6 = ''' Feature: My steps are rocking! Scenario: Step definition receive regex matched named groups as parameters Then he gets a caipirinha ''' FEATURE7 = """ Feature: Many scenarios @first Scenario: 1st one Given I have a defined step Scenario: 2nd one Given I have a defined step @third Scenario: 3rd one Given I have a defined step Scenario: 4th one Given I have a defined step Scenario: 5th one Given I have a defined step """ FEATURE8 = """ Feature: Count step definitions with exceptions as failing steps Scenario: Raising exception Given I have a defined step When I have a step that raises an exception Then this step will be skipped """ FEATURE9 = """ Feature: When using behave_as, the new steps have the same scenario Scenario: The Original Scenario Given I have a step which calls the "access the scenario" step with behave_as """ FEATURE10 = """ @tag Feature: Many scenarios Scenario: 1st one Given I have a defined step Scenario: 2nd one Given I have a defined step """ def step_runner_environ(): "Make sure the test environment is what is expected" from lettuce import registry registry.clear() @step('I have a defined step') def have_a_defined_step(*args, **kw): assert True @step('other step fails') def and_another(*args, **kw): assert False, 'It should fail' @step("define a step") def define_a_step(*args, **kw): assert True @step(u'When I have a step that raises an exception') def raises_exception(step): raise Exception() @step('I have a step which calls the "(.*)" step with behave_as') def runs_some_other_step_with_behave_as(step, something_else): step.behave_as("When %(i_do_something_else)s" % {'i_do_something_else': something_else}) def step_runner_cleanup(): from lettuce import registry registry.clear() @with_setup(step_runner_environ) def test_can_count_steps_and_its_states(): "The scenario result has the steps passed, failed and skipped steps. " \ "And total steps as well." f = Feature.from_string(FEATURE1) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(len(scenario_result.steps_failed), 1) assert_equals(len(scenario_result.steps_undefined), 1) assert_equals(len(scenario_result.steps_skipped), 1) assert_equals(scenario_result.total_steps, 4) @with_setup(step_runner_environ) def test_can_point_undefined_steps(): "The scenario result has also the undefined steps." f = Feature.from_string(FEATURE2) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_undefined), 2) assert_equals(len(scenario_result.steps_passed), 1) assert_equals(scenario_result.total_steps, 3) undefined1 = scenario_result.steps_undefined[0] undefined2 = scenario_result.steps_undefined[1] assert_equals(undefined1.sentence, 'Then this one has no definition') assert_equals(undefined2.sentence, 'And this one also') @with_setup(step_runner_environ) def test_can_figure_out_why_has_failed(): "It can figure out why the test has failed" f = Feature.from_string(FEATURE1) feature_result = f.run() scenario_result = feature_result.scenario_results[0] failed_step = scenario_result.steps_failed[0] assert_equals(failed_step.why.cause, 'It should fail') assert 'Traceback (most recent call last):' in failed_step.why.traceback assert 'AssertionError: It should fail' in failed_step.why.traceback assert_equals(type(failed_step.why.exception), AssertionError) @with_setup(step_runner_environ) def test_skipped_steps_can_be_retrieved_as_steps(): "Skipped steps can be retrieved as steps" f = Feature.from_string(FEATURE1) feature_result = f.run() scenario_result = feature_result.scenario_results[0] for step in scenario_result.steps_skipped: assert_equals(type(step), Step) @with_setup(step_runner_environ) def test_ignore_case_on_step_definitions(): "By default lettuce ignore case on step definitions" f = Feature.from_string(FEATURE3) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 3) assert_equals(scenario_result.total_steps, 3) assert all([s.has_definition for s in scenario_result.scenario.steps]) @with_setup(step_runner_environ) def test_doesnt_ignore_case(): "Lettuce can, optionally consider case on step definitions" f = Feature.from_string(FEATURE3) feature_result = f.run(ignore_case=False) scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(len(scenario_result.steps_undefined), 2) assert_equals(scenario_result.total_steps, 3) assert not all([s.has_definition for s in scenario_result.scenario.steps]) @with_setup(step_runner_environ) def test_steps_are_aware_of_its_definitions(): "Steps are aware of its definitions line numbers and file names" f = Feature.from_string(FEATURE1) feature_result = f.run() scenario_result = feature_result.scenario_results[0] for step in scenario_result.steps_passed: assert step.has_definition step1 = scenario_result.steps_passed[0] assert_equals(step1.defined_at.line, 124) assert_equals(step1.defined_at.file, core.fs.relpath(__file__.rstrip("c"))) @with_setup(step_runner_environ) def test_steps_that_match_groups_takes_them_as_parameters(): "Steps that match groups takes them as parameters" @step(r'Given a ([^\s]+) called "(.*)"') def given_what_named(step, what, name): assert_equals(what, 'person') assert_equals(name, 'John Doe') f = Feature.from_string(FEATURE4) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(scenario_result.total_steps, 1) @with_setup(step_runner_environ) def test_steps_that_match_named_groups_takes_them_as_parameters(): "Steps that match named groups takes them as parameters" @step(r'When a (?P<what>\w+) at "(?P<city>.*)"') def given_action_named(step, what, city): assert_equals(what, 'foreign') assert_equals(city, 'Rio de Janeiro') f = Feature.from_string(FEATURE5) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(scenario_result.total_steps, 1) @with_setup(step_runner_environ) def test_steps_that_match_groups_and_named_groups_takes_just_named_as_params(): "Steps that match groups and named groups takes just the named as parameters" @step(r'(he|she) gets a (?P<what>\w+)') def given_action_named(step, what): assert_equals(what, 'caipirinha') f = Feature.from_string(FEATURE6) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(scenario_result.total_steps, 1) @with_setup(step_runner_environ) def test_step_definitions_takes_the_step_object_as_first_argument(): "Step definitions takes step object as first argument" FEATURE = ''' Feature: Steps as args Scenario: Steps as args When I define this one ''' @step(r'When I define this one') def when_i_define_this_one(step): assert_equals(step.sentence, 'When I define this one') f = Feature.from_string(FEATURE) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_passed), 1) assert_equals(scenario_result.total_steps, 1) @with_setup(step_runner_environ) def test_feature_can_run_only_specified_scenarios(): "Features can run only specified scenarios, by index + 1" feature = Feature.from_string(FEATURE7) scenarios_ran = [] @after.each_scenario def just_register(scenario): scenarios_ran.append(scenario.name) feature.run(scenarios=(2, 5)) assert_equals(scenarios_ran, ['2nd one', '5th one']) @with_setup(step_runner_environ) def test_feature_can_run_only_specified_scenarios_in_tags(): "Features can run only specified scenarios, by tags" feature = Feature.from_string(FEATURE7) scenarios_ran = [] @after.each_scenario def just_register(scenario): scenarios_ran.append(scenario.name) result = feature.run(tags=['first', 'third']) assert result.scenario_results assert_equals(scenarios_ran, ['1st one', '3rd one']) @with_setup(step_runner_environ) def test_scenarios_inherit_feature_tags(): "Tags applied to features are inherited by scenarios" feature = Feature.from_string(FEATURE10) scenarios_ran = [] @after.each_scenario def just_register(scenario): scenarios_ran.append(scenario.name) result = feature.run(tags=['tag']) assert result.scenario_results assert_equals(scenarios_ran, ['1st one', '2nd one']) @with_setup(step_runner_environ) def test_count_raised_exceptions_as_failing_steps(): "When a step definition raises an exception, it is marked as a failed step. " try: f = Feature.from_string(FEATURE8) feature_result = f.run() scenario_result = feature_result.scenario_results[0] assert_equals(len(scenario_result.steps_failed), 1) finally: registry.clear() def test_step_runs_subordinate_step_with_given(): global simple_thing_ran simple_thing_ran = False @step('I do something simple') def simple_thing(step): global simple_thing_ran simple_thing_ran = True @step('I do many complex things') def complex_things(step): step.given('I do something simple') runnable_step = Step.from_string('Given I do many complex things') runnable_step.run(True) assert(simple_thing_ran) del simple_thing_ran def test_step_runs_subordinate_step_with_then(): global simple_thing_ran simple_thing_ran = False @step('I do something simple') def simple_thing(step): global simple_thing_ran simple_thing_ran = True @step('I do many complex things') def complex_things(step): step.then('I do something simple') runnable_step = Step.from_string('Then I do many complex things') runnable_step.run(True) assert(simple_thing_ran) del simple_thing_ran def test_step_runs_subordinate_step_with_when(): global simple_thing_ran simple_thing_ran = False @step('I do something simple') def simple_thing(step): global simple_thing_ran simple_thing_ran = True @step('I do many complex things') def complex_things(step): step.when('I do something simple') runnable_step = Step.from_string('When I do many complex things') runnable_step.run(True) assert(simple_thing_ran) del simple_thing_ran def test_multiple_subordinate_steps_are_run(): 'When a step definition calls two subordinate step definitions (that do not fail), both should run.' @step('I run two subordinate steps') def two_subordinate_steps(step): step.behave_as(""" When I run the first sub-step And I run the second sub-step """) global first_ran global second_ran first_ran = False second_ran = False @step('I run the first sub-step$') def increment(step): global first_ran first_ran = True @step('I run the second sub-step') def increment_twice(step): global second_ran second_ran = True runnable_step = Step.from_string('Given I run two subordinate steps') runnable_step.run(True) assert_equals((first_ran, second_ran), (True, True)) del first_ran del second_ran @with_setup(step_runner_environ) def test_successful_behave_as_step_passes(): 'When a step definition calls another (successful) step definition with behave_as, that step should be a success.' runnable_step = Step.from_string('Given I have a step which calls the "define a step" step with behave_as') runnable_step.run(True) assert runnable_step.passed @with_setup(step_runner_environ) def test_successful_behave_as_step_doesnt_fail(): 'When a step definition calls another (successful) step definition with behave_as, that step should not be marked a failure.' runnable_step = Step.from_string('Given I have a step which calls the "define a step" step with behave_as') runnable_step.run(True) assert_false(runnable_step.failed) @with_setup(step_runner_environ) def test_failing_behave_as_step_doesnt_pass(): 'When a step definition calls another (failing) step definition with behave_as, that step should not be marked as success.' runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as') try: runnable_step.run(True) except: pass assert_false(runnable_step.passed) @with_setup(step_runner_environ) def test_failing_behave_as_step_fails(): 'When a step definition calls another (failing) step definition with behave_as, that step should be marked a failure.' runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as') try: runnable_step.run(True) except: pass assert runnable_step.failed @with_setup(step_runner_environ) def test_undefined_behave_as_step_doesnt_pass(): 'When a step definition calls an undefined step definition with behave_as, that step should not be marked as success.' runnable_step = Step.from_string('Given I have a step which calls the "undefined step" step with behave_as') assert_raises(AssertionError, runnable_step.run, True) assert_false(runnable_step.passed) @with_setup(step_runner_environ) def test_undefined_behave_as_step_fails(): 'When a step definition calls an undefined step definition with behave_as, that step should be marked a failure.' runnable_step = Step.from_string('Given I have a step which calls the "undefined step" step with behave_as') assert_raises(AssertionError, runnable_step.run, True) assert runnable_step.failed @with_setup(step_runner_environ) def test_failing_behave_as_step_raises_assertion(): 'When a step definition calls another (failing) step definition with behave_as, that step should be marked a failure.' runnable_step = Step.from_string('Given I have a step which calls the "other step fails" step with behave_as') assert_raises(AssertionError, runnable_step.run, True) @with_setup(step_runner_environ) def test_behave_as_step_can_access_the_scenario(): 'When a step definition calls another step definition with behave_as, the step called using behave_as should have access to the current scenario' @step('[^"]access the scenario') def access_the_scenario(step): assert_equal(step.scenario.name, 'The Original Scenario') try: f = Feature.from_string(FEATURE9) feature_result = f.run() assert feature_result.passed, 'The scenario passed to the behave_as step did not match' finally: registry.clear() @with_setup(step_runner_environ, step_runner_cleanup) def test_invalid_regex_raise_an_error(): def load_step(): @step('invalid step regex(.*') def step_with_bad_regex(step): pass assert_raises(StepLoadingError, load_step)
17,647
Python
.py
418
37.38756
149
0.72072
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,701
test_core.py
gabrielfalcao_lettuce/tests/unit/test_core.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 unittest from lettuce import core from sure import expect from nose.tools import assert_equals from nose.tools import assert_not_equals STEP_WITH_TABLE = u''' Given I have the following items in my shelf: | name | description | | Glass | a nice glass to drink grape juice | | Pasta | a pasta to cook and eat with grape juice in the glass | | Pasta | a pasta to cook and eat with grape juice in the glass | ''' def test_step_definition(): "Step definition takes a function and a step, keeps its definition " \ "relative path, and line + 1 (to consider the decorator)" def dumb(): pass definition = core.StepDefinition("FOO BAR", dumb) assert_equals(definition.function, dumb) assert_equals(definition.file, core.fs.relpath(__file__).rstrip("c")) assert_equals(definition.line, 39) def test_step_description(): "Step description takes a line and filename, " \ "and keeps the relative path for filename" description = core.StepDescription(10, __file__) assert_equals(description.file, core.fs.relpath(__file__)) assert_not_equals(description.file, __file__) assert_equals(description.line, 10) def test_scenario_description(): "Scenario description takes a scenario, filename and " \ "a string, and keeps the relative path for filename and line" string = ''' asdasdasdasd 8fg6f8g23o83g dfjdsfjsdScenario: NAMEOFSCENARIOjdkasbdkajsb Fsdad Scenario: NAMEOFSCENARIO da sodnasndjasdasd ''' class ScenarioFake: name = 'NAMEOFSCENARIO' description = core.ScenarioDescription( ScenarioFake, __file__, string, core.Language()) assert_equals(description.file, core.fs.relpath(__file__)) assert_not_equals(description.file, __file__) assert_equals(description.line, 6) def test_feature_description(): "Feature description takes a feature, filename and original " \ "string, and keeps the relative path for filename, line " \ "and description lines" string = u''' # lang: en-us Feature: FEATURE NAME! #@@$%ˆ&*)(*%$E# here comes the description of the scenario really! ''' class FakeFeature: description = 'the description\nof the scenario\n' description = core.FeatureDescription( FakeFeature, __file__, string, core.Language()) assert_equals(description.file, core.fs.relpath(__file__)) assert_not_equals(description.file, __file__) assert_equals(description.line, 3) assert_equals(description.description_at, (5, 6)) def test_step_represent_string_when_not_defined(): """Step.represent_string behaviour when not defined""" class FakeFeature: max_length = 10 class FakeScenario: feature = FakeFeature relative_path = core.fs.relpath(__file__) step = core.Step('some sentence', '', 239, __file__) step.scenario = FakeScenario assert_equals( step.represent_string('test'), " test # %s:239\n" % relative_path, ) def test_step_represent_string_when_defined(): "Step.represent_string behaviour when defined" class FakeFeature: max_length = 10 class FakeScenario: feature = FakeFeature class FakeScenarioDefinition: line = 421 file = 'should/be/filename' step = core.Step('some sentence', '', 239, "not a file") step.scenario = FakeScenario step.defined_at = FakeScenarioDefinition assert_equals( step.represent_string('foobar'), " foobar # should/be/filename:421\n", ) def test_step_represent_table(): "Step.represent_hashes" step = core.Step.from_string(STEP_WITH_TABLE) assert_equals( step.represent_hashes(), ' | name | description |\n' ' | Glass | a nice glass to drink grape juice |\n' ' | Pasta | a pasta to cook and eat with grape juice in the glass |\n' ' | Pasta | a pasta to cook and eat with grape juice in the glass |\n' ) STEP_WITH_MATRIX = u''' Given i have the following matrix: | a | b | ab | | 2 | 24 | 3 | ''' STEP_WITH_MATRIX2 = u''' Given i have the following matrix: | a | a | | 2 | a | | | 67 | ''' def test_step_represent_matrix(): "Step with a more suggestive representation for a matrix" step = core.Step.from_string(STEP_WITH_MATRIX2) assert_equals( step.represent_columns(), ' | a | a |\n' ' | 2 | a |\n' ' | | 67|\n' ) SCENARIO_OUTLINE = u''' Scenario: Regular numbers Given I do fill description with '<value_one>' And then, age with with '<and_other>' Examples: | value_one | and_other | | first| primeiro | |second |segundo| ''' def test_scenario_outline_represent_examples(): "Step.represent_hashes" step = core.Scenario.from_string(SCENARIO_OUTLINE) assert_equals( step.represent_examples(), ' | value_one | and_other |\n' ' | first | primeiro |\n' ' | second | segundo |\n' ) class TotalResultTestCase(unittest.TestCase): def test_is_success_yes(self): total = core.TotalResult() self.assertTrue(total.is_success) def test_is_success_no(self): total = core.TotalResult() total.failed_scenario_locations.append('<scenario location>') self.assertFalse(total.is_success)
6,455
Python
.py
167
33.107784
83
0.647474
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,702
test_language.py
gabrielfalcao_lettuce/tests/unit/test_language.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.core import Language def test_language_is_english_by_default(): "Language class is english by default" lang = Language() assert_equals(lang.code, 'en') assert_equals(lang.name, 'English') assert_equals(lang.native, 'English') assert_equals(lang.feature, 'Feature') assert_equals(lang.scenario, 'Scenario') assert_equals(lang.examples, 'Examples|Scenarios') assert_equals(lang.scenario_outline, 'Scenario Outline') def test_language_has_first_of(): "Language() can pick up first occurrece of a string" lang = Language() assert_equals(lang.first_of_examples, 'Examples') def test_search_language_only_in_comments(): assert_equals(Language.guess_from_string('# language: fr').code, 'fr') assert_equals(Language.guess_from_string('#language: fr ').code, 'fr') assert_equals(Language.guess_from_string(' #language: fr').code, 'fr') assert_equals(Language.guess_from_string(' # language: fr').code, 'fr') assert_equals(Language.guess_from_string('\t# language: fr').code, 'fr') assert_equals(Language.guess_from_string('# language: fr foo').code, 'fr') assert_equals(Language.guess_from_string('language: fr').code, 'en') assert_equals(Language.guess_from_string('#And my current language: fr').code, 'en')
2,142
Python
.py
41
48.853659
89
0.729794
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,703
test_server.py
gabrielfalcao_lettuce/tests/unit/test_server.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 lettuce import os import commands import sys from nose.tools import assert_equals from lettuce.fs import FileSystem current_directory = FileSystem.dirname(__file__) def test_server_threading(): """ Test django httpd threading """ FileSystem.pushd(current_directory, "django", "coconut") status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=1") assert_equals(status, 0, out)
1,228
Python
.py
31
37.387097
71
0.759026
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,704
test_strings.py
gabrielfalcao_lettuce/tests/unit/test_strings.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 strings def test_escape_if_necessary_escapes_1_char(): "strings.escape_if_necessary escapes regex if has only one char" assert_equals(strings.escape_if_necessary("$"), "[$]") assert_equals(strings.escape_if_necessary("^"), "[^]") assert_equals(strings.escape_if_necessary("#"), "[#]") assert_equals(strings.escape_if_necessary("("), "[(]") assert_equals(strings.escape_if_necessary(")"), "[)]") assert_equals(strings.escape_if_necessary("{"), "[{]") assert_equals(strings.escape_if_necessary("}"), "[}]") def test_escape_if_necessary_escapes_nothing_if_has_more_than_1_char(): "Escape if necessary does nothing if the string has more than 1 char" assert_equals(strings.escape_if_necessary("NOT ESCAPED"), "NOT ESCAPED") def test_get_stripped_lines(): "strings.get_stripped_lines strip every line, and jump empty ones" my_string = ''' first line second line ''' assert_equals( strings.get_stripped_lines(my_string), [ 'first line', 'second line' ] ) def test_get_stripped_lines_ignore_comments(): "strings.get_stripped_lines ignore lines that start with some char" my_string = ''' first line # second line ''' assert_equals( strings.get_stripped_lines(my_string, ignore_lines_starting_with="#"), [ 'first line', ] ) def test_split_wisely_splits_ignoring_case(): "strings.split_wisely splits ignoring case" my_string = 'first line\n' \ 'second Line\n' \ 'third LIne\n' \ 'fourth lINe\n' assert_equals( strings.split_wisely(my_string, 'line', strip=False), [ 'first ', 'second ', 'third ', 'fourth ' ] ) def test_split_wisely_splits_ignoring_case_and_stripping(): "strings.split_wisely splits ignoring case and stripping" my_string = ''' first line second Line third LIne fourth lINe ''' assert_equals( strings.split_wisely(my_string, 'line', strip=True), [ 'first', 'second', 'third', 'fourth' ] ) def test_wise_startswith_ignores_case(): "strings.wise_startswith ignores case" assert strings.wise_startswith("Gabriel", "g") assert strings.wise_startswith("Gabriel", "G") assert strings.wise_startswith("'Gabriel", "'") assert strings.wise_startswith("#Gabriel", "#") assert strings.wise_startswith("$Gabriel", "$") assert strings.wise_startswith("^Gabriel", "^") def test_wise_startswith_also_strips_the_string(): "strings.wise_startswith ignores case" assert strings.wise_startswith(" Gabriel", "g") assert strings.wise_startswith(" Gabriel", "G") assert strings.wise_startswith(" 'Gabriel", "'") assert strings.wise_startswith(" #Gabriel", "#") assert strings.wise_startswith(" $Gabriel", "$") assert strings.wise_startswith(" ^Gabriel", "^") def test_remove_it_accepts_regex_to_remove_all_from_string(): "strings.remove_it accepts regex and remove all matches from string" assert_equals( strings.remove_it(u"Gabriel Falcão", u"[aã]"), "Gbriel Flco" ) def test_column_width(): "strings.column_width" assert_equals( strings.column_width(u"あいうえお"), 10 ) def test_column_width_w_number_and_char(): "strings.column_width_w_number_and_char" assert_equals( strings.column_width( u"%s%c" % (u"4209", 0x4209)), 6 ) def test_rfill_simple(): "strings.rfill simple case" assert_equals( strings.rfill("ab", 10, "-"), "ab--------" ) def test_rfill_empty(): "strings.rfill empty" assert_equals( strings.rfill("", 10, "*"), "**********" ) def test_rfill_blank(): "strings.rfill blank" assert_equals( strings.rfill(" ", 10, "|"), " |||||||||" ) def test_rfill_full(): "strings.rfill full" assert_equals( strings.rfill("abcdefghij", 10, "|"), "abcdefghij" ) def test_rfill_append(): "strings.rfill append" assert_equals( strings.rfill("ab", 10, append="# path/to/file.extension: 2"), "ab # path/to/file.extension: 2" ) def test_dicts_to_string(): "strings.dicts_to_string" dicts = [ { 'name': u'Gabriel Falcão', 'age': 22 }, { 'name': 'Miguel', 'age': 19 } ] assert_equals( strings.dicts_to_string(dicts, ['name', 'age']), u"| name | age |\n" u"| Gabriel Falcão | 22 |\n" u"| Miguel | 19 |\n" ) def test_dicts_to_string_escapes_pipe(): "strings.dicts_to_string escapes pipe" dicts = [ { 'name': u'Gabriel | Falcão', 'age': 22 }, { 'name': 'Miguel | Arcanjo', 'age': 19 } ] assert_equals( strings.dicts_to_string(dicts, ['name', 'age']), u"| name | age |\n" u"| Gabriel \\| Falcão | 22 |\n" u"| Miguel \\| Arcanjo | 19 |\n" ) def test_dicts_to_string_allows_empty(): "strings.dicts_to_string allows empty" dicts = [ { 'name': u'Gabriel | Falcão', 'age': 22 }, { 'name': 'Miguel | Arcanjo' } ] assert_equals( strings.dicts_to_string(dicts, ['name', 'age']), u"| name | age |\n" u"| Gabriel \\| Falcão | 22 |\n" u"| Miguel \\| Arcanjo | |\n" ) def test_parse_hashes(): "strings.parse_hashes" keys = [u'name', u'age'] dicts = [ { u'name': u'Gabriel Falcão', u'age': u'22' }, { u'name': u'Miguel', u'age': u'33' } ] table = [ u"| name | age |\n", u"| Gabriel Falcão | 22 |\n", u"| Miguel | 33 |\n", ] got_keys, got_dicts = strings.parse_hashes(table) assert_equals(keys, got_keys) assert_equals(dicts, got_dicts) def test_parse_hashes_escapes_pipes(): "strings.parse_hashes escapes pipe" keys = [u'name', u'age'] dicts = [ { u'name': u'Gabriel | Falcão', u'age': u'22' }, { u'name': u'Miguel | Silva', u'age': u'33' } ] table = [ u"| name | age |\n", u"| Gabriel \| Falcão | 22 |\n", u"| Miguel \| Silva | 33 |\n", ] got_keys, got_dicts = strings.parse_hashes(table) assert_equals(keys, got_keys) assert_equals(dicts, got_dicts) def test_parse_hashes_allow_empty(): "strings.parse_hashes allow empty" keys = [u'name', u'age'] dicts = [ { u'name': u'Gabriel', u'age': u'22' }, { u'name': u'', u'age': u'33' }, { u'name': u'Dave', u'age': u'' } ] table = [ u"| name | age |\n", u"| Gabriel | 22 |\n", u"| | 33 |\n", u"| Dave | |\n", ] got_keys, got_dicts = strings.parse_hashes(table) assert_equals(keys, got_keys) assert_equals(dicts, got_dicts)
8,348
Python
.py
272
23.577206
78
0.55956
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,705
test_language_ru.py
gabrielfalcao_lettuce/tests/unit/test_language_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 nose.tools import assert_equals from lettuce.core import Language, Scenario, Feature SCENARIO = u""" Сценарий: Сохранение базы курсов универитета в текстовый файл Пускай имеем в базе университет следующие курсы: | Название | Длительность | | Матан | 2 года | | Основы программирования | 1 год | Когда я сохраняю базу курсову в файл 'курсы.txt' Получаю в первой строке файла 'курсы.txt' строку 'Матан:2' И во второй строке файла 'курсы.txt' строку 'Основы программирования:1' """ SCENARIO_OUTLINE1 = u''' Структура сценария: Заполнение пользователей в базу Пускай я заполняю в поле "имя" "<имя>" И я заполняю в поле "возраст" "<возраст>" Если я сохраняю форму То я вижу сообщени "Студент <имя>, возраст <возраст>, успешно занесен в базу!" Примеры: | имя | возраст | | Вася | 22 | | Петя | 30 | ''' FEATURE = u''' Функционал: Деление чисел Поскольку деление сложный процесс и люди часто допускают ошибки Нужно дать им возможность делить на калькуляторе Сценарий: Целочисленное деление Допустим я беру калькулятор Тогда я делю делимое на делитель и получаю частное | делимое | делитель | частное | | 100 | 2 | 50 | | 28 | 7 | 4 | | 0 | 5 | 0 | ''' def test_language_russian(): 'Language: RU -> Language class supports russian through code "ru"' lang = Language('ru') assert_equals(lang.code, u'ru') assert_equals(lang.name, u'Russian') assert_equals(lang.native, u'Русский') assert_equals(lang.feature, u'Функционал') assert_equals(lang.scenario, u'Сценарий') assert_equals(lang.examples, u'Примеры|Сценарии') assert_equals(lang.scenario_outline, u'Структура сценария') def test_scenario_ru_from_string(): 'Language: RU -> Scenario.from_string' ru = Language('ru') scenario = Scenario.from_string(SCENARIO, language=ru) assert_equals( scenario.name, u'Сохранение базы курсов универитета в текстовый файл' ) assert_equals( scenario.steps[0].hashes, [ {u'Название': u'Матан', u'Длительность': u'2 года'}, {u'Название': u'Основы программирования', u'Длительность': u'1 год'}, ] ) def test_scenario_outline1_ru_from_string(): 'Language: RU -> Scenario.from_string, with scenario outline, first case' ru = Language('ru') scenario = Scenario.from_string(SCENARIO_OUTLINE1, language=ru) assert_equals( scenario.name, u'Заполнение пользователей в базу' ) assert_equals( scenario.outlines, [ {u'имя': u'Вася', u'возраст': '22'}, {u'имя': u'Петя', u'возраст': '30'}, ] ) def test_feature_ptbr_from_string(): 'Language: RU -> Feature.from_string' ru = Language('ru') feature = Feature.from_string(FEATURE, language=ru) assert_equals( feature.name, u'Деление чисел' ) assert_equals( feature.description, u"Поскольку деление сложный процесс и люди часто допускают ошибки\n" u"Нужно дать им возможность делить на калькуляторе" ) (scenario, ) = feature.scenarios assert_equals( scenario.name, u'Целочисленное деление' ) assert_equals( scenario.steps[-1].hashes, [ {u'делимое': '100', u'делитель': '2', u'частное': '50'}, {u'делимое': '28', u'делитель': '7', u'частное': '4'}, {u'делимое': '0', u'делитель': '5', u'частное': '0'}, ] )
5,556
Python
.py
117
32.487179
82
0.653972
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,706
test_file_system.py
gabrielfalcao_lettuce/tests/unit/test_file_system.py
# -*- coding: utf-8 -*- import sys from StringIO import StringIO from mox import Mox from nose.tools import assert_equals from nose.tools import assert_raises from lettuce import fs as io def test_has_a_stack_list(): "FileSystem stack list" assert hasattr(io.FileSystem, 'stack'), \ 'FileSystem should have a stack' assert isinstance(io.FileSystem.stack, list), \ 'FileSystem.stack should be a list' def test_instance_stack_is_not_the_same_as_class_level(): "FileSystem stack list has different lifecycle in FileSystem objects" class MyFs(io.FileSystem): pass MyFs.stack.append('foo') MyFs.stack.append('bar') assert_equals(MyFs().stack, []) def test_pushd_appends_current_dir_to_stack_if_empty(): "Default behaviour of pushd() is adding the current dir to the stack" mox = Mox() old_os = io.os io.os = mox.CreateMockAnything() class MyFs(io.FileSystem): stack = [] @classmethod def current_dir(cls): return 'should be current dir' io.os.chdir('somewhere') mox.ReplayAll() try: assert len(MyFs.stack) is 0 MyFs.pushd('somewhere') assert len(MyFs.stack) is 2 assert_equals(MyFs.stack, ['should be current dir', 'somewhere']) mox.VerifyAll() finally: io.os = old_os def test_pushd(): "FileSystem.pushd" mox = Mox() old_os = io.os io.os = mox.CreateMockAnything() class MyFs(io.FileSystem): stack = ['first'] io.os.chdir('second') mox.ReplayAll() try: assert len(MyFs.stack) is 1 MyFs.pushd('second') assert len(MyFs.stack) is 2 assert_equals(MyFs.stack, ['first', 'second']) mox.VerifyAll() finally: io.os = old_os def test_pop_with_more_than_1_item(): "FileSystem.popd with more than 1 item" mox = Mox() old_os = io.os io.os = mox.CreateMockAnything() class MyFs(io.FileSystem): stack = ['one', 'two'] io.os.chdir('one') mox.ReplayAll() try: assert len(MyFs.stack) is 2 MyFs.popd() assert len(MyFs.stack) is 1 assert_equals(MyFs.stack, ['one']) mox.VerifyAll() finally: io.os = old_os def test_pop_with_1_item(): "FileSystem.pop behaviour with only one item" mox = Mox() old_os = io.os io.os = mox.CreateMockAnything() class MyFs(io.FileSystem): stack = ['one'] mox.ReplayAll() try: assert len(MyFs.stack) is 1 MyFs.popd() assert len(MyFs.stack) is 0 assert_equals(MyFs.stack, []) mox.VerifyAll() finally: io.os = old_os def test_pop_with_no_item(): "FileSystem.pop behaviour without items in stack" mox = Mox() old_os = io.os io.os = mox.CreateMockAnything() class MyFs(io.FileSystem): stack = [] mox.ReplayAll() try: assert len(MyFs.stack) is 0 MyFs.popd() assert len(MyFs.stack) is 0 assert_equals(MyFs.stack, []) mox.VerifyAll() finally: io.os = old_os def test_filename_with_extension(): "FileSystem.filename with extension" got = io.FileSystem.filename('/path/to/filename.jpg') assert_equals(got, 'filename.jpg') def test_filename_without_extension(): "FileSystem.filename without extension" got = io.FileSystem.filename('/path/to/filename.jpg', False) assert_equals(got, 'filename') def test_dirname(): "FileSystem.dirname" got = io.FileSystem.dirname('/path/to/filename.jpg') assert_equals(got, '/path/to') def test_exists(): "FileSystem.exists" mox = Mox() old_exists = io.exists io.exists = mox.CreateMockAnything() io.exists('some path').AndReturn('should be bool') mox.ReplayAll() try: got = io.FileSystem.exists('some path') assert_equals(got, 'should be bool') mox.VerifyAll() finally: io.exists = old_exists def test_extract_zip_non_verbose(): "FileSystem.extract_zip non-verbose" mox = Mox() class MyFs(io.FileSystem): stack = [] abspath = mox.CreateMockAnything() pushd = mox.CreateMockAnything() popd = mox.CreateMockAnything() open_raw = mox.CreateMockAnything() mkdir = mox.CreateMockAnything() mox.StubOutWithMock(io, 'zipfile') filename = 'modafoca.zip' base_path = '../to/project' full_path = '/full/path/to/project' MyFs.abspath(base_path).AndReturn(full_path) MyFs.pushd(full_path) zip_mock = mox.CreateMockAnything() io.zipfile.ZipFile(filename).AndReturn(zip_mock) file_list = [ 'settings.yml', 'app', 'app/controllers.py' ] zip_mock.namelist().AndReturn(file_list) zip_mock.read('settings.yml').AndReturn('settings.yml content') zip_mock.read('app/controllers.py').AndReturn('controllers.py content') file_mock1 = mox.CreateMockAnything() MyFs.open_raw('settings.yml', 'w').AndReturn(file_mock1) file_mock1.write('settings.yml content') file_mock1.close() MyFs.open_raw('app', 'w').AndRaise(IOError('it is a directory, dumb ass!')) MyFs.mkdir('app') file_mock2 = mox.CreateMockAnything() MyFs.open_raw('app/controllers.py', 'w').AndReturn(file_mock2) file_mock2.write('controllers.py content') file_mock2.close() MyFs.popd() mox.ReplayAll() try: MyFs.extract_zip('modafoca.zip', base_path) mox.VerifyAll() finally: mox.UnsetStubs() def test_extract_zip_verbose(): "FileSystem.extract_zip verbose" mox = Mox() sys.stdout = StringIO() class MyFs(io.FileSystem): stack = [] abspath = mox.CreateMockAnything() pushd = mox.CreateMockAnything() popd = mox.CreateMockAnything() open_raw = mox.CreateMockAnything() mkdir = mox.CreateMockAnything() mox.StubOutWithMock(io, 'zipfile') filename = 'modafoca.zip' base_path = '../to/project' full_path = '/full/path/to/project' MyFs.abspath(base_path).AndReturn(full_path) MyFs.pushd(full_path) zip_mock = mox.CreateMockAnything() io.zipfile.ZipFile(filename).AndReturn(zip_mock) file_list = [ 'settings.yml', 'app', 'app/controllers.py' ] zip_mock.namelist().AndReturn(file_list) zip_mock.read('settings.yml').AndReturn('settings.yml content') zip_mock.read('app/controllers.py').AndReturn('controllers.py content') file_mock1 = mox.CreateMockAnything() MyFs.open_raw('settings.yml', 'w').AndReturn(file_mock1) file_mock1.write('settings.yml content') file_mock1.close() MyFs.open_raw('app', 'w').AndRaise(IOError('it is a directory, dumb ass!')) MyFs.mkdir('app') file_mock2 = mox.CreateMockAnything() MyFs.open_raw('app/controllers.py', 'w').AndReturn(file_mock2) file_mock2.write('controllers.py content') file_mock2.close() MyFs.popd() mox.ReplayAll() try: MyFs.extract_zip('modafoca.zip', base_path, verbose=True) assert_equals(sys.stdout.getvalue(), 'Extracting files to /full/path/to/project\n ' \ '-> Unpacking settings.yml\n -> Unpacking app' \ '\n---> Creating directory app\n -> Unpacking' \ ' app/controllers.py\n') mox.VerifyAll() finally: mox.UnsetStubs() sys.stdout = sys.__stdout__ def test_locate_non_recursive(): "FileSystem.locate non-recursive" mox = Mox() old_glob = io.glob io.glob = mox.CreateMockAnything() base_path = '../to/project' full_path = '/full/path/to/project' class MyFs(io.FileSystem): stack = [] abspath = mox.CreateMockAnything() io.glob('%s/*match*.py' % full_path) MyFs.abspath(base_path).AndReturn(full_path) mox.ReplayAll() try: MyFs.locate(base_path, '*match*.py', recursive=False) mox.VerifyAll() finally: mox.UnsetStubs() io.glob = old_glob def test_locate_recursive(): "FileSystem.locate recursive" mox = Mox() base_path = '../to/project' full_path = '/full/path/to/project' class MyFs(io.FileSystem): stack = [] abspath = mox.CreateMockAnything() walk = mox.CreateMockAnything() io.glob('%s/*match*.py' % full_path) MyFs.abspath(base_path).AndReturn(full_path) walk_list = [ (None, None, ['file1.py', 'file2.jpg']), (None, None, ['path1/file3.png', 'path1/file4.html']) ] MyFs.walk(full_path).AndReturn(walk_list) mox.ReplayAll() try: MyFs.locate(base_path, '*match*.py', recursive=True) mox.VerifyAll() finally: mox.UnsetStubs() def test_mkdir_success(): "FileSystem.mkdir with success" mox = Mox() mox.StubOutWithMock(io, 'os') class MyFs(io.FileSystem): pass io.os.makedirs('/make/all/those/subdirs') mox.ReplayAll() try: MyFs.mkdir('/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs() def test_mkdir_ignore_dirs_already_exists(): "FileSystem.mkdir in a existent dir" mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.os, 'path') class MyFs(io.FileSystem): pass oserror = OSError() oserror.errno = 17 io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror) io.os.path.isdir('/make/all/those/subdirs').AndReturn(True) mox.ReplayAll() try: MyFs.mkdir('/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs() def test_mkdir_raises_on_oserror_errno_not_17(): "FileSystem.mkdir raises on errno not 17" mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.os, 'path') class MyFs(io.FileSystem): pass oserror = OSError() oserror.errno = 0 io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror) mox.ReplayAll() try: assert_raises(OSError, MyFs.mkdir, '/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs() def tes_mkdir_raises_when_path_is_not_a_dir(): "Test mkdir raises when path is not a dir" mox = Mox() mox.StubOutWithMock(io, 'os') mox.StubOutWithMock(io.os, 'path') class MyFs(io.FileSystem): pass oserror = OSError() oserror.errno = 17 io.os.makedirs('/make/all/those/subdirs').AndRaise(oserror) io.os.isdir('/make/all/those/subdirs').AndReturn(False) mox.ReplayAll() try: assert_raises(OSError, MyFs.mkdir, '/make/all/those/subdirs') mox.VerifyAll() finally: mox.UnsetStubs()
10,824
Python
.py
330
26.190909
79
0.633516
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,707
test_feature_parser.py
gabrielfalcao_lettuce/tests/unit/test_feature_parser.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 sure import expect from sure.old import that from lettuce import step from lettuce.core import Scenario from lettuce.core import Feature from lettuce.core import Background from lettuce.core import HashList from lettuce.exceptions import LettuceSyntaxError from nose.tools import assert_equals FEATURE1 = """ Feature: Rent movies Scenario: Renting a featured movie Given I have the following movies in my database | Name | Rating | New | Available | | Matrix Revolutions | 4 stars | no | 6 | | Iron Man 2 | 5 stars | yes | 11 | When the client 'John Doe' rents 'Iron man 2' Then he needs to pay 10 bucks Scenario: Renting a non-featured movie Given I have the following movies in my database | Name | Rating | New | Available | | A night at the museum 2 | 3 stars | yes | 9 | | Matrix Revolutions | 4 stars | no | 6 | When the client 'Mary Doe' rents 'Matrix Revolutions' Then she needs to pay 6 bucks Scenario: Renting two movies allows client to take one more without charge Given I have the following movies in my database | Name | Rating | New | Available | | A night at the museum 2 | 3 stars | yes | 9 | | Matrix Revolutions | 4 stars | no | 6 | | Iron Man 2 | 5 stars | yes | 11 | When the client 'Jack' rents 'Iron man 2' And also rents 'Iron man 2' and 'A night at the museum 2' Then he needs to pay 16 bucks """ FEATURE2 = """ Feature: Division In order to avoid silly mistakes Cashiers must be able to calculate a fraction Scenario: Regular numbers * I have entered 3 into the calculator * I have entered 2 into the calculator * I press divide * the result should be 1.5 on the screen """ FEATURE3 = """ Feature: A long line as feature name will define the max length of the feature In order to describe my features I want to add description on them Scenario: Regular numbers Nothing to do """ FEATURE4 = """ Feature: Big sentence As a clever guy I want to describe this Feature So that I can take care of my Scenario Scenario: Regular numbers Given a huge sentence, that have so many characters And another one, very tiny """ FEATURE5 = """ Feature: Big table Scenario: Regular numbers Given that I have these items: | description | | this is such a huge description within a table, the maxlengh will be huge | | this is another description within a table | """ FEATURE6 = """ Feature: Big scenario outline Scenario: Regular numbers Given I do fill 'description' with '<value_two>' Examples: | value_two | | this is such a huge value within a table, the maxlengh will be damn big | | this is another description within a table | """ FEATURE7 = """ Feature: Big table Scenario: Regular numbers Given that I have these items: | description-long-as-hell | name-that-will-make-my-max-length-big | | one | john | | two | baby | """ FEATURE8 = """ Feature: Big scenario outline Scenario: big scenario outlines Given I do fill 'description' with '<value_two>' Examples: | value_two_thousand_and_three | another_one | and_even_bigger | | 1 | um | one | | 2 | dois | two | """ FEATURE9 = """ Feature: Big scenario outline Scenario: big scenario outlines Given I do fill 'description' with '<value_two>' Examples: | value_two_thousand_and_three_biiiiiiiiiiiiiiiiiiiiiiiiiiiiig | | 1 | | 2 | | 3 | """ FEATURE10 = """ Feature: Big sentence As a clever guy I want to describe this Feature So that I can take care of my Scenario Scenario: Regular numbers Given a huge sentence, that have so many characters And another one, very tiny # Feature: Big sentence # As a clever guy # I want to describe this Feature # So that I can take care of my Scenario # Scenario: Regular numbers # Given a huge sentence, that have so many characters # And another one, very tiny """ FEATURE11 = """ Feature: Yay tags @many @other @basic @tags @here @:) Scenario: Double Yay Given this scenario has tags Then it can be inspected from within the object """ FEATURE12 = """ Feature: Yay tags and many scenarios @many @other @basic @tags @here @:) Scenario: Holy tag, Batman Given this scenario has tags Then it can be inspected from within the object @only @a-few @tags Scenario: Holy guacamole Given this scenario has tags Then it can be inspected from within the object """ FEATURE13 = ''' Feature: correct matching @runme Scenario: Holy tag, Batman Given this scenario has tags Then it can be inspected from within the object Scenario: This has no tags Given this scenario has no tags Then I fill my email with [email protected] @slow Scenario: this is slow Given this scenario has tags When I fill my email with "[email protected]" Then it can be inspected from within the object Scenario: Also without tags Given this scenario has no tags Then I fill my email with '[email protected]' ''' FEATURE14 = """ Feature: Extra whitespace feature I want to match scenarios with extra whitespace Scenario: Extra whitespace scenario Given this scenario, which has extra leading whitespace Then the scenario definition should still match """ FEATURE15 = """ Feature: Redis database server Scenario: Bootstraping Redis role Given I have a an empty running farm When I add redis role to this farm Then I expect server bootstrapping as M1 And scalarizr version is last in M1 And redis is running on M1 Scenario: Restart scalarizr When I reboot scalarizr in M1 And see 'Scalarizr terminated' in M1 log Then scalarizr process is 2 in M1 And not ERROR in M1 scalarizr log @rebundle Scenario: Rebundle server When I create server snapshot for M1 Then Bundle task created for M1 And Bundle task becomes completed for M1 @rebundle Scenario: Use new role Given I have a an empty running farm When I add to farm role created by last bundle task Then I expect server bootstrapping as M1 @rebundle Scenario: Restart scalarizr after bundling When I reboot scalarizr in M1 And see 'Scalarizr terminated' in M1 log Then scalarizr process is 2 in M1 And not ERROR in M1 scalarizr log Scenario: Bundling data When I trigger databundle creation Then Scalr sends DbMsr_CreateDataBundle to M1 And Scalr receives DbMsr_CreateDataBundleResult from M1 And Last databundle date updated to current Scenario: Modifying data Given I have small-sized database 1 on M1 When I create a databundle And I terminate server M1 Then I expect server bootstrapping as M1 And M1 contains database 1 Scenario: Reboot server When I reboot server M1 Then Scalr receives RebootStart from M1 And Scalr receives RebootFinish from M1 Scenario: Backuping data on Master When I trigger backup creation Then Scalr sends DbMsr_CreateBackup to M1 And Scalr receives DbMsr_CreateBackupResult from M1 And Last backup date updated to current Scenario: Setup replication When I increase minimum servers to 2 for redis role Then I expect server bootstrapping as M2 And scalarizr version is last in M2 And M2 is slave of M1 Scenario: Restart scalarizr in slave When I reboot scalarizr in M2 And see 'Scalarizr terminated' in M2 log Then scalarizr process is 2 in M2 And not ERROR in M2 scalarizr log Scenario: Slave force termination When I force terminate M2 Then Scalr sends HostDown to M1 And not ERROR in M1 scalarizr log And redis is running on M1 And scalarizr process is 2 in M1 Then I expect server bootstrapping as M2 And not ERROR in M1 scalarizr log And not ERROR in M2 scalarizr log And redis is running on M1 @ec2 Scenario: Slave delete EBS When I know M2 ebs storage And M2 ebs status is in-use Then I terminate server M2 with decrease And M2 ebs status is deleting And not ERROR in M1 scalarizr log @ec2 Scenario: Setup replication for EBS test When I increase minimum servers to 2 for redis role Then I expect server bootstrapping as M2 And M2 is slave of M1 Scenario: Writing on Master, reading on Slave When I create database 2 on M1 Then M2 contains database 2 Scenario: Slave -> Master promotion Given I increase minimum servers to 3 for redis role And I expect server bootstrapping as M3 When I create database 3 on M1 And I terminate server M1 with decrease Then Scalr sends DbMsr_PromoteToMaster to N1 And Scalr receives DbMsr_PromoteToMasterResult from N1 And Scalr sends DbMsr_NewMasterUp to all And M2 contains database 3 @restart_farm Scenario: Restart farm When I stop farm And wait all servers are terminated Then I start farm And I expect server bootstrapping as M1 And scalarizr version is last in M1 And redis is running on M1 And M1 contains database 3 Then I expect server bootstrapping as M2 And M2 is slave of M1 And M2 contains database 3 """ FEATURE18 = """ @feature_runme Feature: correct matching @runme1 Scenario: Holy tag, Batman [1] Given this scenario has tags Then it can be inspected from within the object @runme2 Scenario: Holy tag2, Batman (2) Given this scenario has other tags Then it can be inspected from within the object even with the table | What | Is | This | | It | is | TABLE | @runme3 Scenario: Holy tag3, Batman Given this scenario has even more tags Then it can be inspected from within the object """ FEATURE19 = """ Feature: correct matching @runme1 Scenario: Holy tag, Batman (1) Given this scenario has tags Then it can be inspected from within the object @runme2 Scenario: Holy tag2, Batman [2] Given this scenario has other tags Then it can be inspected from within the object """ FEATURE16 = """ Feature: Movie rental As a rental store owner I want to keep track of my clients So that I can manage my business better Background: Given I have the following movies in my database: | Name | Rating | New | Available | | Matrix Revolutions | 4 stars | no | 6 | | Iron Man 2 | 5 stars | yes | 11 | And the following clients: | Name | | John Doe | | Foo Bar | Scenario: Renting a featured movie Given the client 'John Doe' rents 'Iron Man 2' Then there are 10 more left Scenario: Renting an old movie Given the client 'Foo Bar' rents 'Matrix Revolutions' Then there are 5 more left """ FEATURE17 = """ Feature: Movie rental without MMF Background: Given I have the following movies in my database: | Name | Rating | New | Available | | Matrix Revolutions | 4 stars | no | 6 | | Iron Man 2 | 5 stars | yes | 11 | And the following clients: | Name | | John Doe | | Foo Bar | Scenario: Renting a featured movie Given the client 'John Doe' rents 'Iron Man 2' Then there are 10 more left """ FEATURE20 = """ Feature: My scenarios have no name Scenario: Given this scenario raises a syntax error """ FEATURE21 = """ Feature: Taming the tag parser Background: Given the email addresses: | name | email | | Chuck Norris | [email protected] | Then the next scenario has only the tags it's supposed to Scenario: I'm isolated Given I am parsed Then this scenario has only zero tags @tag Scenario: I'm so isolated Given I am parsed Then this scenario has one tag """ FEATURE22 = """ Feature: one tag in the first scenario @onetag Scenario: This is the first scenario Given I am parsed Then this scenario has one tag """ FEATURE23 = """ Feature: three tags in the first scenario @onetag @another @$%^&even-weird_chars Scenario: This is the first scenario Given I am parsed Then this scenario has three tags """ def test_feature_has_repr(): "Feature implements __repr__ nicely" feature = Feature.from_string(FEATURE1) expect(repr(feature)).to.equal('<Feature: "Rent movies">') def test_scenario_has_name(): "It should extract the name string from the scenario" feature = Feature.from_string(FEATURE1) assert isinstance(feature, Feature) expect(feature.name).to.equal("Rent movies") def test_feature_has_scenarios(): "A feature object should have a list of scenarios" feature = Feature.from_string(FEATURE1) expect(feature.scenarios).to.be.a(list) expect(feature.scenarios).to.have.length_of(3) expected_scenario_names = [ "Renting a featured movie", "Renting a non-featured movie", "Renting two movies allows client to take one more without charge", ] for scenario, expected_name in zip(feature.scenarios, expected_scenario_names): expect(scenario).to.be.a(Scenario) expect(scenario.name).to.equal(expected_name) expect(feature.scenarios[1].steps[0].keys).to.equal( ('Name', 'Rating', 'New', 'Available')) expect(list(feature.scenarios[1].steps[0].hashes)).to.equal([ { 'Name': 'A night at the museum 2', 'Rating': '3 stars', 'New': 'yes', 'Available': '9', }, { 'Name': 'Matrix Revolutions', 'Rating': '4 stars', 'New': 'no', 'Available': '6', }, ]) def test_can_parse_feature_description(): "A feature object should have a description" feature = Feature.from_string(FEATURE2) assert_equals( feature.description, "In order to avoid silly mistakes\n" "Cashiers must be able to calculate a fraction" ) expected_scenario_names = ["Regular numbers"] 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_scenarios_parsed_by_feature_has_feature(): "Scenarios parsed by features has feature" feature = Feature.from_string(FEATURE2) for scenario in feature.scenarios: assert_equals(scenario.feature, feature) def test_feature_max_length_on_scenario(): "The max length of a feature considering when the scenario is longer than " \ "the remaining things" feature = Feature.from_string(FEATURE1) assert_equals(feature.max_length, 76) def test_feature_max_length_on_feature_description(): "The max length of a feature considering when one of the description lines " \ "of the feature is longer than the remaining things" feature = Feature.from_string(FEATURE2) assert_equals(feature.max_length, 47) def test_feature_max_length_on_feature_name(): "The max length of a feature considering when the name of the feature " \ "is longer than the remaining things" feature = Feature.from_string(FEATURE3) assert_equals(feature.max_length, 78) def test_feature_max_length_on_step_sentence(): "The max length of a feature considering when the some of the step sentences " \ "is longer than the remaining things" feature = Feature.from_string(FEATURE4) assert_equals(feature.max_length, 55) def test_feature_max_length_on_step_with_table(): "The max length of a feature considering when the table of some of the steps " \ "is longer than the remaining things" feature = Feature.from_string(FEATURE5) assert_equals(feature.max_length, 83) def test_feature_max_length_on_step_with_table_keys(): "The max length of a feature considering when the table keys of some of the " \ "steps are longer than the remaining things" feature = Feature.from_string(FEATURE7) assert_equals(feature.max_length, 74) def test_feature_max_length_on_scenario_outline(): "The max length of a feature considering when the table of some of the " \ "scenario oulines is longer than the remaining things" feature = Feature.from_string(FEATURE6) assert_equals(feature.max_length, 79) def test_feature_max_length_on_scenario_outline_keys(): "The max length of a feature considering when the table keys of the " \ "scenario oulines are longer than the remaining things" feature1 = Feature.from_string(FEATURE8) feature2 = Feature.from_string(FEATURE9) assert_equals(feature1.max_length, 68) assert_equals(feature2.max_length, 68) def test_description_on_long_named_feature(): "Can parse the description on long named features" feature = Feature.from_string(FEATURE3) assert_equals( feature.description, "In order to describe my features\n" "I want to add description on them", ) def test_description_on_big_sentenced_steps(): "Can parse the description on long sentenced steps" feature = Feature.from_string(FEATURE4) assert_equals( feature.description, "As a clever guy\n" "I want to describe this Feature\n" "So that I can take care of my Scenario", ) def test_comments(): "It should ignore lines that start with #, despite white spaces" feature = Feature.from_string(FEATURE10) assert_equals(feature.max_length, 55) def test_single_scenario_single_scenario(): "Features should have at least the first scenario parsed with tags" feature = Feature.from_string(FEATURE11) first_scenario = feature.scenarios[0] assert that(first_scenario.tags).deep_equals([ 'many', 'other', 'basic', 'tags', 'here', ':)']) def test_single_feature_single_tag(): "All scenarios within a feature inherit the feature's tags" feature = Feature.from_string(FEATURE18) assert that(feature.scenarios[0].tags).deep_equals([ 'runme1', 'feature_runme']) assert that(feature.scenarios[1].tags).deep_equals([ 'runme2', 'feature_runme']) assert that(feature.scenarios[2].tags).deep_equals([ 'runme3', 'feature_runme']) def test_single_scenario_many_scenarios(): "Untagged scenario following a tagged one should have no tags" @step('this scenario has tags') def scenario_has_tags(step): assert step.scenario.tags @step('this scenario has no tags') def scenario_has_no_tags(step): assert not step.scenario.tags @step('it can be inspected from within the object') def inspected_within_object(step): assert step.scenario.tags @step(r'fill my email with [\'"]?([^\'"]+)[\'"]?') def fill_email(step, email): assert that(email).equals('[email protected]') feature = Feature.from_string(FEATURE13) first_scenario = feature.scenarios[0] assert that(first_scenario.tags).equals(['runme']) second_scenario = feature.scenarios[1] assert that(second_scenario.tags).equals([]) third_scenario = feature.scenarios[2] assert that(third_scenario.tags).equals(['slow']) last_scenario = feature.scenarios[3] assert that(last_scenario.tags).equals([]) result = feature.run() print print for sr in result.scenario_results: for failed in sr.steps_failed: print "+" * 10 print print failed.why.cause print print "+" * 10 print print assert result.passed def test_scenarios_with_extra_whitespace(): "Make sure that extra leading whitespace is ignored" feature = Feature.from_string(FEATURE14) assert_equals(type(feature.scenarios), list) assert_equals(len(feature.scenarios), 1, "It should have 1 scenario") assert_equals(feature.name, "Extra whitespace feature") scenario = feature.scenarios[0] assert_equals(type(scenario), Scenario) assert_equals(scenario.name, "Extra whitespace scenario") def test_scenarios_parsing(): "Tags are parsed correctly" feature = Feature.from_string(FEATURE15) scenarios_and_tags = [(s.name, s.tags) for s in feature.scenarios] scenarios_and_tags.should.equal([ ('Bootstraping Redis role', []), ('Restart scalarizr', []), ('Rebundle server', [u'rebundle']), ('Use new role', [u'rebundle']), ('Restart scalarizr after bundling', [u'rebundle']), ('Bundling data', []), ('Modifying data', []), ('Reboot server', []), ('Backuping data on Master', []), ('Setup replication', []), ('Restart scalarizr in slave', []), ('Slave force termination', []), ('Slave delete EBS', [u'ec2']), ('Setup replication for EBS test', [u'ec2']), ('Writing on Master, reading on Slave', []), ('Slave -> Master promotion', []), ('Restart farm', [u'restart_farm']), ]) def test_scenarios_with_special_characters(): "Make sure that regex special characters in the scenario names are ignored" feature = Feature.from_string(FEATURE19) assert that(feature.scenarios[0].tags).deep_equals([ 'runme1']) assert that(feature.scenarios[1].tags).deep_equals([ 'runme2']) def test_background_parsing_with_mmf(): feature = Feature.from_string(FEATURE16) expect(feature.description).to.equal( "As a rental store owner\n" "I want to keep track of my clients\n" "So that I can manage my business better" ) expect(feature).to.have.property('background').being.a(Background) expect(feature.background).to.have.property('steps') expect(feature.background.steps).to.have.length_of(2) step1, step2 = feature.background.steps step1.sentence.should.equal( 'Given I have the following movies in my database:') step1.hashes.should.equal(HashList(step1, [ { u'Available': u'6', u'Rating': u'4 stars', u'Name': u'Matrix Revolutions', u'New': u'no', }, { u'Available': u'11', u'Rating': u'5 stars', u'Name': u'Iron Man 2', u'New': u'yes', }, ])) step2.sentence.should.equal( 'And the following clients:') step2.hashes.should.equal(HashList(step2, [ {u'Name': u'John Doe'}, {u'Name': u'Foo Bar'}, ])) def test_background_parsing_without_mmf(): feature = Feature.from_string(FEATURE17) expect(feature.description).to.be.empty expect(feature).to.have.property('background').being.a(Background) expect(feature.background).to.have.property('steps') expect(feature.background.steps).to.have.length_of(2) step1, step2 = feature.background.steps step1.sentence.should.equal( 'Given I have the following movies in my database:') step1.hashes.should.equal(HashList(step1, [ { u'Available': u'6', u'Rating': u'4 stars', u'Name': u'Matrix Revolutions', u'New': u'no', }, { u'Available': u'11', u'Rating': u'5 stars', u'Name': u'Iron Man 2', u'New': u'yes', }, ])) step2.sentence.should.equal( 'And the following clients:') step2.hashes.should.equal(HashList(step2, [ {u'Name': u'John Doe'}, {u'Name': u'Foo Bar'}, ])) def test_syntax_error_for_scenarios_with_no_name(): ("Trying to parse features with unnamed " "scenarios will cause a syntax error") expect(Feature.from_string).when.called_with(FEATURE20).to.throw( LettuceSyntaxError, ('In the feature "My scenarios have no name", ' 'scenarios must have a name, make sure to declare ' 'a scenario like this: `Scenario: name of your scenario`') ) def test_scenario_post_email(): ("Having a scenario which the body has an email address; " "Then the following scenario should have no " "tags related to the email") feature = Feature.from_string(FEATURE21) scenario1, scenario2 = feature.scenarios scenario1.tags.should.be.empty scenario2.tags.should.equal(['tag']) def test_feature_first_scenario_tag_extraction(): ("A feature object should be able to find the single tag " "belonging to the first scenario") feature = Feature.from_string(FEATURE22) assert that(feature.scenarios[0].tags).deep_equals([ 'onetag']) def test_feature_first_scenario_tags_extraction(): ("A feature object should be able to find the tags " "belonging to the first scenario") feature = Feature.from_string(FEATURE23) assert that(feature.scenarios[0].tags).deep_equals([ 'onetag', 'another', '$%^&even-weird_chars'])
27,405
Python
.py
694
33.456772
84
0.656408
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,708
test_registry.py
gabrielfalcao_lettuce/tests/unit/test_registry.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.registry import _function_matches, StepDict from lettuce.exceptions import StepLoadingError from nose.tools import assert_raises, assert_equal def test_function_matches_compares_with_abs_path(): u"lettuce.registry._function_matches() should compare callback filenames with abspath" class fakecallback1: class func_code: co_filename = "/some/path/to/some/../file.py" co_firstlineno = 1 class fakecallback2: class func_code: co_filename = "/some/path/to/file.py" co_firstlineno = 1 assert _function_matches(fakecallback1, fakecallback2), \ 'the callbacks should have matched' def test_StepDict_raise_StepLoadingError_if_load_first_argument_is_not_a_regex(): u"lettuce.STEP_REGISTRY.load(step, func) should raise an error if step is not a regex" steps = StepDict() test_load = lambda: steps.load("an invalid regex;)", lambda: "") assert_raises(StepLoadingError, test_load) def test_StepDict_can_load_a_step_composed_of_a_regex_and_a_function(): u"lettuce.STEP_REGISTRY.load(step, func) append item(step, func) to STEP_REGISTRY" steps = StepDict() func = lambda: "" step = "a step to test" steps.load(step, func) assert (step in steps) assert_equal(steps[step], func) def test_StepDict_load_a_step_return_the_given_function(): u"lettuce.STEP_REGISTRY.load(step, func) returns func" steps = StepDict() func = lambda: "" assert_equal(steps.load("another step", func), func) def test_StepDict_can_extract_a_step_sentence_from_function_name(): u"lettuce.STEP_REGISTRY._extract_sentence(func) parse func name and return a sentence" steps = StepDict() def a_step_sentence(): pass assert_equal("A step sentence", steps._extract_sentence(a_step_sentence)) def test_StepDict_can_extract_a_step_sentence_from_function_doc(): u"lettuce.STEP_REGISTRY._extract_sentence(func) parse func doc and return a sentence" steps = StepDict() def a_step_func(): """A step sentence""" pass assert_equal("A step sentence", steps._extract_sentence(a_step_func)) def test_StepDict_can_load_a_step_from_a_function(): u"lettuce.STEP_REGISTRY.load_func(func) append item(step, func) to STEP_REGISTRY" steps = StepDict() def a_step_to_test(): pass steps.load_func(a_step_to_test) expected_sentence = "A step to test" assert (expected_sentence in steps) assert_equal(steps[expected_sentence], a_step_to_test) def test_StepDict_can_load_steps_from_an_object(): u"lettuce.STEP_REGISTRY.load_steps(obj) append all obj methods to STEP_REGISTRY" steps = StepDict() class LotsOfSteps: def step_1(self): pass def step_2(self): """Doing something""" pass step_list = LotsOfSteps() steps.load_steps(step_list) expected_sentence1 = "Step 1" expected_sentence2 = "Doing something" assert (expected_sentence1 in steps) assert (expected_sentence2 in steps) assert_equal(steps[expected_sentence1], step_list.step_1) assert_equal(steps[expected_sentence2], step_list.step_2) def test_StepDict_can_exclude_methods_when_load_steps(): u"lettuce.STEP_REGISTRY.load_steps(obj) don't load exluded attr in STEP_REGISTRY" steps = StepDict() class LotsOfSteps: exclude = ["step_1"] def step_1(self): pass def step_2(self): """Doing something""" pass step_list = LotsOfSteps() steps.load_steps(step_list) expected_sentence1 = "Step 1" expected_sentence2 = "Doing something" assert (expected_sentence1 not in steps) assert (expected_sentence2 in steps) def test_StepDict_can_exclude_callable_object_when_load_steps(): u"lettuce.STEP_REGISTRY.load_steps(obj) don't load callable objets in STEP_REGISTRY" steps = StepDict() class NoStep: class NotAStep(object): def __call__(self): pass no_step = NoStep() steps.load_steps(no_step) assert len(steps) == 0
4,903
Python
.py
114
37.491228
90
0.700797
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,709
manage.py
gabrielfalcao_lettuce/tests/unit/django/coconut/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coconut.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
250
Python
.py
7
32.571429
71
0.7375
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,710
settings.py
gabrielfalcao_lettuce/tests/unit/django/coconut/coconut/settings.py
# Django settings for coconut project. DEBUG = True ROOT_URLCONF = 'coconut.urls' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', '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', 'coconut' ) SECRET_KEY = 'secret'
730
Python
.py
18
35.833333
108
0.535966
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,711
urls.py
gabrielfalcao_lettuce/tests/unit/django/coconut/coconut/urls.py
from django.conf.urls import patterns, include, url from .views import WaitView urlpatterns = patterns('', url(r'^$', WaitView.as_view(), name='home'), )
159
Python
.py
5
29.8
51
0.718954
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,712
wsgi.py
gabrielfalcao_lettuce/tests/unit/django/coconut/coconut/wsgi.py
""" WSGI config for coconut project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coconut.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
1,136
Python
.py
22
50.363636
79
0.820397
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,713
views.py
gabrielfalcao_lettuce/tests/unit/django/coconut/coconut/views.py
import time from django.views.generic import View from django.http import HttpResponse class WaitView(View): def get(self, *args, **kwargs): time.sleep(3) return HttpResponse("OK")
204
Python
.py
7
24.857143
37
0.726804
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,714
threading_server.py
gabrielfalcao_lettuce/tests/unit/django/coconut/coconut/features/threading_server.py
# -*- coding: utf-8 -*- import urllib import time from lettuce import step from lettuce.django import django_url from threading import Thread, activeCount from nose.tools import * class ThreadUrlVisit(Thread): def __init__(self, url): super(ThreadUrlVisit, self).__init__() self.url = django_url(url) self.start_time = None self.end_time = None def run(self): self.start_time = time.time() try: resp = urllib.urlopen(self.url) assert_equals(resp.read(), "OK") finally: self.end_time = time.time() @step(u'Given I navigate to "([^"]*)" with (\d+) threads') def given_i_navigate_to_group1_with_group2_threads(step, url, threads): step.scenario.started_threads = [] step.scenario.start_threads = time.time() for i in xrange(int(threads)): thread = ThreadUrlVisit(url) step.scenario.started_threads.append(thread) thread.start() @step(u'Then I see (\d+) threads in server execution') def then_i_see_threads_in_server_execution(step, count): current_count = activeCount() assert_equals(str(current_count), count) @step(u'Then I wait all requests') def then_i_wait_all_requests(step): while activeCount() != 1: pass step.scenario.end_threads = time.time() @step(u'Then all requests was finishing in pararell mode') def then_all_requests_was_finishing_in_pararell_mode(step): end_times = [t.end_time for t in step.scenario.started_threads] max_time = max(end_times) min_time = min(end_times) total_time = max_time-min_time assert total_time < 20
1,666
Python
.py
44
31.704545
71
0.674286
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,715
test_alfaces.py
gabrielfalcao_lettuce/tests/integration/test_alfaces.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 time import commands import multiprocessing from tests.asserts import assert_equals, assert_not_equals from lettuce.fs import FileSystem current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_django_agains_alfaces(): 'running the "harvest" django command with verbosity 3' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color") assert_equals(status, 0, out) assert "Test the django app DO NOTHING" in out assert "Test the django app FOO BAR" in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_django_background_server_running_in_background(): 'the django builtin server fails if the HTTP port is not available' import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") raise SystemExit() def runserver(): application = tornado.web.Application([ (r"/", MainHandler), ]) application.listen(8000) tornado.ioloop.IOLoop.instance().start() server = multiprocessing.Process(target=runserver) server.start() time.sleep(1) # the child process take some time to get up e = 'Lettuce could not run the builtin Django server at 0.0.0.0:8000"\n' \ 'maybe you forgot a "runserver" instance running ?\n\n' \ 'well if you really do not want lettuce to run the server ' \ 'for you, then just run:\n\n' \ 'python manage.py --no-server' try: status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color") assert_equals(out, e) assert_not_equals(status, 0) finally: os.kill(server.pid, 9) @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_django_background_server_running_in_background_with_custom_port(): 'the harvest command should take a --port argument' import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") raise SystemExit() def runserver(): application = tornado.web.Application([ (r"/", MainHandler), ]) application.listen(9889) tornado.ioloop.IOLoop.instance().start() server = multiprocessing.Process(target=runserver) server.start() time.sleep(1) # the child process take some time to get up e = 'Lettuce could not run the builtin Django server at 0.0.0.0:9889"\n' \ 'maybe you forgot a "runserver" instance running ?\n\n' \ 'well if you really do not want lettuce to run the server ' \ 'for you, then just run:\n\n' \ 'python manage.py --no-server' try: status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --port=9889") assert_equals(out, e) assert_not_equals(status, 0) finally: os.kill(server.pid, 9) @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_limit_by_app_getting_all_apps_by_comma(): 'running "harvest" with --apps=multiple,apps,separated,by,comma' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --apps=foobar,donothing") assert_equals(status, 0, out) assert "Test the django app DO NOTHING" in out assert "Test the django app FOO BAR" in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_limit_by_app_getting_one_app(): 'running "harvest" with --apps=one_app' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --apps=foobar") assert_equals(status, 0, out) assert "Test the django app DO NOTHING" not in out assert "Test the django app FOO BAR" in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_excluding_apps_separated_by_comma(): 'running "harvest" with --avoid-apps=multiple,apps' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --avoid-apps=donothing,foobar") assert_equals(status, 0, out) assert "Test the django app DO NOTHING" not in out assert "Test the django app FOO BAR" not in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_excluding_app(): 'running "harvest" with --avoid-apps=one_app' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --avoid-apps=donothing") assert_equals(status, 0, out) assert "Test the django app DO NOTHING" not in out assert "Test the django app FOO BAR" in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_running_only_apps_within_lettuce_apps_setting(): 'running the "harvest" will run only on configured apps if the ' \ 'setting LETTUCE_APPS is set' status, out = commands.getstatusoutput( "python manage.py harvest --settings=onlyfoobarsettings --verbosity=3 --no-color") assert_equals(status, 0, out) assert "Test the django app FOO BAR" in out assert "Test the django app DO NOTHING" not in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_running_all_apps_but_lettuce_avoid_apps(): 'running the "harvest" will run all apps but those within ' \ 'LETTUCE_AVOID_APPS' status, out = commands.getstatusoutput( "python manage.py harvest --settings=allbutfoobarsettings " \ "--verbosity=3 --no-color") assert_equals(status, 0, out) assert "Test the django app FOO BAR" not in out assert "Test the django app DO NOTHING" in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_ignores_settings_avoid_apps_if_apps_argument_is_passed(): 'even if all apps are avoid in settings, it is possible to run a single ' \ 'app by --apps argument' status, out = commands.getstatusoutput( "python manage.py harvest --settings=avoidallappssettings " "--verbosity=3 --no-color --apps=foobar,donothing") assert_equals(status, 0, out) assert "Test the django app FOO BAR" in out assert "Test the django app DO NOTHING" in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_no_server(): '"harvest" --no-server does not start the server' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --apps=foobar --no-server") assert_equals(status, 0, out) assert "Django's builtin server is running at" not in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_django_specifying_scenarios_to_run(): 'django harvest can run only specified scenarios with ' \ '--scenarios or -s options' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --scenarios=2,5 -a foobar") assert_equals(status, 0, out) assert "2nd scenario" in out assert "5th scenario" in out assert "1st scenario" not in out assert "3rd scenario" not in out assert "4th scenario" not in out assert "6th scenario" not in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_django_specifying_scenarios_to_run_by_tag(): 'django harvest can run only specified scenarios with ' \ '--tags or -t options' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color --tag=fast -a foobar") assert_equals(status, 0, out) assert "3rd scenario" in out assert "6th scenario" in out assert "1st scenario" not in out assert "2rd scenario" not in out assert "4th scenario" not in out assert "5th scenario" not in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_running_only_specified_features(): 'it can run only the specified features, passing the file path' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color " \ "foobar/features/foobar.feature") assert_equals(status, 0, out) assert "Test the django app FOO BAR" in out assert "Test the django app DO NOTHING" not in out @FileSystem.in_directory(current_directory, 'django', 'alfaces') def test_specifying_features_in_inner_directory(): 'it can run only the specified features from a subdirectory' status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=3 --no-color " \ "foobar/features/deeper/deeper/leaf.feature") assert_equals(status, 0, out) assert "Test the django app FOO BAR" not in out assert "Test a feature in an inner directory" in out assert "Test the django app DO NOTHING" not in out
9,792
Python
.py
204
42.313725
90
0.702691
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,716
test_brocolis.py
gabrielfalcao_lettuce/tests/integration/test_brocolis.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 commands from lettuce.fs import FileSystem from nose.tools import assert_equals from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'brocolis') def test_harvest_with_debug_mode_enabled(): 'python manage.py harvest -d turns settings.DEBUG=True' for option in ['-d', '--debug-mode']: status, out = run_scenario('leaves', 'enabled', **{option: None}) assert_equals(status, 0, out) @FileSystem.in_directory(current_directory, 'django', 'brocolis') def test_harvest_with_debug_mode_disabled(): 'python manage.py harvest without turns settings.DEBUG=False' status, out = run_scenario('leaves', 'disabled') assert_equals(status, 0, out) @FileSystem.in_directory(current_directory, 'django', 'brocolis') def test_harvest_sets_environment_variabled_for_gae(): 'harvest sets environment variables SERVER_NAME and SERVER_PORT in order to work with google app engine' status, out = run_scenario('leaves', 'appengine') assert_equals(status, 0, out) @FileSystem.in_directory(current_directory, 'django', 'brocolis') def test_harvest_uses_test_runner(): 'harvest uses TEST_RUNNER specified in settings' status, out = run_scenario('leaves', 'disabled') assert_equals(status, 0, out) assert "Custom test runner enabled." in out
2,167
Python
.py
43
47.581395
108
0.750711
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,717
test_bamboo.py
gabrielfalcao_lettuce/tests/integration/test_bamboo.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.fs import FileSystem from nose.tools import assert_equals, assert_not_equals from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'bamboo') def test_mail_count(): 'Mail count is checked through Lettuce steps' status, out = run_scenario('leaves', 'count', 1) assert_equals(status, 0, out) status, out = run_scenario('leaves', 'count', 2) assert_equals(status, 0, out) status, out = run_scenario('leaves', 'count', 3) assert_not_equals(status, 0) assert "Length of outbox is 1" in out @FileSystem.in_directory(current_directory, 'django', 'bamboo') def test_mail_content(): 'Mail content is checked through Lettuce steps' status, out = run_scenario('leaves', 'content', 1) assert_equals(status, 0, out) status, out = run_scenario('leaves', 'content', 2) assert_equals(status, 0, out) status, out = run_scenario('leaves', 'content', 3) assert_not_equals(status, 0) assert "An email contained expected text in the body" in out @FileSystem.in_directory(current_directory, 'django', 'bamboo') def test_mail_fail(): 'Mock mail failure dies with error' status, out = run_scenario('leaves', 'mock-failure', 1) assert_not_equals(status, 0) assert "SMTPException: Failure mocked by lettuce" in out
2,162
Python
.py
46
44
71
0.73289
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,718
test_couves.py
gabrielfalcao_lettuce/tests/integration/test_couves.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 commands from lettuce.fs import FileSystem from sure import expect from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'couves') def test_django_agains_couves(): 'it always call @after.all hooks, even after exceptions' status, out = run_scenario() expect("Couves before all").to.be.within(out) expect("Couves after all").to.be.within(out) @FileSystem.in_directory(current_directory, 'django', 'couves') def test_django_agains_couves_nohooks(): 'it only calls @before.all and @after.all hooks if there are features found' status, out = run_scenario(**{'--tags': 'nothingwillbefound'}) expect("Couves before all").to.not_be.within(out) expect("Couves after all").to.not_be.within(out)
1,602
Python
.py
33
46.30303
80
0.755128
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,719
test_dill.py
gabrielfalcao_lettuce/tests/integration/test_dill.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 commands from lettuce.fs import FileSystem from nose.tools import assert_equals, assert_not_equals from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'dill') def test_model_creation(): 'Models are created through Lettuce steps' status, out = run_scenario('leaves', 'create') assert_equals(status, 0, out) @FileSystem.in_directory(current_directory, 'django', 'dill') def test_model_update(): 'Models are updated through Lettuce steps' status, out = run_scenario('leaves', 'update', 1) assert_equals(status, 0, out) status, out = run_scenario('leaves', 'update', 2) assert_not_equals(status, 0, out) assert "IntegrityError: PRIMARY KEY must be unique" in out status, out = run_scenario('leaves', 'update', 3) assert_not_equals(status, 0, out) assert "The \"pk\" field is required for all update operations" in out status, out = run_scenario('leaves', 'update', 4) assert_not_equals(status, 0, out) assert "Must use the writes_models decorator to update models" in out @FileSystem.in_directory(current_directory, 'django', 'dill') def test_model_existence_check(): 'Model existence is checked through Lettuce steps' status, out = run_scenario('leaves', 'existence', 1) assert_equals(status, 0, out) status, out = run_scenario('leaves', 'existence', 2) assert_not_equals(status, 0) assert "Garden does not exist: {u'name': u'Botanic Gardens'}" in out gardens = "\n".join([ "Rows in DB are:", "id=1, name=Secret Garden, area=45, raining=False,", "id=2, name=Octopus's Garden, area=120, raining=True,", "id=3, name=Covent Garden, area=200, raining=True,", ]) assert gardens in out assert "AssertionError: 1 rows missing" in out status, out = run_scenario('leaves', 'existence', 3) assert_not_equals(status, 0) assert "Garden does not exist: {u'name': u'Secret Garden', " \ "u'@howbig': u'huge'}" in out gardens = "\n".join([ "Rows in DB are:", "id=1, name=Secret Garden, area=45, raining=False, howbig=small,", "id=2, name=Octopus's Garden, area=120, raining=True, howbig=medium,", "id=3, name=Covent Garden, area=200, raining=True, howbig=big,", ]) assert gardens in out assert "AssertionError: 1 rows missing" in out status, out = run_scenario('leaves', 'existence', 4) assert_not_equals(status, 0) assert "Expected 2 geese, found 1" in out @FileSystem.in_directory(current_directory, 'django', 'dill') def test_use_test_database_setting(): 'Test database is recreated each time if LETTUCE_USE_TEST_DATABASE is set' for i in range(1, 2): status, out = commands.getstatusoutput( "python manage.py harvest --settings=testdbsettings " + "leaves/features/testdb.feature") assert_equals(status, 0, out) assert "Harvester count: 1" in out, out
3,802
Python
.py
80
42.925
78
0.698811
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,720
test_cucumber.py
gabrielfalcao_lettuce/tests/integration/test_cucumber.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 commands from lettuce.fs import FileSystem from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'cucumber') def test_django_against_cucumber_django_project(): 'testing all django hooks' status, out = run_scenario() assert "before harvest" in out assert "after harvest" in out
1,175
Python
.py
26
43.346154
71
0.768154
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,721
__init__.py
gabrielfalcao_lettuce/tests/integration/__init__.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/>.
784
Python
.py
16
48
71
0.765625
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,722
test_grocery.py
gabrielfalcao_lettuce/tests/integration/test_grocery.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 sys import commands from lettuce.fs import FileSystem from tests.asserts import assert_equals current_directory = FileSystem.dirname(__file__) lib_directory = FileSystem.join(current_directory, 'lib') OLD_PYTHONPATH = os.getenv('PYTHONPATH', ':'.join(sys.path)) def teardown(): os.environ['PYTHONPATH'] = OLD_PYTHONPATH @FileSystem.in_directory(current_directory, 'django', 'grocery') def test_django_admin_media_serving_on_django_13(): 'lettuce should serve admin static files properly on Django 1.3' os.environ['PYTHONPATH'] = "%s:%s" % ( FileSystem.join(lib_directory, 'Django-1.3'), OLD_PYTHONPATH, ) status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=2 ./features/") assert_equals(status, 0, out) lines = out.splitlines() assert u"Preparing to serve django's admin site static files..." in lines assert u'Running on port 7000 ... OK' in lines assert u'Fetching admin media ... OK' in lines assert u'Fetching static files ... OK' in lines assert u'Fetching CSS files: ... OK' in lines assert u'Fetching javascript files: ... OK' in lines assert u"Django's builtin server is running at 0.0.0.0:7000" in lines @FileSystem.in_directory(current_directory, 'django', 'grocery') def test_django_admin_media_serving_on_django_125(): 'lettuce should serve admin static files properly on Django 1.2.5' os.environ['PYTHONPATH'] = "%s:%s" % ( FileSystem.join(lib_directory, 'Django-1.2.5'), OLD_PYTHONPATH, ) status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=2 ./features/") assert_equals(status, 0, out) lines = out.splitlines() f = '\n\n' f += '*' * 100 f += '\n' + '\n'.join(lines) assert u"Preparing to serve django's admin site static files..." in lines, f assert u"Django's builtin server is running at 0.0.0.0:7000" in lines, f assert u'Running on port 7000 ... OK' in lines, f assert u'Fetching admin media ... OK' in lines, f assert u'Fetching static files ... OK' in lines, f assert u'Fetching CSS files: ... OK' in lines, f assert u'Fetching javascript files: ... OK' in lines, f @FileSystem.in_directory(current_directory, 'django', 'grocery') def test_django_admin_media_serving_forced_by_setting(): 'settings.LETTUCE_SERVE_ADMIN_MEDIA forces lettuce to serve admin assets' os.environ['PYTHONPATH'] = "%s:%s" % ( FileSystem.join(lib_directory, 'Django-1.3'), OLD_PYTHONPATH, ) extra_args = " --scenarios=1,3,4,5 --settings=settings_without_admin" status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=2 ./features/ %s" % extra_args) assert_equals(status, 0, out) lines = out.splitlines() assert u"Preparing to serve django's admin site static files " \ "(as per settings.LETTUCE_SERVE_ADMIN_MEDIA=True)..." in lines assert u'Running on port 7000 ... OK' in lines assert u'Fetching static files ... OK' in lines assert u'Fetching CSS files: ... OK' in lines assert u'Fetching javascript files: ... OK' in lines assert u"Django's builtin server is running at 0.0.0.0:7000" in lines # the scenario 2 is not suppose to run assert u'Fetching admin media ... OK' not in lines
4,149
Python
.py
86
43.848837
80
0.702776
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,723
test_kale.py
gabrielfalcao_lettuce/tests/integration/test_kale.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 commands from lettuce.fs import FileSystem from nose.tools import assert_equals from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'kale') def test_harvest_uses_test_runner(): 'harvest uses LETTUCE_TEST_SERVER specified in settings' status, out = run_scenario('leaves', 'modification') assert_equals(status, 0, out)
1,212
Python
.py
26
44.961538
71
0.77138
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,724
test_chive.py
gabrielfalcao_lettuce/tests/integration/test_chive.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 sys import commands from lettuce.fs import FileSystem from tests.asserts import assert_not_equals current_directory = FileSystem.dirname(__file__) lib_directory = FileSystem.join(current_directory, 'lib') OLD_PYTHONPATH = os.getenv('PYTHONPATH', ':'.join(sys.path)) def teardown(): os.environ['PYTHONPATH'] = OLD_PYTHONPATH @FileSystem.in_directory(current_directory, 'django', 'chive') def test_django_admin_media_serving_on_django_13(): 'lettuce should serve admin static files properly on Django 1.3' os.environ['PYTHONPATH'] = "%s:%s" % ( FileSystem.join(lib_directory, 'Django-1.3'), OLD_PYTHONPATH, ) status, out = commands.getstatusoutput( "python manage.py harvest --verbosity=2 ./features/") assert_not_equals(status, 0) lines = out.splitlines() assert u"Preparing to serve django's admin site static files..." in lines assert u"Django's builtin server is running at 0.0.0.0:7000" in lines
1,774
Python
.py
39
42.615385
77
0.743902
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,725
test_celeries.py
gabrielfalcao_lettuce/tests/integration/test_celeries.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 commands from lettuce.fs import FileSystem from sure import this as the from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'celeries') def test_failfast(): 'passing --failfast to the harvest command will cause lettuce to stop in the first failure' status, output = run_scenario(**{'--failfast': None}) the(output).should.contain("This one is present") the(output).should.contain("Celeries before all") the(output).should.contain("Celeries before harvest") the(output).should.contain("Celeries before feature 'Test the django app leaves'") the(output).should.contain("Celeries before scenario 'This one is present'") the(output).should.contain("Celeries before step 'Given I say foo bar'") the(output).should.contain("Celeries after step 'Given I say foo bar'") the(output).should.contain("Celeries before step 'Then it fails'") the(output).should.contain("Celeries after step 'Then it fails'") the(output).should.contain("Celeries after scenario 'This one is present'") the(output).should.contain("Celeries after feature 'Test the django app leaves'") the(output).should.contain("Celeries after harvest") the(output).should.contain("Celeries after all") the(output).should_not.contain("This one is never called")
2,164
Python
.py
39
52.641026
95
0.754842
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,726
test_rucola.py
gabrielfalcao_lettuce/tests/integration/test_rucola.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 commands from lettuce.fs import FileSystem from nose.tools import assert_equals from tests.util import run_scenario current_directory = FileSystem.dirname(__file__) @FileSystem.in_directory(current_directory, 'django', 'rucola') def test_harvest_uses_test_runner(): 'harvest uses LETTUCE_TEST_SERVER specified in settings' status, out = run_scenario() assert "Test Suite Summary:" in out
1,194
Python
.py
26
44.346154
71
0.772532
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,727
setup.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/setup.py
from distutils.core import setup from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES import os import sys class osx_install_data(install_data): # On MacOS, the platform-specific lib dir is /System/Library/Framework/Python/.../ # which is wrong. Python 2.5 supplied with MacOS 10.5 has an Apple-specific fix # for this in distutils.command.install_data#306. It fixes install_lib but not # install_data, which is why we roll our own install_data class. def finalize_options(self): # By the time finalize_options is called, install.install_lib is set to the # fixed directory, so we set the installdir to install_lib. The # install_data class uses ('install_data', 'install_dir') instead. self.set_undefined_options('install', ('install_lib', 'install_dir')) install_data.finalize_options(self) if sys.platform == "darwin": cmdclasses = {'install_data': osx_install_data} else: cmdclasses = {'install_data': install_data} def fullsplit(path, result=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) # Tell distutils to put the data_files in platform-specific installation # locations. See here for an explanation: # http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] # Compile the list of packages available, because distutils doesn't have # an easy way to do this. packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir != '': os.chdir(root_dir) django_dir = 'django' for dirpath, dirnames, filenames in os.walk(django_dir): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith('.'): del dirnames[i] if '__init__.py' in filenames: packages.append('.'.join(fullsplit(dirpath))) elif filenames: data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]]) # Small hack for working with bdist_wininst. # See http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html if len(sys.argv) > 1 and sys.argv[1] == 'bdist_wininst': for file_info in data_files: file_info[0] = '\\PURELIB\\%s' % file_info[0] # Dynamically calculate the version based on django.VERSION. version = __import__('django').get_version() if u'SVN' in version: version = ' '.join(version.split(' ')[:-1]) setup( name = "Django", version = version.replace(' ', '-'), url = 'http://www.djangoproject.com/', author = 'Django Software Foundation', author_email = '[email protected]', description = 'A high-level Python Web framework that encourages rapid development and clean, pragmatic design.', download_url = 'http://media.djangoproject.com/releases/1.3/Django-1.3.tar.gz', packages = packages, cmdclass = cmdclasses, data_files = data_files, scripts = ['django/bin/django-admin.py'], classifiers = ['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: WSGI', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
4,325
Python
.py
92
39.945652
117
0.650012
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,728
csrf_migration_helper.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/extras/csrf_migration_helper.py
#!/usr/bin/env python # This script aims to help developers locate forms and view code that needs to # use the new CSRF protection in Django 1.2. It tries to find all the code that # may need the steps described in the CSRF documentation. It does not modify # any code directly, it merely attempts to locate it. Developers should be # aware of its limitations, described below. # # For each template that contains at least one POST form, the following info is printed: # # <Absolute path to template> # AKA: <Aliases (relative to template directory/directories that contain it)> # POST forms: <Number of POST forms> # With token: <Number of POST forms with the CSRF token already added> # Without token: # <File name and line number of form without token> # # Searching for: # <Template names that need to be searched for in view code # (includes templates that 'include' current template)> # # Found: # <File name and line number of any view code found> # # The format used allows this script to be used in Emacs grep mode: # M-x grep # Run grep (like this): /path/to/my/virtualenv/python /path/to/django/src/extras/csrf_migration_helper.py --settings=mysettings /path/to/my/srcs # Limitations # =========== # # - All templates must be stored on disk in '.html' or '.htm' files. # (extensions configurable below) # # - All Python code must be stored on disk in '.py' files. (extensions # configurable below) # # - All templates must be accessible from TEMPLATE_DIRS or from the 'templates/' # directory in apps specified in INSTALLED_APPS. Non-file based template # loaders are out of the picture, because there is no way to ask them to # return all templates. # # - It's impossible to programmatically determine which forms should and should # not have the token added. The developer must decide when to do this, # ensuring that the token is only added to internally targetted forms. # # - It's impossible to programmatically work out when a template is used. The # attempts to trace back to view functions are guesses, and could easily fail # in the following ways: # # * If the 'include' template tag is used with a variable # i.e. {% include tname %} where tname is a variable containing the actual # template name, rather than {% include "my_template.html" %}. # # * If the template name has been built up by view code instead of as a simple # string. For example, generic views and the admin both do this. (These # apps are both contrib and both use RequestContext already, as it happens). # # * If the 'ssl' tag (or any template tag other than 'include') is used to # include the template in another template. # # - All templates belonging to apps referenced in INSTALLED_APPS will be # searched, which may include third party apps or Django contrib. In some # cases, this will be a good thing, because even if the templates of these # apps have been fixed by someone else, your own view code may reference the # same template and may need to be updated. # # You may, however, wish to comment out some entries in INSTALLED_APPS or # TEMPLATE_DIRS before running this script. # Improvements to this script are welcome! # Configuration # ============= TEMPLATE_EXTENSIONS = [ ".html", ".htm", ] PYTHON_SOURCE_EXTENSIONS = [ ".py", ] TEMPLATE_ENCODING = "UTF-8" PYTHON_ENCODING = "UTF-8" # Method # ====== # Find templates: # - template dirs # - installed apps # # Search for POST forms # - Work out what the name of the template is, as it would appear in an # 'include' or get_template() call. This can be done by comparing template # filename to all template dirs. Some templates can have more than one # 'name' e.g. if a directory and one of its child directories are both in # TEMPLATE_DIRS. This is actually a common hack used for # overriding-and-extending admin templates. # # For each POST form, # - see if it already contains '{% csrf_token %}' immediately after <form> # - work back to the view function(s): # - First, see if the form is included in any other templates, then # recursively compile a list of affected templates. # - Find any code function that references that template. This is just a # brute force text search that can easily return false positives # and fail to find real instances. import os import sys import re from optparse import OptionParser USAGE = """ This tool helps to locate forms that need CSRF tokens added and the corresponding view code. This processing is NOT fool proof, and you should read the help contained in the script itself. Also, this script may need configuring (by editing the script) before use. Usage: python csrf_migration_helper.py [--settings=path.to.your.settings] /path/to/python/code [more paths...] Paths can be specified as relative paths. With no arguments, this help is printed. """ _POST_FORM_RE = \ re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE) _FORM_CLOSE_RE = re.compile(r'</form\s*>') _TOKEN_RE = re.compile('\{% csrf_token') def get_template_dirs(): """ Returns a set of all directories that contain project templates. """ from django.conf import settings dirs = set() if ('django.template.loaders.filesystem.load_template_source' in settings.TEMPLATE_LOADERS or 'django.template.loaders.filesystem.Loader' in settings.TEMPLATE_LOADERS): dirs.update(map(unicode, settings.TEMPLATE_DIRS)) if ('django.template.loaders.app_directories.load_template_source' in settings.TEMPLATE_LOADERS or 'django.template.loaders.app_directories.Loader' in settings.TEMPLATE_LOADERS): from django.template.loaders.app_directories import app_template_dirs dirs.update(app_template_dirs) return dirs def make_template_info(filename, root_dirs): """ Creates a Template object for a filename, calculating the possible relative_filenames from the supplied filename and root template directories """ return Template(filename, [filename[len(d)+1:] for d in root_dirs if filename.startswith(d)]) class Template(object): def __init__(self, absolute_filename, relative_filenames): self.absolute_filename, self.relative_filenames = absolute_filename, relative_filenames def content(self): try: return self._content except AttributeError: fd = open(self.absolute_filename) try: content = fd.read().decode(TEMPLATE_ENCODING) except UnicodeDecodeError, e: message = '%s in %s' % ( e[4], self.absolute_filename.encode('UTF-8', 'ignore')) raise UnicodeDecodeError(*(e.args[:4] + (message,))) fd.close() self._content = content return content content = property(content) def post_form_info(self): """ Get information about any POST forms in the template. Returns [(linenumber, csrf_token added)] """ forms = {} form_line = 0 for ln, line in enumerate(self.content.split("\n")): if not form_line and _POST_FORM_RE.search(line): # record the form with no CSRF token yet form_line = ln + 1 forms[form_line] = False if form_line and _TOKEN_RE.search(line): # found the CSRF token forms[form_line] = True form_line = 0 if form_line and _FORM_CLOSE_RE.search(line): # no token found by form closing tag form_line = 0 return forms.items() def includes_template(self, t): """ Returns true if this template includes template 't' (via {% include %}) """ for r in t.relative_filenames: if re.search(r'\{%\s*include\s+(\'|")' + re.escape(r) + r'(\1)\s*%\}', self.content): return True return False def related_templates(self): """ Returns all templates that include this one, recursively. (starting with this one) """ try: return self._related_templates except AttributeError: pass retval = set([self]) for t in self.all_templates: if t.includes_template(self): # If two templates mutually include each other, directly or # indirectly, we have a problem here... retval = retval.union(t.related_templates()) self._related_templates = retval return retval def __repr__(self): return repr(self.absolute_filename) def __eq__(self, other): return self.absolute_filename == other.absolute_filename def __hash__(self): return hash(self.absolute_filename) def get_templates(dirs): """ Returns all files in dirs that have template extensions, as Template objects. """ templates = set() for root in dirs: for (dirpath, dirnames, filenames) in os.walk(root): for f in filenames: if len([True for e in TEMPLATE_EXTENSIONS if f.endswith(e)]) > 0: t = make_template_info(os.path.join(dirpath, f), dirs) # templates need to be able to search others: t.all_templates = templates templates.add(t) return templates def get_python_code(paths): """ Returns all Python code, as a list of tuples, each one being: (filename, list of lines) """ retval = [] for p in paths: if not os.path.isdir(p): raise Exception("'%s' is not a directory." % p) for (dirpath, dirnames, filenames) in os.walk(p): for f in filenames: if len([True for e in PYTHON_SOURCE_EXTENSIONS if f.endswith(e)]) > 0: fn = os.path.join(dirpath, f) fd = open(fn) content = [l.decode(PYTHON_ENCODING) for l in fd.readlines()] fd.close() retval.append((fn, content)) return retval def search_python_list(python_code, template_names): """ Searches python code for a list of template names. Returns a list of tuples, each one being: (filename, line number) """ retval = [] for tn in template_names: retval.extend(search_python(python_code, tn)) retval = list(set(retval)) retval.sort() return retval def search_python(python_code, template_name): """ Searches Python code for a template name. Returns a list of tuples, each one being: (filename, line number) """ retval = [] for fn, content in python_code: for ln, line in enumerate(content): if ((u'"%s"' % template_name) in line) or \ ((u"'%s'" % template_name) in line): retval.append((fn, ln + 1)) return retval def main(pythonpaths): template_dirs = get_template_dirs() templates = get_templates(template_dirs) python_code = get_python_code(pythonpaths) for t in templates: # Logic form_matches = t.post_form_info() num_post_forms = len(form_matches) form_lines_without_token = [ln for (ln, has_token) in form_matches if not has_token] if num_post_forms == 0: continue to_search = [rf for rt in t.related_templates() for rf in rt.relative_filenames] found = search_python_list(python_code, to_search) # Display: print t.absolute_filename for r in t.relative_filenames: print u" AKA %s" % r print u" POST forms: %s" % num_post_forms print u" With token: %s" % (num_post_forms - len(form_lines_without_token)) if form_lines_without_token: print u" Without token:" for ln in form_lines_without_token: print "%s:%d:" % (t.absolute_filename, ln) print print u" Searching for:" for r in to_search: print u" " + r print print u" Found:" if len(found) == 0: print " Nothing" else: for fn, ln in found: print "%s:%d:" % (fn, ln) print print "----" parser = OptionParser(usage=USAGE) parser.add_option("", "--settings", action="store", dest="settings", help="Dotted path to settings file") if __name__ == '__main__': options, args = parser.parse_args() if len(args) == 0: parser.print_help() sys.exit(1) settings = getattr(options, 'settings', None) if settings is None: if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None: print "You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter" sys.exit(1) else: os.environ["DJANGO_SETTINGS_MODULE"] = settings main(args)
13,030
Python
.py
318
34.525157
146
0.645745
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,729
conf.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/conf.py
# -*- coding: utf-8 -*- # # Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ["djangodocs"] # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = '.txt' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'contents' # General substitutions. project = 'Django' copyright = 'Django Software Foundation and contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.3' # The full version, including alpha/beta/rc tags. release = '1.3' # The next version to be released django_next_version = '1.3' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'trac' # Sphinx will recurse into subversion configuration folders and try to read # any document file within. These should be ignored. # Note: exclude_dirnames is new in Sphinx 0.5 exclude_dirnames = ['.svn'] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # HTML translator class for the builder html_translator_class = "djangodocs.DjangoHTMLTranslator" # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Djangodoc' modindex_common_prefix = ["django."] # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). #latex_documents = [] latex_documents = [ ('contents', 'django.tex', u'Django Documentation', u'Django Software Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('contents', 'django', 'Django Documentation', ['Django Software Foundation'], 1) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'Django' epub_author = u'Django Software Foundation' epub_publisher = u'Django Software Foundation' epub_copyright = u'2010, Django Software Foundation' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True
8,707
Python
.py
196
43.005102
85
0.734297
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,730
djangodocs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/_ext/djangodocs.py
""" Sphinx plugins for Django documentation. """ import os import re from docutils import nodes, transforms try: import json except ImportError: try: import simplejson as json except ImportError: try: from django.utils import simplejson as json except ImportError: json = None from sphinx import addnodes, roles from sphinx.builders.html import StandaloneHTMLBuilder from sphinx.writers.html import SmartyPantsHTMLTranslator from sphinx.util.console import bold from sphinx.util.compat import Directive # RE for option descriptions without a '--' prefix simple_option_desc_re = re.compile( r'([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)') def setup(app): app.add_crossref_type( directivename = "setting", rolename = "setting", indextemplate = "pair: %s; setting", ) app.add_crossref_type( directivename = "templatetag", rolename = "ttag", indextemplate = "pair: %s; template tag" ) app.add_crossref_type( directivename = "templatefilter", rolename = "tfilter", indextemplate = "pair: %s; template filter" ) app.add_crossref_type( directivename = "fieldlookup", rolename = "lookup", indextemplate = "pair: %s; field lookup type", ) app.add_description_unit( directivename = "django-admin", rolename = "djadmin", indextemplate = "pair: %s; django-admin command", parse_node = parse_django_admin_node, ) app.add_description_unit( directivename = "django-admin-option", rolename = "djadminopt", indextemplate = "pair: %s; django-admin command-line option", parse_node = parse_django_adminopt_node, ) app.add_config_value('django_next_version', '0.0', True) app.add_directive('versionadded', VersionDirective) app.add_directive('versionchanged', VersionDirective) app.add_transform(SuppressBlockquotes) app.add_builder(DjangoStandaloneHTMLBuilder) class VersionDirective(Directive): has_content = True required_arguments = 1 optional_arguments = 1 final_argument_whitespace = True option_spec = {} def run(self): env = self.state.document.settings.env arg0 = self.arguments[0] is_nextversion = env.config.django_next_version == arg0 ret = [] node = addnodes.versionmodified() ret.append(node) if not is_nextversion: if len(self.arguments) == 1: linktext = 'Please, see the release notes </releases/%s>' % (arg0) xrefs = roles.XRefRole()('doc', linktext, linktext, self.lineno, self.state) node.extend(xrefs[0]) node['version'] = arg0 else: node['version'] = "Development version" node['type'] = self.name if len(self.arguments) == 2: inodes, messages = self.state.inline_text(self.arguments[1], self.lineno+1) node.extend(inodes) if self.content: self.state.nested_parse(self.content, self.content_offset, node) ret = ret + messages env.note_versionchange(node['type'], node['version'], node, self.lineno) return ret class SuppressBlockquotes(transforms.Transform): """ Remove the default blockquotes that encase indented list, tables, etc. """ default_priority = 300 suppress_blockquote_child_nodes = ( nodes.bullet_list, nodes.enumerated_list, nodes.definition_list, nodes.literal_block, nodes.doctest_block, nodes.line_block, nodes.table ) def apply(self): for node in self.document.traverse(nodes.block_quote): if len(node.children) == 1 and isinstance(node.children[0], self.suppress_blockquote_child_nodes): node.replace_self(node.children[0]) class DjangoHTMLTranslator(SmartyPantsHTMLTranslator): """ Django-specific reST to HTML tweaks. """ # Don't use border=1, which docutils does by default. def visit_table(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils')) # <big>? Really? def visit_desc_parameterlist(self, node): self.body.append('(') self.first_param = 1 def depart_desc_parameterlist(self, node): self.body.append(')') # # Don't apply smartypants to literal blocks # def visit_literal_block(self, node): self.no_smarty += 1 SmartyPantsHTMLTranslator.visit_literal_block(self, node) def depart_literal_block(self, node): SmartyPantsHTMLTranslator.depart_literal_block(self, node) self.no_smarty -= 1 # # Turn the "new in version" stuff (versionadded/versionchanged) into a # better callout -- the Sphinx default is just a little span, # which is a bit less obvious that I'd like. # # FIXME: these messages are all hardcoded in English. We need to change # that to accomodate other language docs, but I can't work out how to make # that work. # version_text = { 'deprecated': 'Deprecated in Django %s', 'versionchanged': 'Changed in Django %s', 'versionadded': 'New in Django %s', } def visit_versionmodified(self, node): self.body.append( self.starttag(node, 'div', CLASS=node['type']) ) title = "%s%s" % ( self.version_text[node['type']] % node['version'], len(node) and ":" or "." ) self.body.append('<span class="title">%s</span> ' % title) def depart_versionmodified(self, node): self.body.append("</div>\n") # Give each section a unique ID -- nice for custom CSS hooks def visit_section(self, node): old_ids = node.get('ids', []) node['ids'] = ['s-' + i for i in old_ids] node['ids'].extend(old_ids) SmartyPantsHTMLTranslator.visit_section(self, node) node['ids'] = old_ids def parse_django_admin_node(env, sig, signode): command = sig.split(' ')[0] env._django_curr_admin_command = command title = "django-admin.py %s" % sig signode += addnodes.desc_name(title, title) return sig def parse_django_adminopt_node(env, sig, signode): """A copy of sphinx.directives.CmdoptionDesc.parse_signature()""" from sphinx.domains.std import option_desc_re count = 0 firstname = '' for m in option_desc_re.finditer(sig): optname, args = m.groups() if count: signode += addnodes.desc_addname(', ', ', ') signode += addnodes.desc_name(optname, optname) signode += addnodes.desc_addname(args, args) if not count: firstname = optname count += 1 if not count: for m in simple_option_desc_re.finditer(sig): optname, args = m.groups() if count: signode += addnodes.desc_addname(', ', ', ') signode += addnodes.desc_name(optname, optname) signode += addnodes.desc_addname(args, args) if not count: firstname = optname count += 1 if not firstname: raise ValueError return firstname class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder): """ Subclass to add some extra things we need. """ name = 'djangohtml' def finish(self): super(DjangoStandaloneHTMLBuilder, self).finish() if json is None: self.warn("cannot create templatebuiltins.js due to missing simplejson dependency") return self.info(bold("writing templatebuiltins.js...")) xrefs = self.env.domaindata["std"]["objects"] templatebuiltins = { "ttags": [n for ((t, n), (l, a)) in xrefs.items() if t == "templatetag" and l == "ref/templates/builtins"], "tfilters": [n for ((t, n), (l, a)) in xrefs.items() if t == "templatefilter" and l == "ref/templates/builtins"], } outfilename = os.path.join(self.outdir, "templatebuiltins.js") f = open(outfilename, 'wb') f.write('var django_template_builtins = ') json.dump(templatebuiltins, f) f.write(';\n') f.close();
8,377
Python
.py
221
30.176471
110
0.619633
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,731
literals_to_xrefs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/_ext/literals_to_xrefs.py
""" Runs through a reST file looking for old-style literals, and helps replace them with new-style references. """ import re import sys import shelve refre = re.compile(r'``([^`\s]+?)``') ROLES = ( 'attr', 'class', "djadmin", 'data', 'exc', 'file', 'func', 'lookup', 'meth', 'mod' , "djadminopt", "ref", "setting", "term", "tfilter", "ttag", # special "skip" ) ALWAYS_SKIP = [ "NULL", "True", "False", ] def fixliterals(fname): data = open(fname).read() last = 0 new = [] storage = shelve.open("/tmp/literals_to_xref.shelve") lastvalues = storage.get("lastvalues", {}) for m in refre.finditer(data): new.append(data[last:m.start()]) last = m.end() line_start = data.rfind("\n", 0, m.start()) line_end = data.find("\n", m.end()) prev_start = data.rfind("\n", 0, line_start) next_end = data.find("\n", line_end + 1) # Skip always-skip stuff if m.group(1) in ALWAYS_SKIP: new.append(m.group(0)) continue # skip when the next line is a title next_line = data[m.end():next_end].strip() if next_line[0] in "!-/:-@[-`{-~" and all(c == next_line[0] for c in next_line): new.append(m.group(0)) continue sys.stdout.write("\n"+"-"*80+"\n") sys.stdout.write(data[prev_start+1:m.start()]) sys.stdout.write(colorize(m.group(0), fg="red")) sys.stdout.write(data[m.end():next_end]) sys.stdout.write("\n\n") replace_type = None while replace_type is None: replace_type = raw_input( colorize("Replace role: ", fg="yellow") ).strip().lower() if replace_type and replace_type not in ROLES: replace_type = None if replace_type == "": new.append(m.group(0)) continue if replace_type == "skip": new.append(m.group(0)) ALWAYS_SKIP.append(m.group(1)) continue default = lastvalues.get(m.group(1), m.group(1)) if default.endswith("()") and replace_type in ("class", "func", "meth"): default = default[:-2] replace_value = raw_input( colorize("Text <target> [", fg="yellow") + default + colorize("]: ", fg="yellow") ).strip() if not replace_value: replace_value = default new.append(":%s:`%s`" % (replace_type, replace_value)) lastvalues[m.group(1)] = replace_value new.append(data[last:]) open(fname, "w").write("".join(new)) storage["lastvalues"] = lastvalues storage.close() # # The following is taken from django.utils.termcolors and is copied here to # avoid the dependancy. # def colorize(text='', opts=(), **kwargs): """ Returns your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Returns the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold' 'underscore' 'blink' 'reverse' 'conceal' 'noreset' - string will not be auto-terminated with the RESET code Examples: colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize() colorize('goodbye', opts=('underscore',)) print colorize('first line', fg='red', opts=('noreset',)) print 'this should be red too' print colorize('and so should this') print 'this should not be red' """ color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) background = dict([(color_names[x], '4%s' % x) for x in range(8)]) RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} text = str(text) code_list = [] if text == '' and len(opts) == 1 and opts[0] == 'reset': return '\x1b[%sm' % RESET for k, v in kwargs.iteritems(): if k == 'fg': code_list.append(foreground[v]) elif k == 'bg': code_list.append(background[v]) for o in opts: if o in opt_dict: code_list.append(opt_dict[o]) if 'noreset' not in opts: text = text + '\x1b[%sm' % RESET return ('\x1b[%sm' % ';'.join(code_list)) + text if __name__ == '__main__': try: fixliterals(sys.argv[1]) except (KeyboardInterrupt, SystemExit): print
4,814
Python
.py
141
26.120567
93
0.555727
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,732
applyxrefs.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/docs/_ext/applyxrefs.py
"""Adds xref targets to the top of files.""" import sys import os testing = False DONT_TOUCH = ( './index.txt', ) def target_name(fn): if fn.endswith('.txt'): fn = fn[:-4] return '_' + fn.lstrip('./').replace('/', '-') def process_file(fn, lines): lines.insert(0, '\n') lines.insert(0, '.. %s:\n' % target_name(fn)) try: f = open(fn, 'w') except IOError: print("Can't open %s for writing. Not touching it." % fn) return try: f.writelines(lines) except IOError: print("Can't write to %s. Not touching it." % fn) finally: f.close() def has_target(fn): try: f = open(fn, 'r') except IOError: print("Can't open %s. Not touching it." % fn) return (True, None) readok = True try: lines = f.readlines() except IOError: print("Can't read %s. Not touching it." % fn) readok = False finally: f.close() if not readok: return (True, None) #print fn, len(lines) if len(lines) < 1: print("Not touching empty file %s." % fn) return (True, None) if lines[0].startswith('.. _'): return (True, None) return (False, lines) def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 1: argv.extend('.') files = [] for root in argv[1:]: for (dirpath, dirnames, filenames) in os.walk(root): files.extend([(dirpath, f) for f in filenames]) files.sort() files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')] #print files for fn in files: if fn in DONT_TOUCH: print("Skipping blacklisted file %s." % fn) continue target_found, lines = has_target(fn) if not target_found: if testing: print '%s: %s' % (fn, lines[0]), else: print "Adding xref to %s" % fn process_file(fn, lines) else: print "Skipping %s: already has a xref" % fn if __name__ == '__main__': sys.exit(main())
2,148
Python
.py
75
21.346667
75
0.533721
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,733
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
.py
312
52.092949
103
0.743454
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,734
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns('', # test_client modeltest urls (r'^test_client/', include('modeltests.test_client.urls')), (r'^test_client_regress/', include('regressiontests.test_client_regress.urls')), # File upload test views (r'^file_uploads/', include('regressiontests.file_uploads.urls')), # Always provide the auth system login and logout views (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}), (r'^accounts/logout/$', 'django.contrib.auth.views.logout'), # test urlconf for {% url %} template tag (r'^url_tag/', include('regressiontests.templates.urls')), # django built-in views (r'^views/', include('regressiontests.views.urls')), # test urlconf for middleware tests (r'^middleware/', include('regressiontests.middleware.urls')), # admin view tests (r'^test_admin/', include('regressiontests.admin_views.urls')), (r'^generic_inline_admin/', include('regressiontests.generic_inline_admin.urls')), # admin widget tests (r'widget_admin/', include('regressiontests.admin_widgets.urls')), (r'^utils/', include('regressiontests.utils.urls')), # test urlconf for syndication tests (r'^syndication/', include('regressiontests.syndication.urls')), # conditional get views (r'condition/', include('regressiontests.conditional_processing.urls')), # middleware exceptions tests (r'middleware_exceptions/', include('regressiontests.middleware_exceptions.urls')), # special headers views (r'special_headers/', include('regressiontests.special_headers.urls')), # test util views (r'test_utils/', include('regressiontests.test_utils.urls')), )
1,748
Python
.py
33
47.878788
95
0.706471
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,735
test_sqlite.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/test_sqlite.py
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # http://docs.djangoproject.com/en/dev/internals/contributing/#unit-tests # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', } }
835
Python
.py
21
37.190476
76
0.751538
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,736
runtests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/runtests.py
#!/usr/bin/env python import os, subprocess, sys import django.contrib as contrib from django.utils import unittest CONTRIB_DIR_NAME = 'django.contrib' MODEL_TESTS_DIR_NAME = 'modeltests' REGRESSION_TESTS_DIR_NAME = 'regressiontests' TEST_TEMPLATE_DIR = 'templates' CONTRIB_DIR = os.path.dirname(contrib.__file__) MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME) REGRESSION_TEST_DIR = os.path.join(os.path.dirname(__file__), REGRESSION_TESTS_DIR_NAME) REGRESSION_SUBDIRS_TO_SKIP = ['locale'] ALWAYS_INSTALLED_APPS = [ 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.flatpages', 'django.contrib.redirects', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.comments', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.staticfiles', ] def geodjango(settings): # All databases must have spatial backends to run GeoDjango tests. spatial_dbs = [name for name, db_dict in settings.DATABASES.items() if db_dict['ENGINE'].startswith('django.contrib.gis')] return len(spatial_dbs) == len(settings.DATABASES) def get_test_modules(): modules = [] for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR): for f in os.listdir(dirpath): if f.startswith('__init__') or f.startswith('.') or \ f.startswith('sql') or f.startswith('invalid') or \ os.path.basename(f) in REGRESSION_SUBDIRS_TO_SKIP: continue modules.append((loc, f)) return modules def get_invalid_modules(): modules = [] for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR), (CONTRIB_DIR_NAME, CONTRIB_DIR): for f in os.listdir(dirpath): if f.startswith('__init__') or f.startswith('.') or f.startswith('sql'): continue if f.startswith('invalid'): modules.append((loc, f)) return modules class InvalidModelTestCase(unittest.TestCase): def __init__(self, module_label): unittest.TestCase.__init__(self) self.module_label = module_label def runTest(self): from django.core.management.validation import get_validation_errors from django.db.models.loading import load_app from cStringIO import StringIO try: module = load_app(self.module_label) except Exception, e: self.fail('Unable to load invalid model module') # Make sure sys.stdout is not a tty so that we get errors without # coloring attached (makes matching the results easier). We restore # sys.stderr afterwards. orig_stdout = sys.stdout s = StringIO() sys.stdout = s count = get_validation_errors(s, module) sys.stdout = orig_stdout s.seek(0) error_log = s.read() actual = error_log.split('\n') expected = module.model_errors.split('\n') unexpected = [err for err in actual if err not in expected] missing = [err for err in expected if err not in actual] self.assertTrue(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected)) self.assertTrue(not missing, "Missing Errors: " + '\n'.join(missing)) def setup(verbosity, test_labels): from django.conf import settings state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'USE_I18N': settings.USE_I18N, 'LOGIN_URL': settings.LOGIN_URL, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),) settings.USE_I18N = True settings.LANGUAGE_CODE = 'en' settings.LOGIN_URL = '/accounts/login/' settings.MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.common.CommonMiddleware', ) settings.SITE_ID = 1 # For testing comment-utils, we require the MANAGERS attribute # to be set, so that a test email is sent out which we catch # in our tests. settings.MANAGERS = ("[email protected]",) # Load all the ALWAYS_INSTALLED_APPS. # (This import statement is intentionally delayed until after we # access settings because of the USE_I18N dependency.) from django.db.models.loading import get_apps, load_app get_apps() # Load all the test model apps. test_labels_set = set([label.split('.')[0] for label in test_labels]) test_modules = get_test_modules() # If GeoDjango, then we'll want to add in the test applications # that are a part of its test suite. if geodjango(settings): from django.contrib.gis.tests import geo_apps test_modules.extend(geo_apps(runtests=True)) for module_dir, module_name in test_modules: module_label = '.'.join([module_dir, module_name]) # if the module was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to the list to test. if not test_labels or module_name in test_labels_set: if verbosity >= 2: print "Importing application %s" % module_name mod = load_app(module_label) if mod: if module_label not in settings.INSTALLED_APPS: settings.INSTALLED_APPS.append(module_label) return state def teardown(state): from django.conf import settings # Restore the old settings. for key, value in state.items(): setattr(settings, key, value) def django_tests(verbosity, interactive, failfast, test_labels): from django.conf import settings state = setup(verbosity, test_labels) # Add tests for invalid models apps. extra_tests = [] for module_dir, module_name in get_invalid_modules(): module_label = '.'.join([module_dir, module_name]) if not test_labels or module_name in test_labels: extra_tests.append(InvalidModelTestCase(module_label)) try: # Invalid models are not working apps, so we cannot pass them into # the test runner with the other test_labels test_labels.remove(module_name) except ValueError: pass # If GeoDjango is used, add it's tests that aren't a part of # an application (e.g., GEOS, GDAL, Distance objects). if geodjango(settings): from django.contrib.gis.tests import geodjango_suite extra_tests.append(geodjango_suite(apps=False)) # Run the test suite, including the extra validation tests. from django.test.utils import get_runner if not hasattr(settings, 'TEST_RUNNER'): settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' TestRunner = get_runner(settings) if hasattr(TestRunner, 'func_name'): # Pre 1.2 test runners were just functions, # and did not support the 'failfast' option. import warnings warnings.warn( 'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.', DeprecationWarning ) failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive, extra_tests=extra_tests) else: test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast) failures = test_runner.run_tests(test_labels, extra_tests=extra_tests) teardown(state) return failures def bisect_tests(bisection_label, options, test_labels): state = setup(int(options.verbosity), test_labels) if not test_labels: # Get the full list of test labels to use for bisection from django.db.models.loading import get_apps test_labels = [app.__name__.split('.')[-2] for app in get_apps()] print '***** Bisecting test suite:',' '.join(test_labels) # Make sure the bisection point isn't in the test list # Also remove tests that need to be run in specific combinations for label in [bisection_label, 'model_inheritance_same_model_name']: try: test_labels.remove(label) except ValueError: pass subprocess_args = [sys.executable, __file__, '--settings=%s' % options.settings] if options.failfast: subprocess_args.append('--failfast') if options.verbosity: subprocess_args.append('--verbosity=%s' % options.verbosity) if not options.interactive: subprocess_args.append('--noinput') iteration = 1 while len(test_labels) > 1: midpoint = len(test_labels)/2 test_labels_a = test_labels[:midpoint] + [bisection_label] test_labels_b = test_labels[midpoint:] + [bisection_label] print '***** Pass %da: Running the first half of the test suite' % iteration print '***** Test labels:',' '.join(test_labels_a) failures_a = subprocess.call(subprocess_args + test_labels_a) print '***** Pass %db: Running the second half of the test suite' % iteration print '***** Test labels:',' '.join(test_labels_b) print failures_b = subprocess.call(subprocess_args + test_labels_b) if failures_a and not failures_b: print "***** Problem found in first half. Bisecting again..." iteration = iteration + 1 test_labels = test_labels_a[:-1] elif failures_b and not failures_a: print "***** Problem found in second half. Bisecting again..." iteration = iteration + 1 test_labels = test_labels_b[:-1] elif failures_a and failures_b: print "***** Multiple sources of failure found" break else: print "***** No source of failure found... try pair execution (--pair)" break if len(test_labels) == 1: print "***** Source of error:",test_labels[0] teardown(state) def paired_tests(paired_test, options, test_labels): state = setup(int(options.verbosity), test_labels) if not test_labels: print "" # Get the full list of test labels to use for bisection from django.db.models.loading import get_apps test_labels = [app.__name__.split('.')[-2] for app in get_apps()] print '***** Trying paired execution' # Make sure the constant member of the pair isn't in the test list # Also remove tests that need to be run in specific combinations for label in [paired_test, 'model_inheritance_same_model_name']: try: test_labels.remove(label) except ValueError: pass subprocess_args = [sys.executable, __file__, '--settings=%s' % options.settings] if options.failfast: subprocess_args.append('--failfast') if options.verbosity: subprocess_args.append('--verbosity=%s' % options.verbosity) if not options.interactive: subprocess_args.append('--noinput') for i, label in enumerate(test_labels): print '***** %d of %d: Check test pairing with %s' % (i+1, len(test_labels), label) failures = subprocess.call(subprocess_args + [label, paired_test]) if failures: print '***** Found problem pair with',label return print '***** No problem pair found' teardown(state) if __name__ == "__main__": from optparse import OptionParser usage = "%prog [options] [module module module ...]" parser = OptionParser(usage=usage) parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='1', type='choice', choices=['0', '1', '2', '3'], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output') parser.add_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.') parser.add_option('--failfast', action='store_true', dest='failfast', default=False, help='Tells Django to stop running the test suite after first failed test.') parser.add_option('--settings', help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.') parser.add_option('--bisect', action='store', dest='bisect', default=None, help="Bisect the test suite to discover a test that causes a test failure when combined with the named test.") parser.add_option('--pair', action='store', dest='pair', default=None, help="Run the test suite in pairs with the named test to find problem pairs.") options, args = parser.parse_args() if options.settings: os.environ['DJANGO_SETTINGS_MODULE'] = options.settings elif "DJANGO_SETTINGS_MODULE" not in os.environ: parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. " "Set it or use --settings.") else: options.settings = os.environ['DJANGO_SETTINGS_MODULE'] if options.bisect: bisect_tests(options.bisect, options, args) elif options.pair: paired_tests(options.pair, options, args) else: failures = django_tests(int(options.verbosity), options.interactive, options.failfast, args) if failures: sys.exit(bool(failures))
13,950
Python
.py
290
40.306897
161
0.659124
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,737
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_utils/urls.py
from django.conf.urls.defaults import patterns import views urlpatterns = patterns('', (r'^get_person/(\d+)/$', views.get_person), )
140
Python
.py
5
25.6
47
0.719697
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,738
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_utils/tests.py
import sys from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature from models import Person if sys.version_info >= (2, 5): from tests_25 import AssertNumQueriesContextManagerTests class SkippingTestCase(TestCase): def test_skip_unless_db_feature(self): "A test that might be skipped is actually called." # Total hack, but it works, just want an attribute that's always true. @skipUnlessDBFeature("__class__") def test_func(): raise ValueError self.assertRaises(ValueError, test_func) class AssertNumQueriesTests(TestCase): def test_assert_num_queries(self): def test_func(): raise ValueError self.assertRaises(ValueError, self.assertNumQueries, 2, test_func ) def test_assert_num_queries_with_client(self): person = Person.objects.create(name='test') self.assertNumQueries( 1, self.client.get, "/test_utils/get_person/%s/" % person.pk ) self.assertNumQueries( 1, self.client.get, "/test_utils/get_person/%s/" % person.pk ) def test_func(): self.client.get("/test_utils/get_person/%s/" % person.pk) self.client.get("/test_utils/get_person/%s/" % person.pk) self.assertNumQueries(2, test_func) class SaveRestoreWarningState(TestCase): def test_save_restore_warnings_state(self): """ Ensure save_warnings_state/restore_warnings_state work correctly. """ # In reality this test could be satisfied by many broken implementations # of save_warnings_state/restore_warnings_state (e.g. just # warnings.resetwarnings()) , but it is difficult to test more. import warnings self.save_warnings_state() class MyWarning(Warning): pass # Add a filter that causes an exception to be thrown, so we can catch it warnings.simplefilter("error", MyWarning) self.assertRaises(Warning, lambda: warnings.warn("warn", MyWarning)) # Now restore. self.restore_warnings_state() # After restoring, we shouldn't get an exception. But we don't want a # warning printed either, so we have to silence the warning. warnings.simplefilter("ignore", MyWarning) warnings.warn("warn", MyWarning) # Remove the filter we just added. self.restore_warnings_state() __test__ = {"API_TEST": r""" # Some checks of the doctest output normalizer. # Standard doctests do fairly >>> from django.utils import simplejson >>> from django.utils.xmlutils import SimplerXMLGenerator >>> from StringIO import StringIO >>> def produce_long(): ... return 42L >>> def produce_int(): ... return 42 >>> def produce_json(): ... return simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2), 'whiz': 42}]) >>> def produce_xml(): ... stream = StringIO() ... xml = SimplerXMLGenerator(stream, encoding='utf-8') ... xml.startDocument() ... xml.startElement("foo", {"aaa" : "1.0", "bbb": "2.0"}) ... xml.startElement("bar", {"ccc" : "3.0"}) ... xml.characters("Hello") ... xml.endElement("bar") ... xml.startElement("whiz", {}) ... xml.characters("Goodbye") ... xml.endElement("whiz") ... xml.endElement("foo") ... xml.endDocument() ... return stream.getvalue() >>> def produce_xml_fragment(): ... stream = StringIO() ... xml = SimplerXMLGenerator(stream, encoding='utf-8') ... xml.startElement("foo", {"aaa": "1.0", "bbb": "2.0"}) ... xml.characters("Hello") ... xml.endElement("foo") ... xml.startElement("bar", {"ccc": "3.0", "ddd": "4.0"}) ... xml.endElement("bar") ... return stream.getvalue() # Long values are normalized and are comparable to normal integers ... >>> produce_long() 42 # ... and vice versa >>> produce_int() 42L # JSON output is normalized for field order, so it doesn't matter # which order json dictionary attributes are listed in output >>> produce_json() '["foo", {"bar": ["baz", null, 1.0, 2], "whiz": 42}]' >>> produce_json() '["foo", {"whiz": 42, "bar": ["baz", null, 1.0, 2]}]' # XML output is normalized for attribute order, so it doesn't matter # which order XML element attributes are listed in output >>> produce_xml() '<?xml version="1.0" encoding="UTF-8"?>\n<foo aaa="1.0" bbb="2.0"><bar ccc="3.0">Hello</bar><whiz>Goodbye</whiz></foo>' >>> produce_xml() '<?xml version="1.0" encoding="UTF-8"?>\n<foo bbb="2.0" aaa="1.0"><bar ccc="3.0">Hello</bar><whiz>Goodbye</whiz></foo>' >>> produce_xml_fragment() '<foo aaa="1.0" bbb="2.0">Hello</foo><bar ccc="3.0" ddd="4.0"></bar>' >>> produce_xml_fragment() '<foo bbb="2.0" aaa="1.0">Hello</foo><bar ddd="4.0" ccc="3.0"></bar>' """}
4,833
Python
.py
117
36.222222
119
0.633917
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,739
tests_25.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_utils/tests_25.py
from __future__ import with_statement from django.test import TestCase from models import Person class AssertNumQueriesContextManagerTests(TestCase): def test_simple(self): with self.assertNumQueries(0): pass with self.assertNumQueries(1): Person.objects.count() with self.assertNumQueries(2): Person.objects.count() Person.objects.count() def test_failure(self): with self.assertRaises(AssertionError) as exc_info: with self.assertNumQueries(2): Person.objects.count() self.assertIn("1 queries executed, 2 expected", str(exc_info.exception)) with self.assertRaises(TypeError): with self.assertNumQueries(4000): raise TypeError def test_with_client(self): person = Person.objects.create(name="test") with self.assertNumQueries(1): self.client.get("/test_utils/get_person/%s/" % person.pk) with self.assertNumQueries(1): self.client.get("/test_utils/get_person/%s/" % person.pk) with self.assertNumQueries(2): self.client.get("/test_utils/get_person/%s/" % person.pk) self.client.get("/test_utils/get_person/%s/" % person.pk)
1,281
Python
.py
29
34.344828
80
0.642742
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,740
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/test_utils/views.py
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from models import Person def get_person(request, pk): person = get_object_or_404(Person, pk=pk) return HttpResponse(person.name)
222
Python
.py
6
34.666667
46
0.796296
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,741
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/syndication/models.py
from django.db import models class Entry(models.Model): title = models.CharField(max_length=200) date = models.DateTimeField() class Meta: ordering = ('date',) def __unicode__(self): return self.title def get_absolute_url(self): return "/blog/%s/" % self.pk class Article(models.Model): title = models.CharField(max_length=200) entry = models.ForeignKey(Entry) def __unicode__(self): return self.title
474
Python
.py
15
25.8
44
0.660754
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,742
feeds.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/syndication/feeds.py
from django.contrib.syndication import feeds, views from django.core.exceptions import ObjectDoesNotExist from django.utils import feedgenerator, tzinfo from models import Article, Entry class ComplexFeed(views.Feed): def get_object(self, request, foo=None): if foo is not None: raise ObjectDoesNotExist return None class TestRss2Feed(views.Feed): title = 'My blog' description = 'A more thorough description of my blog.' link = '/blog/' feed_guid = '/foo/bar/1234' author_name = 'Sally Smith' author_email = '[email protected]' author_link = 'http://www.example.com/' categories = ('python', 'django') feed_copyright = 'Copyright (c) 2007, Sally Smith' ttl = 600 def items(self): return Entry.objects.all() def item_description(self, item): return "Overridden description: %s" % item def item_pubdate(self, item): return item.date item_author_name = 'Sally Smith' item_author_email = '[email protected]' item_author_link = 'http://www.example.com/' item_categories = ('python', 'testing') item_copyright = 'Copyright (c) 2007, Sally Smith' class TestRss091Feed(TestRss2Feed): feed_type = feedgenerator.RssUserland091Feed class TestAtomFeed(TestRss2Feed): feed_type = feedgenerator.Atom1Feed subtitle = TestRss2Feed.description class ArticlesFeed(TestRss2Feed): """ A feed to test no link being defined. Articles have no get_absolute_url() method, and item_link() is not defined. """ def items(self): return Article.objects.all() class TestEnclosureFeed(TestRss2Feed): pass class TemplateFeed(TestRss2Feed): """ A feed to test defining item titles and descriptions with templates. """ title_template = 'syndication/title.html' description_template = 'syndication/description.html' # Defining a template overrides any item_title definition def item_title(self): return "Not in a template" class NaiveDatesFeed(TestAtomFeed): """ A feed with naive (non-timezone-aware) dates. """ def item_pubdate(self, item): return item.date class TZAwareDatesFeed(TestAtomFeed): """ A feed with timezone-aware dates. """ def item_pubdate(self, item): # Provide a weird offset so that the test can know it's getting this # specific offset and not accidentally getting on from # settings.TIME_ZONE. return item.date.replace(tzinfo=tzinfo.FixedOffset(42)) class TestFeedUrlFeed(TestAtomFeed): feed_url = 'http://example.com/customfeedurl/' class MyCustomAtom1Feed(feedgenerator.Atom1Feed): """ Test of a custom feed generator class. """ def root_attributes(self): attrs = super(MyCustomAtom1Feed, self).root_attributes() attrs[u'django'] = u'rocks' return attrs def add_root_elements(self, handler): super(MyCustomAtom1Feed, self).add_root_elements(handler) handler.addQuickElement(u'spam', u'eggs') def item_attributes(self, item): attrs = super(MyCustomAtom1Feed, self).item_attributes(item) attrs[u'bacon'] = u'yum' return attrs def add_item_elements(self, handler, item): super(MyCustomAtom1Feed, self).add_item_elements(handler, item) handler.addQuickElement(u'ministry', u'silly walks') class TestCustomFeed(TestAtomFeed): feed_type = MyCustomAtom1Feed class DeprecatedComplexFeed(feeds.Feed): def get_object(self, bits): if len(bits) != 1: raise ObjectDoesNotExist return None class DeprecatedRssFeed(feeds.Feed): link = "/blog/" title = 'My blog' def items(self): return Entry.objects.all() def item_link(self, item): return "/blog/%s/" % item.pk
3,833
Python
.py
103
31.368932
77
0.694934
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,743
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/syndication/urls.py
from django.conf.urls.defaults import * import feeds feed_dict = { 'complex': feeds.DeprecatedComplexFeed, 'rss': feeds.DeprecatedRssFeed, } urlpatterns = patterns('django.contrib.syndication.views', (r'^complex/(?P<foo>.*)/$', feeds.ComplexFeed()), (r'^rss2/$', feeds.TestRss2Feed()), (r'^rss091/$', feeds.TestRss091Feed()), (r'^atom/$', feeds.TestAtomFeed()), (r'^custom/$', feeds.TestCustomFeed()), (r'^naive-dates/$', feeds.NaiveDatesFeed()), (r'^aware-dates/$', feeds.TZAwareDatesFeed()), (r'^feedurl/$', feeds.TestFeedUrlFeed()), (r'^articles/$', feeds.ArticlesFeed()), (r'^template/$', feeds.TemplateFeed()), (r'^depr-feeds/(?P<url>.*)/$', 'feed', {'feed_dict': feed_dict}), (r'^depr-feeds-empty/(?P<url>.*)/$', 'feed', {'feed_dict': None}), )
811
Python
.py
20
36.55
70
0.625159
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,744
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/syndication/tests.py
import datetime import warnings from xml.dom import minidom from django.contrib.syndication import feeds, views from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.utils import tzinfo from django.utils.feedgenerator import rfc2822_date, rfc3339_date from models import Entry class FeedTestCase(TestCase): fixtures = ['feeddata.json'] def assertChildNodes(self, elem, expected): actual = set([n.nodeName for n in elem.childNodes]) expected = set(expected) self.assertEqual(actual, expected) def assertChildNodeContent(self, elem, expected): for k, v in expected.items(): self.assertEqual( elem.getElementsByTagName(k)[0].firstChild.wholeText, v) def assertCategories(self, elem, expected): self.assertEqual(set(i.firstChild.wholeText for i in elem.childNodes if i.nodeName == 'category'), set(expected)); ###################################### # Feed view ###################################### class SyndicationFeedTest(FeedTestCase): """ Tests for the high-level syndication feed framework. """ def test_rss2_feed(self): """ Test the structure and content of feeds generated by Rss201rev2Feed. """ response = self.client.get('/syndication/rss2/') doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName('rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute('version'), '2.0') # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName('channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] # Find the last build date d = Entry.objects.latest('date').date ltz = tzinfo.LocalTimezone(d) last_build_date = rfc2822_date(d.replace(tzinfo=ltz)) self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category']) self.assertChildNodeContent(chan, { 'title': 'My blog', 'description': 'A more thorough description of my blog.', 'link': 'http://example.com/blog/', 'language': 'en', 'lastBuildDate': last_build_date, #'atom:link': '', 'ttl': '600', 'copyright': 'Copyright (c) 2007, Sally Smith', }) self.assertCategories(chan, ['python', 'django']); # Ensure the content of the channel is correct self.assertChildNodeContent(chan, { 'title': 'My blog', 'link': 'http://example.com/blog/', }) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName('atom:link')[0].getAttribute('href'), 'http://example.com/syndication/rss2/' ) # Find the pubdate of the first feed item d = Entry.objects.get(pk=1).date ltz = tzinfo.LocalTimezone(d) pub_date = rfc2822_date(d.replace(tzinfo=ltz)) items = chan.getElementsByTagName('item') self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent(items[0], { 'title': 'My first entry', 'description': 'Overridden description: My first entry', 'link': 'http://example.com/blog/1/', 'guid': 'http://example.com/blog/1/', 'pubDate': pub_date, 'author': '[email protected] (Sally Smith)', }) self.assertCategories(items[0], ['python', 'testing']); for item in items: self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'category', 'pubDate', 'author']) def test_rss091_feed(self): """ Test the structure and content of feeds generated by RssUserland091Feed. """ response = self.client.get('/syndication/rss091/') doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName('rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute('version'), '0.91') # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName('channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link', 'ttl', 'copyright', 'category']) # Ensure the content of the channel is correct self.assertChildNodeContent(chan, { 'title': 'My blog', 'link': 'http://example.com/blog/', }) self.assertCategories(chan, ['python', 'django']) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName('atom:link')[0].getAttribute('href'), 'http://example.com/syndication/rss091/' ) items = chan.getElementsByTagName('item') self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent(items[0], { 'title': 'My first entry', 'description': 'Overridden description: My first entry', 'link': 'http://example.com/blog/1/', }) for item in items: self.assertChildNodes(item, ['title', 'link', 'description']) self.assertCategories(item, []) def test_atom_feed(self): """ Test the structure and content of feeds generated by Atom1Feed. """ response = self.client.get('/syndication/atom/') feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('xmlns'), 'http://www.w3.org/2005/Atom') self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'rights', 'category', 'author']) for link in feed.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href'), 'http://example.com/syndication/atom/') entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertChildNodes(entry, ['title', 'link', 'id', 'summary', 'category', 'updated', 'rights', 'author']) summary = entry.getElementsByTagName('summary')[0] self.assertEqual(summary.getAttribute('type'), 'html') def test_custom_feed_generator(self): response = self.client.get('/syndication/custom/') feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('django'), 'rocks') self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'entry', 'spam', 'rights', 'category', 'author']) entries = feed.getElementsByTagName('entry') self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertEqual(entry.getAttribute('bacon'), 'yum') self.assertChildNodes(entry, ['title', 'link', 'id', 'summary', 'ministry', 'rights', 'author', 'updated', 'category']) summary = entry.getElementsByTagName('summary')[0] self.assertEqual(summary.getAttribute('type'), 'html') def test_title_escaping(self): """ Tests that titles are escaped correctly in RSS feeds. """ response = self.client.get('/syndication/rss2/') doc = minidom.parseString(response.content) for item in doc.getElementsByTagName('item'): link = item.getElementsByTagName('link')[0] if link.firstChild.wholeText == 'http://example.com/blog/4/': title = item.getElementsByTagName('title')[0] self.assertEqual(title.firstChild.wholeText, u'A &amp; B &lt; C &gt; D') def test_naive_datetime_conversion(self): """ Test that datetimes are correctly converted to the local time zone. """ # Naive date times passed in get converted to the local time zone, so # check the recived zone offset against the local offset. response = self.client.get('/syndication/naive-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText d = Entry.objects.latest('date').date ltz = tzinfo.LocalTimezone(d) latest = rfc3339_date(d.replace(tzinfo=ltz)) self.assertEqual(updated, latest) def test_aware_datetime_conversion(self): """ Test that datetimes with timezones don't get trodden on. """ response = self.client.get('/syndication/aware-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText self.assertEqual(updated[-6:], '+00:42') def test_feed_url(self): """ Test that the feed_url can be overridden. """ response = self.client.get('/syndication/feedurl/') doc = minidom.parseString(response.content) for link in doc.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href'), 'http://example.com/customfeedurl/') def test_secure_urls(self): """ Test URLs are prefixed with https:// when feed is requested over HTTPS. """ response = self.client.get('/syndication/rss2/', **{ 'wsgi.url_scheme': 'https', }) doc = minidom.parseString(response.content) chan = doc.getElementsByTagName('channel')[0] self.assertEqual( chan.getElementsByTagName('link')[0].firstChild.wholeText[0:5], 'https' ) atom_link = chan.getElementsByTagName('atom:link')[0] self.assertEqual(atom_link.getAttribute('href')[0:5], 'https') for link in doc.getElementsByTagName('link'): if link.getAttribute('rel') == 'self': self.assertEqual(link.getAttribute('href')[0:5], 'https') def test_item_link_error(self): """ Test that a ImproperlyConfigured is raised if no link could be found for the item(s). """ self.assertRaises(ImproperlyConfigured, self.client.get, '/syndication/articles/') def test_template_feed(self): """ Test that the item title and description can be overridden with templates. """ response = self.client.get('/syndication/template/') doc = minidom.parseString(response.content) feed = doc.getElementsByTagName('rss')[0] chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertChildNodeContent(items[0], { 'title': 'Title in your templates: My first entry', 'description': 'Description in your templates: My first entry', 'link': 'http://example.com/blog/1/', }) def test_add_domain(self): """ Test add_domain() prefixes domains onto the correct URLs. """ self.assertEqual( views.add_domain('example.com', '/foo/?arg=value'), 'http://example.com/foo/?arg=value' ) self.assertEqual( views.add_domain('example.com', '/foo/?arg=value', True), 'https://example.com/foo/?arg=value' ) self.assertEqual( views.add_domain('example.com', 'http://djangoproject.com/doc/'), 'http://djangoproject.com/doc/' ) self.assertEqual( views.add_domain('example.com', 'https://djangoproject.com/doc/'), 'https://djangoproject.com/doc/' ) self.assertEqual( views.add_domain('example.com', 'mailto:[email protected]'), 'mailto:[email protected]' ) ###################################### # Deprecated feeds ###################################### class DeprecatedSyndicationFeedTest(FeedTestCase): """ Tests for the deprecated API (feed() view and the feed_dict etc). """ def setUp(self): self.save_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.contrib.syndication.feeds') warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.contrib.syndication.views') def tearDown(self): self.restore_warnings_state() def test_empty_feed_dict(self): """ Test that an empty feed_dict raises a 404. """ response = self.client.get('/syndication/depr-feeds-empty/aware-dates/') self.assertEqual(response.status_code, 404) def test_nonexistent_slug(self): """ Test that a non-existent slug raises a 404. """ response = self.client.get('/syndication/depr-feeds/foobar/') self.assertEqual(response.status_code, 404) def test_rss_feed(self): """ A simple test for Rss201rev2Feed feeds generated by the deprecated system. """ response = self.client.get('/syndication/depr-feeds/rss/') doc = minidom.parseString(response.content) feed = doc.getElementsByTagName('rss')[0] self.assertEqual(feed.getAttribute('version'), '2.0') chan = feed.getElementsByTagName('channel')[0] self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link']) items = chan.getElementsByTagName('item') self.assertEqual(len(items), Entry.objects.count()) def test_complex_base_url(self): """ Tests that the base url for a complex feed doesn't raise a 500 exception. """ response = self.client.get('/syndication/depr-feeds/complex/') self.assertEqual(response.status_code, 404)
14,553
Python
.py
311
37.289389
151
0.615618
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,745
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/select_related_regress/models.py
from django.db import models class Building(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return u"Building: %s" % self.name class Device(models.Model): building = models.ForeignKey('Building') name = models.CharField(max_length=10) def __unicode__(self): return u"device '%s' in building %s" % (self.name, self.building) class Port(models.Model): device = models.ForeignKey('Device') port_number = models.CharField(max_length=10) def __unicode__(self): return u"%s/%s" % (self.device.name, self.port_number) class Connection(models.Model): start = models.ForeignKey(Port, related_name='connection_start', unique=True) end = models.ForeignKey(Port, related_name='connection_end', unique=True) def __unicode__(self): return u"%s to %s" % (self.start, self.end) # Another non-tree hierarchy that exercises code paths similar to the above # example, but in a slightly different configuration. class TUser(models.Model): name = models.CharField(max_length=200) class Person(models.Model): user = models.ForeignKey(TUser, unique=True) class Organizer(models.Model): person = models.ForeignKey(Person) class Student(models.Model): person = models.ForeignKey(Person) class Class(models.Model): org = models.ForeignKey(Organizer) class Enrollment(models.Model): std = models.ForeignKey(Student) cls = models.ForeignKey(Class) # Models for testing bug #8036. class Country(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country) class ClientStatus(models.Model): name = models.CharField(max_length=50) class Client(models.Model): name = models.CharField(max_length=50) state = models.ForeignKey(State, null=True) status = models.ForeignKey(ClientStatus) class SpecialClient(Client): value = models.IntegerField() # Some model inheritance exercises class Parent(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name class Child(Parent): value = models.IntegerField() class Item(models.Model): name = models.CharField(max_length=10) child = models.ForeignKey(Child, null=True) def __unicode__(self): return self.name
2,390
Python
.py
62
34.129032
77
0.722222
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,746
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/select_related_regress/tests.py
from django.test import TestCase from regressiontests.select_related_regress.models import * class SelectRelatedRegressTests(TestCase): def test_regression_7110(self): """ Regression test for bug #7110. When using select_related(), we must query the Device and Building tables using two different aliases (each) in order to differentiate the start and end Connection fields. The net result is that both the "connections = ..." queries here should give the same results without pulling in more than the absolute minimum number of tables (history has shown that it's easy to make a mistake in the implementation and include some unnecessary bonus joins). """ b=Building.objects.create(name='101') dev1=Device.objects.create(name="router", building=b) dev2=Device.objects.create(name="switch", building=b) dev3=Device.objects.create(name="server", building=b) port1=Port.objects.create(port_number='4',device=dev1) port2=Port.objects.create(port_number='7',device=dev2) port3=Port.objects.create(port_number='1',device=dev3) c1=Connection.objects.create(start=port1, end=port2) c2=Connection.objects.create(start=port2, end=port3) connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id') self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections], [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')]) connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id') self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections], [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')]) # This final query should only join seven tables (port, device and building # twice each, plus connection once). self.assertEqual(connections.query.count_active_tables(), 7) def test_regression_8106(self): """ Regression test for bug #8106. Same sort of problem as the previous test, but this time there are more extra tables to pull in as part of the select_related() and some of them could potentially clash (so need to be kept separate). """ us = TUser.objects.create(name="std") usp = Person.objects.create(user=us) uo = TUser.objects.create(name="org") uop = Person.objects.create(user=uo) s = Student.objects.create(person = usp) o = Organizer.objects.create(person = uop) c = Class.objects.create(org=o) e = Enrollment.objects.create(std=s, cls=c) e_related = Enrollment.objects.all().select_related()[0] self.assertEqual(e_related.std.person.user.name, u"std") self.assertEqual(e_related.cls.org.person.user.name, u"org") def test_regression_8036(self): """ Regression test for bug #8036 the first related model in the tests below ("state") is empty and we try to select the more remotely related state__country. The regression here was not skipping the empty column results for country before getting status. """ australia = Country.objects.create(name='Australia') active = ClientStatus.objects.create(name='active') client = Client.objects.create(name='client', status=active) self.assertEqual(client.status, active) self.assertEqual(Client.objects.select_related()[0].status, active) self.assertEqual(Client.objects.select_related('state')[0].status, active) self.assertEqual(Client.objects.select_related('state', 'status')[0].status, active) self.assertEqual(Client.objects.select_related('state__country')[0].status, active) self.assertEqual(Client.objects.select_related('state__country', 'status')[0].status, active) self.assertEqual(Client.objects.select_related('status')[0].status, active) def test_multi_table_inheritance(self): """ Exercising select_related() with multi-table model inheritance. """ c1 = Child.objects.create(name="child1", value=42) i1 = Item.objects.create(name="item1", child=c1) i2 = Item.objects.create(name="item2") self.assertQuerysetEqual( Item.objects.select_related("child").order_by("name"), ["<Item: item1>", "<Item: item2>"] ) def test_regression_12851(self): """ Regression for #12851 Deferred fields are used correctly if you select_related a subset of fields. """ australia = Country.objects.create(name='Australia') active = ClientStatus.objects.create(name='active') wa = State.objects.create(name="Western Australia", country=australia) c1 = Client.objects.create(name='Brian Burke', state=wa, status=active) burke = Client.objects.select_related('state').defer('state__name').get(name='Brian Burke') self.assertEqual(burke.name, u'Brian Burke') self.assertEqual(burke.state.name, u'Western Australia') # Still works if we're dealing with an inherited class sc1 = SpecialClient.objects.create(name='Troy Buswell', state=wa, status=active, value=42) troy = SpecialClient.objects.select_related('state').defer('state__name').get(name='Troy Buswell') self.assertEqual(troy.name, u'Troy Buswell') self.assertEqual(troy.value, 42) self.assertEqual(troy.state.name, u'Western Australia') # Still works if we defer an attribute on the inherited class troy = SpecialClient.objects.select_related('state').defer('value', 'state__name').get(name='Troy Buswell') self.assertEqual(troy.name, u'Troy Buswell') self.assertEqual(troy.value, 42) self.assertEqual(troy.state.name, u'Western Australia') # Also works if you use only, rather than defer troy = SpecialClient.objects.select_related('state').only('name').get(name='Troy Buswell') self.assertEqual(troy.name, u'Troy Buswell') self.assertEqual(troy.value, 42) self.assertEqual(troy.state.name, u'Western Australia')
6,336
Python
.py
106
50.698113
129
0.675105
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,747
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/context_processors/urls.py
from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^request_attrs/$', views.request_processor), (r'^auth_processor_no_attr_access/$', views.auth_processor_no_attr_access), (r'^auth_processor_attr_access/$', views.auth_processor_attr_access), (r'^auth_processor_user/$', views.auth_processor_user), (r'^auth_processor_perms/$', views.auth_processor_perms), (r'^auth_processor_messages/$', views.auth_processor_messages), url(r'^userpage/(.+)/$', views.userpage, name="userpage"), )
544
Python
.py
11
45.636364
79
0.7
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,748
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/context_processors/tests.py
""" Tests for Django's bundled context processors. """ import warnings from django.conf import settings from django.contrib.auth import authenticate from django.db.models import Q from django.test import TestCase from django.template import Template class RequestContextProcessorTests(TestCase): """ Tests for the ``django.core.context_processors.request`` processor. """ urls = 'regressiontests.context_processors.urls' def test_request_attributes(self): """ Test that the request object is available in the template and that its attributes can't be overridden by GET and POST parameters (#3828). """ url = '/request_attrs/' # We should have the request object in the template. response = self.client.get(url) self.assertContains(response, 'Have request') # Test is_secure. response = self.client.get(url) self.assertContains(response, 'Not secure') response = self.client.get(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') response = self.client.post(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') # Test path. response = self.client.get(url) self.assertContains(response, url) response = self.client.get(url, {'path': '/blah/'}) self.assertContains(response, url) response = self.client.post(url, {'path': '/blah/'}) self.assertContains(response, url) class AuthContextProcessorTests(TestCase): """ Tests for the ``django.contrib.auth.context_processors.auth`` processor """ urls = 'regressiontests.context_processors.urls' fixtures = ['context-processors-users.xml'] def setUp(self): self.save_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.contrib.auth.models') warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.core.context_processors') def tearDown(self): self.restore_warnings_state() def test_session_not_accessed(self): """ Tests that the session is not accessed simply by including the auth context processor """ response = self.client.get('/auth_processor_no_attr_access/') self.assertContains(response, "Session not accessed") def test_session_is_accessed(self): """ Tests that the session is accessed if the auth context processor is used and relevant attributes accessed. """ response = self.client.get('/auth_processor_attr_access/') self.assertContains(response, "Session accessed") def test_perms_attrs(self): self.client.login(username='super', password='secret') response = self.client.get('/auth_processor_perms/') self.assertContains(response, "Has auth permissions") def test_message_attrs(self): self.client.login(username='super', password='secret') response = self.client.get('/auth_processor_messages/') self.assertContains(response, "Message 1") def test_user_attrs(self): """ Test that the lazy objects returned behave just like the wrapped objects. """ # These are 'functional' level tests for common use cases. Direct # testing of the implementation (SimpleLazyObject) is in the 'utils' # tests. self.client.login(username='super', password='secret') user = authenticate(username='super', password='secret') response = self.client.get('/auth_processor_user/') self.assertContains(response, "unicode: super") self.assertContains(response, "id: 100") self.assertContains(response, "username: super") # bug #12037 is tested by the {% url %} in the template: self.assertContains(response, "url: /userpage/super/") # See if this object can be used for queries where a Q() comparing # a user can be used with another Q() (in an AND or OR fashion). # This simulates what a template tag might do with the user from the # context. Note that we don't need to execute a query, just build it. # # The failure case (bug #12049) on Python 2.4 with a LazyObject-wrapped # User is a fatal TypeError: "function() takes at least 2 arguments # (0 given)" deep inside deepcopy(). # # Python 2.5 and 2.6 succeeded, but logged internally caught exception # spew: # # Exception RuntimeError: 'maximum recursion depth exceeded while # calling a Python object' in <type 'exceptions.AttributeError'> # ignored" query = Q(user=response.context['user']) & Q(someflag=True) # Tests for user equality. This is hard because User defines # equality in a non-duck-typing way # See bug #12060 self.assertEqual(response.context['user'], user) self.assertEqual(user, response.context['user'])
5,103
Python
.py
109
38.678899
81
0.660442
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,749
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/context_processors/views.py
from django.core import context_processors from django.shortcuts import render_to_response from django.template.context import RequestContext def request_processor(request): return render_to_response('context_processors/request_attrs.html', RequestContext(request, {}, processors=[context_processors.request])) def auth_processor_no_attr_access(request): r1 = render_to_response('context_processors/auth_attrs_no_access.html', RequestContext(request, {}, processors=[context_processors.auth])) # *After* rendering, we check whether the session was accessed return render_to_response('context_processors/auth_attrs_test_access.html', {'session_accessed':request.session.accessed}) def auth_processor_attr_access(request): r1 = render_to_response('context_processors/auth_attrs_access.html', RequestContext(request, {}, processors=[context_processors.auth])) return render_to_response('context_processors/auth_attrs_test_access.html', {'session_accessed':request.session.accessed}) def auth_processor_user(request): return render_to_response('context_processors/auth_attrs_user.html', RequestContext(request, {}, processors=[context_processors.auth])) def auth_processor_perms(request): return render_to_response('context_processors/auth_attrs_perms.html', RequestContext(request, {}, processors=[context_processors.auth])) def auth_processor_messages(request): request.user.message_set.create(message="Message 1") return render_to_response('context_processors/auth_attrs_messages.html', RequestContext(request, {}, processors=[context_processors.auth])) def userpage(request): pass
1,698
Python
.py
29
53.517241
79
0.762793
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,750
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_ordering/models.py
# coding: utf-8 from django.db import models from django.contrib import admin class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() rank = models.IntegerField() class Meta: ordering = ('name',) class Song(models.Model): band = models.ForeignKey(Band) name = models.CharField(max_length=100) duration = models.IntegerField() class Meta: ordering = ('name',) class SongInlineDefaultOrdering(admin.StackedInline): model = Song class SongInlineNewOrdering(admin.StackedInline): model = Song ordering = ('duration', )
616
Python
.py
20
26.5
53
0.715254
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,751
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_ordering/tests.py
from django.test import TestCase from django.contrib.admin.options import ModelAdmin from models import Band, Song, SongInlineDefaultOrdering, SongInlineNewOrdering class TestAdminOrdering(TestCase): """ Let's make sure that ModelAdmin.queryset uses the ordering we define in ModelAdmin rather that ordering defined in the model's inner Meta class. """ def setUp(self): b1 = Band(name='Aerosmith', bio='', rank=3) b1.save() b2 = Band(name='Radiohead', bio='', rank=1) b2.save() b3 = Band(name='Van Halen', bio='', rank=2) b3.save() def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ ma = ModelAdmin(Band, None) names = [b.name for b in ma.queryset(None)] self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names) def test_specified_ordering(self): """ Let's use a custom ModelAdmin that changes the ordering, and make sure it actually changes. """ class BandAdmin(ModelAdmin): ordering = ('rank',) # default ordering is ('name',) ma = BandAdmin(Band, None) names = [b.name for b in ma.queryset(None)] self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names) class TestInlineModelAdminOrdering(TestCase): """ Let's make sure that InlineModelAdmin.queryset uses the ordering we define in InlineModelAdmin. """ def setUp(self): b = Band(name='Aerosmith', bio='', rank=3) b.save() self.b = b s1 = Song(band=b, name='Pink', duration=235) s1.save() s2 = Song(band=b, name='Dude (Looks Like a Lady)', duration=264) s2.save() s3 = Song(band=b, name='Jaded', duration=214) s3.save() def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta class. """ inline = SongInlineDefaultOrdering(self.b, None) names = [s.name for s in inline.queryset(None)] self.assertEqual([u'Dude (Looks Like a Lady)', u'Jaded', u'Pink'], names) def test_specified_ordering(self): """ Let's check with ordering set to something different than the default. """ inline = SongInlineNewOrdering(self.b, None) names = [s.name for s in inline.queryset(None)] self.assertEqual([u'Jaded', u'Pink', u'Dude (Looks Like a Lady)'], names)
2,558
Python
.py
64
32.34375
81
0.62671
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,752
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/m2m_regress/models.py
from django.db import models from django.contrib.auth import models as auth # No related name is needed here, since symmetrical relations are not # explicitly reversible. class SelfRefer(models.Model): name = models.CharField(max_length=10) references = models.ManyToManyField('self') related = models.ManyToManyField('self') def __unicode__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name # Regression for #11956 -- a many to many to the base class class TagCollection(Tag): tags = models.ManyToManyField(Tag, related_name='tag_collections') def __unicode__(self): return self.name # A related_name is required on one of the ManyToManyField entries here because # they are both addressable as reverse relations from Tag. class Entry(models.Model): name = models.CharField(max_length=10) topics = models.ManyToManyField(Tag) related = models.ManyToManyField(Tag, related_name="similar") def __unicode__(self): return self.name # Two models both inheriting from a base model with a self-referential m2m field class SelfReferChild(SelfRefer): pass class SelfReferChildSibling(SelfRefer): pass # Many-to-Many relation between models, where one of the PK's isn't an Autofield class Line(models.Model): name = models.CharField(max_length=100) class Worksheet(models.Model): id = models.CharField(primary_key=True, max_length=100) lines = models.ManyToManyField(Line, blank=True, null=True) # Regression for #11226 -- A model with the same name that another one to # which it has a m2m relation. This shouldn't cause a name clash between # the automatically created m2m intermediary table FK field names when # running syncdb class User(models.Model): name = models.CharField(max_length=30) friends = models.ManyToManyField(auth.User)
1,930
Python
.py
45
39.2
80
0.755342
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,753
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/m2m_regress/tests.py
from django.core.exceptions import FieldError from django.test import TestCase from models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild, SelfReferChildSibling, Worksheet) class M2MRegressionTests(TestCase): def test_multiple_m2m(self): # Multiple m2m references to model must be distinguished when # accessing the relations through an instance attribute. s1 = SelfRefer.objects.create(name='s1') s2 = SelfRefer.objects.create(name='s2') s3 = SelfRefer.objects.create(name='s3') s1.references.add(s2) s1.related.add(s3) e1 = Entry.objects.create(name='e1') t1 = Tag.objects.create(name='t1') t2 = Tag.objects.create(name='t2') e1.topics.add(t1) e1.related.add(t2) self.assertQuerysetEqual(s1.references.all(), ["<SelfRefer: s2>"]) self.assertQuerysetEqual(s1.related.all(), ["<SelfRefer: s3>"]) self.assertQuerysetEqual(e1.topics.all(), ["<Tag: t1>"]) self.assertQuerysetEqual(e1.related.all(), ["<Tag: t2>"]) def test_internal_related_name_not_in_error_msg(self): # The secret internal related names for self-referential many-to-many # fields shouldn't appear in the list when an error is made. self.assertRaisesRegexp(FieldError, "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$", lambda: SelfRefer.objects.filter(porcupine='fred') ) def test_m2m_inheritance_symmetry(self): # Test to ensure that the relationship between two inherited models # with a self-referential m2m field maintains symmetry sr_child = SelfReferChild(name="Hanna") sr_child.save() sr_sibling = SelfReferChildSibling(name="Beth") sr_sibling.save() sr_child.related.add(sr_sibling) self.assertQuerysetEqual(sr_child.related.all(), ["<SelfRefer: Beth>"]) self.assertQuerysetEqual(sr_sibling.related.all(), ["<SelfRefer: Hanna>"]) def test_m2m_pk_field_type(self): # Regression for #11311 - The primary key for models in a m2m relation # doesn't have to be an AutoField w = Worksheet(id='abc') w.save() w.delete() def test_add_m2m_with_base_class(self): # Regression for #11956 -- You can add an object to a m2m with the # base class without causing integrity errors t1 = Tag.objects.create(name='t1') t2 = Tag.objects.create(name='t2') c1 = TagCollection.objects.create(name='c1') c1.tags = [t1,t2] c1 = TagCollection.objects.get(name='c1') self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"]) self.assertQuerysetEqual(t1.tag_collections.all(), ["<TagCollection: c1>"])
2,819
Python
.py
55
42.763636
97
0.663994
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,754
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_inlines/models.py
""" Testing of admin inline formsets. """ from django.db import models from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django import forms class Parent(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Child(models.Model): name = models.CharField(max_length=50) teacher = models.ForeignKey(Teacher) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() parent = generic.GenericForeignKey() def __unicode__(self): return u'I am %s, a child of %s' % (self.name, self.parent) class Book(models.Model): name = models.CharField(max_length=50) class Author(models.Model): name = models.CharField(max_length=50) books = models.ManyToManyField(Book) class BookInline(admin.TabularInline): model = Author.books.through class AuthorAdmin(admin.ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) class Holder(models.Model): dummy = models.IntegerField() class Inner(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder) readonly = models.CharField("Inner readonly label", max_length=1) class InnerInline(admin.StackedInline): model = Inner can_delete = False readonly_fields = ('readonly',) # For bug #13174 tests. class Holder2(models.Model): dummy = models.IntegerField() class Inner2(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder2) class HolderAdmin(admin.ModelAdmin): class Media: js = ('my_awesome_admin_scripts.js',) class InnerInline2(admin.StackedInline): model = Inner2 class Media: js = ('my_awesome_inline_scripts.js',) class Holder3(models.Model): dummy = models.IntegerField() class Inner3(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder3) class InnerInline3(admin.StackedInline): model = Inner3 class Media: js = ('my_awesome_inline_scripts.js',) # Test bug #12561 and #12778 # only ModelAdmin media admin.site.register(Holder, HolderAdmin, inlines=[InnerInline]) # ModelAdmin and Inline media admin.site.register(Holder2, HolderAdmin, inlines=[InnerInline2]) # only Inline media admin.site.register(Holder3, inlines=[InnerInline3]) # Models for #12749 class Person(models.Model): firstname = models.CharField(max_length=15) class OutfitItem(models.Model): name = models.CharField(max_length=15) class Fashionista(models.Model): person = models.OneToOneField(Person, primary_key=True) weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True) class ShoppingWeakness(models.Model): fashionista = models.ForeignKey(Fashionista) item = models.ForeignKey(OutfitItem) class InlineWeakness(admin.TabularInline): model = ShoppingWeakness extra = 1 admin.site.register(Fashionista, inlines=[InlineWeakness]) # Models for #13510 class TitleCollection(models.Model): pass class Title(models.Model): collection = models.ForeignKey(TitleCollection, blank=True, null=True) title1 = models.CharField(max_length=100) title2 = models.CharField(max_length=100) class TitleForm(forms.ModelForm): def clean(self): cleaned_data = self.cleaned_data title1 = cleaned_data.get("title1") title2 = cleaned_data.get("title2") if title1 != title2: raise forms.ValidationError("The two titles must be the same") return cleaned_data class TitleInline(admin.TabularInline): model = Title form = TitleForm extra = 1 admin.site.register(TitleCollection, inlines=[TitleInline]) # Models for #15424 class Poll(models.Model): name = models.CharField(max_length=40) class Question(models.Model): poll = models.ForeignKey(Poll) class QuestionInline(admin.TabularInline): model = Question readonly_fields=['call_me'] def call_me(self, obj): return 'Callable in QuestionInline' class PollAdmin(admin.ModelAdmin): inlines = [QuestionInline] def call_me(self, obj): return 'Callable in PollAdmin' class Novel(models.Model): name = models.CharField(max_length=40) class Chapter(models.Model): novel = models.ForeignKey(Novel) class ChapterInline(admin.TabularInline): model = Chapter readonly_fields=['call_me'] def call_me(self, obj): return 'Callable in ChapterInline' class NovelAdmin(admin.ModelAdmin): inlines = [ChapterInline] admin.site.register(Poll, PollAdmin) admin.site.register(Novel, NovelAdmin)
4,836
Python
.py
134
31.873134
91
0.744562
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,755
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/admin_inlines/tests.py
from django.contrib.admin.helpers import InlineAdminForm from django.contrib.contenttypes.models import ContentType from django.test import TestCase # local test models from models import (Holder, Inner, InnerInline, Holder2, Inner2, Holder3, Inner3, Person, OutfitItem, Fashionista, Teacher, Parent, Child) class TestInline(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() self.change_url = '/test_admin/admin/admin_inlines/holder/%i/' % holder.id result = self.client.login(username='super', password='secret') self.assertEqual(result, True) def tearDown(self): self.client.logout() def test_can_delete(self): """ can_delete should be passed to inlineformset factory. """ response = self.client.get(self.change_url) inner_formset = response.context[-1]['inline_admin_formsets'][0].formset expected = InnerInline.can_delete actual = inner_formset.can_delete self.assertEqual(expected, actual, 'can_delete must be equal') def test_readonly_stacked_inline_label(self): """Bug #13174.""" holder = Holder.objects.create(dummy=42) inner = Inner.objects.create(holder=holder, dummy=42, readonly='') response = self.client.get('/test_admin/admin/admin_inlines/holder/%i/' % holder.id) self.assertContains(response, '<label>Inner readonly label:</label>') def test_many_to_many_inlines(self): "Autogenerated many-to-many inlines are displayed correctly (#13407)" response = self.client.get('/test_admin/admin/admin_inlines/author/add/') # The heading for the m2m inline block uses the right text self.assertContains(response, '<h2>Author-book relationships</h2>') # The "add another" label is correct self.assertContains(response, 'Add another Author-Book Relationship') # The '+' is dropped from the autogenerated form prefix (Author_books+) self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_primary(self): person = Person.objects.create(firstname='Imelda') item = OutfitItem.objects.create(name='Shoes') # Imelda likes shoes, but can't cary her own bags. data = { 'shoppingweakness_set-TOTAL_FORMS': 1, 'shoppingweakness_set-INITIAL_FORMS': 0, 'shoppingweakness_set-MAX_NUM_FORMS': 0, '_save': u'Save', 'person': person.id, 'max_weight': 0, 'shoppingweakness_set-0-item': item.id, } response = self.client.post('/test_admin/admin/admin_inlines/fashionista/add/', data) self.assertEqual(response.status_code, 302) self.assertEqual(len(Fashionista.objects.filter(person__firstname='Imelda')), 1) def test_tabular_non_field_errors(self): """ Ensure that non_field_errors are displayed correctly, including the right value for colspan. Refs #13510. """ data = { 'title_set-TOTAL_FORMS': 1, 'title_set-INITIAL_FORMS': 0, 'title_set-MAX_NUM_FORMS': 0, '_save': u'Save', 'title_set-0-title1': 'a title', 'title_set-0-title2': 'a different title', } response = self.client.post('/test_admin/admin/admin_inlines/titlecollection/add/', data) # Here colspan is "4": two fields (title1 and title2), one hidden field and the delete checkbock. self.assertContains(response, '<tr><td colspan="4"><ul class="errorlist"><li>The two titles must be the same</li></ul></td></tr>') def test_no_parent_callable_lookup(self): """Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable""" # Identically named callable isn't present in the parent ModelAdmin, # rendering of the add view shouldn't explode response = self.client.get('/test_admin/admin/admin_inlines/novel/add/') self.assertEqual(response.status_code, 200) # View should have the child inlines section self.assertContains(response, '<div class="inline-group" id="chapter_set-group">') def test_callable_lookup(self): """Admin inline should invoke local callable when its name is listed in readonly_fields""" response = self.client.get('/test_admin/admin/admin_inlines/poll/add/') self.assertEqual(response.status_code, 200) # Add parent object view should have the child inlines section self.assertContains(response, '<div class="inline-group" id="question_set-group">') # The right callabe should be used for the inline readonly_fields # column cells self.assertContains(response, '<p>Callable in QuestionInline</p>') class TestInlineMedia(TestCase): fixtures = ['admin-views-users.xml'] def setUp(self): result = self.client.login(username='super', password='secret') self.assertEqual(result, True) def tearDown(self): self.client.logout() def test_inline_media_only_base(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() change_url = '/test_admin/admin/admin_inlines/holder/%i/' % holder.id response = self.client.get(change_url) self.assertContains(response, 'my_awesome_admin_scripts.js') def test_inline_media_only_inline(self): holder = Holder3(dummy=13) holder.save() Inner3(dummy=42, holder=holder).save() change_url = '/test_admin/admin/admin_inlines/holder3/%i/' % holder.id response = self.client.get(change_url) self.assertContains(response, 'my_awesome_inline_scripts.js') def test_all_inline_media(self): holder = Holder2(dummy=13) holder.save() Inner2(dummy=42, holder=holder).save() change_url = '/test_admin/admin/admin_inlines/holder2/%i/' % holder.id response = self.client.get(change_url) self.assertContains(response, 'my_awesome_admin_scripts.js') self.assertContains(response, 'my_awesome_inline_scripts.js') class TestInlineAdminForm(TestCase): def test_immutable_content_type(self): """Regression for #9362 The problem depends only on InlineAdminForm and its "original" argument, so we can safely set the other arguments to None/{}. We just need to check that the content_type argument of Child isn't altered by the internals of the inline form.""" sally = Teacher.objects.create(name='Sally') john = Parent.objects.create(name='John') joe = Child.objects.create(name='Joe', teacher=sally, parent=john) iaf = InlineAdminForm(None, None, {}, {}, joe) parent_ct = ContentType.objects.get_for_model(Parent) self.assertEqual(iaf.original.content_type, parent_ct)
7,030
Python
.py
133
44.105263
138
0.663611
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,756
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/m2m_through_regress/models.py
from datetime import datetime from django.contrib.auth.models import User from django.core import management from django.db import models # Forward declared intermediate model class Membership(models.Model): person = models.ForeignKey('Person') group = models.ForeignKey('Group') price = models.IntegerField(default=100) def __unicode__(self): return "%s is a member of %s" % (self.person.name, self.group.name) # using custom id column to test ticket #11107 class UserMembership(models.Model): id = models.AutoField(db_column='usermembership_id', primary_key=True) user = models.ForeignKey(User) group = models.ForeignKey('Group') price = models.IntegerField(default=100) def __unicode__(self): return "%s is a user and member of %s" % (self.user.username, self.group.name) class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) # Membership object defined as a class members = models.ManyToManyField(Person, through=Membership) user_members = models.ManyToManyField(User, through='UserMembership') def __unicode__(self): return self.name # A set of models that use an non-abstract inherited model as the 'through' model. class A(models.Model): a_text = models.CharField(max_length=20) class ThroughBase(models.Model): a = models.ForeignKey(A) b = models.ForeignKey('B') class Through(ThroughBase): extra = models.CharField(max_length=20) class B(models.Model): b_text = models.CharField(max_length=20) a_list = models.ManyToManyField(A, through=Through) # Using to_field on the through model class Car(models.Model): make = models.CharField(max_length=20, unique=True) drivers = models.ManyToManyField('Driver', through='CarDriver') def __unicode__(self, ): return self.make class Driver(models.Model): name = models.CharField(max_length=20, unique=True) def __unicode__(self, ): return self.name class CarDriver(models.Model): car = models.ForeignKey('Car', to_field='make') driver = models.ForeignKey('Driver', to_field='name') def __unicode__(self, ): return u"pk=%s car=%s driver=%s" % (str(self.pk), self.car, self.driver)
2,347
Python
.py
56
37.392857
86
0.7163
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,757
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/m2m_through_regress/tests.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.core import management from django.contrib.auth.models import User from django.test import TestCase from models import (Person, Group, Membership, UserMembership, Car, Driver, CarDriver) class M2MThroughTestCase(TestCase): def test_everything(self): bob = Person.objects.create(name="Bob") jim = Person.objects.create(name="Jim") rock = Group.objects.create(name="Rock") roll = Group.objects.create(name="Roll") frank = User.objects.create_user("frank", "[email protected]", "password") jane = User.objects.create_user("jane", "[email protected]", "password") Membership.objects.create(person=bob, group=rock) Membership.objects.create(person=bob, group=roll) Membership.objects.create(person=jim, group=rock) self.assertQuerysetEqual( bob.group_set.all(), [ "<Group: Rock>", "<Group: Roll>", ] ) self.assertQuerysetEqual( roll.members.all(), [ "<Person: Bob>", ] ) self.assertRaises(AttributeError, setattr, bob, "group_set", []) self.assertRaises(AttributeError, setattr, roll, "members", []) self.assertRaises(AttributeError, rock.members.create, name="Anne") self.assertRaises(AttributeError, bob.group_set.create, name="Funk") UserMembership.objects.create(user=frank, group=rock) UserMembership.objects.create(user=frank, group=roll) UserMembership.objects.create(user=jane, group=rock) self.assertQuerysetEqual( frank.group_set.all(), [ "<Group: Rock>", "<Group: Roll>", ] ) self.assertQuerysetEqual( roll.user_members.all(), [ "<User: frank>", ] ) def test_serialization(self): "m2m-through models aren't serialized as m2m fields. Refs #8134" p = Person.objects.create(name="Bob") g = Group.objects.create(name="Roll") m =Membership.objects.create(person=p, group=g) pks = {"p_pk": p.pk, "g_pk": g.pk, "m_pk": m.pk} out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out) self.assertEqual(out.getvalue().strip(), """[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": 100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": "Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]""" % pks) out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out) self.assertEqual(out.getvalue().strip(), """ <?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object pk="%(m_pk)s" model="m2m_through_regress.membership"> <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field> <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field> <field type="IntegerField" name="price">100</field> </object> <object pk="%(p_pk)s" model="m2m_through_regress.person"> <field type="CharField" name="name">Bob</field> </object> <object pk="%(g_pk)s" model="m2m_through_regress.group"> <field type="CharField" name="name">Roll</field> </object> </django-objects> """.strip() % pks) def test_join_trimming(self): "Check that we don't involve too many copies of the intermediate table when doing a join. Refs #8046, #8254" bob = Person.objects.create(name="Bob") jim = Person.objects.create(name="Jim") rock = Group.objects.create(name="Rock") roll = Group.objects.create(name="Roll") Membership.objects.create(person=bob, group=rock) Membership.objects.create(person=jim, group=rock, price=50) Membership.objects.create(person=bob, group=roll, price=50) self.assertQuerysetEqual( rock.members.filter(membership__price=50), [ "<Person: Jim>", ] ) self.assertQuerysetEqual( bob.group_set.filter(membership__price=50), [ "<Group: Roll>", ] ) class ToFieldThroughTests(TestCase): def setUp(self): self.car = Car.objects.create(make="Toyota") self.driver = Driver.objects.create(name="Ryan Briscoe") CarDriver.objects.create(car=self.car, driver=self.driver) def test_to_field(self): self.assertQuerysetEqual( self.car.drivers.all(), ["<Driver: Ryan Briscoe>"] ) def test_to_field_reverse(self): self.assertQuerysetEqual( self.driver.car_set.all(), ["<Car: Toyota>"] ) class ThroughLoadDataTestCase(TestCase): fixtures = ["m2m_through"] def test_sequence_creation(self): "Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107" out = StringIO() management.call_command("dumpdata", "m2m_through_regress", format="json", stdout=out) self.assertEqual(out.getvalue().strip(), """[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, "model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]""")
5,743
Python
.py
118
39.754237
356
0.619303
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,758
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/select_related_onetoone/models.py
from django.db import models class User(models.Model): username = models.CharField(max_length=100) email = models.EmailField() def __unicode__(self): return self.username class UserProfile(models.Model): user = models.OneToOneField(User) city = models.CharField(max_length=100) state = models.CharField(max_length=2) def __unicode__(self): return "%s, %s" % (self.city, self.state) class UserStatResult(models.Model): results = models.CharField(max_length=50) def __unicode__(self): return 'UserStatResults, results = %s' % (self.results,) class UserStat(models.Model): user = models.OneToOneField(User, primary_key=True) posts = models.IntegerField() results = models.ForeignKey(UserStatResult) def __unicode__(self): return 'UserStat, posts = %s' % (self.posts,) class StatDetails(models.Model): base_stats = models.OneToOneField(UserStat) comments = models.IntegerField() def __unicode__(self): return 'StatDetails, comments = %s' % (self.comments,) class AdvancedUserStat(UserStat): karma = models.IntegerField() class Image(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) image = models.OneToOneField(Image, null=True)
1,340
Python
.py
34
34.294118
64
0.705288
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,759
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/select_related_onetoone/tests.py
from django import db from django.conf import settings from django.test import TestCase from models import (User, UserProfile, UserStat, UserStatResult, StatDetails, AdvancedUserStat, Image, Product) class ReverseSelectRelatedTestCase(TestCase): def setUp(self): user = User.objects.create(username="test") userprofile = UserProfile.objects.create(user=user, state="KS", city="Lawrence") results = UserStatResult.objects.create(results='first results') userstat = UserStat.objects.create(user=user, posts=150, results=results) details = StatDetails.objects.create(base_stats=userstat, comments=259) user2 = User.objects.create(username="bob") results2 = UserStatResult.objects.create(results='moar results') advstat = AdvancedUserStat.objects.create(user=user2, posts=200, karma=5, results=results2) StatDetails.objects.create(base_stats=advstat, comments=250) def test_basic(self): def test(): u = User.objects.select_related("userprofile").get(username="test") self.assertEqual(u.userprofile.state, "KS") self.assertNumQueries(1, test) def test_follow_next_level(self): def test(): u = User.objects.select_related("userstat__results").get(username="test") self.assertEqual(u.userstat.posts, 150) self.assertEqual(u.userstat.results.results, 'first results') self.assertNumQueries(1, test) def test_follow_two(self): def test(): u = User.objects.select_related("userprofile", "userstat").get(username="test") self.assertEqual(u.userprofile.state, "KS") self.assertEqual(u.userstat.posts, 150) self.assertNumQueries(1, test) def test_follow_two_next_level(self): def test(): u = User.objects.select_related("userstat__results", "userstat__statdetails").get(username="test") self.assertEqual(u.userstat.results.results, 'first results') self.assertEqual(u.userstat.statdetails.comments, 259) self.assertNumQueries(1, test) def test_forward_and_back(self): def test(): stat = UserStat.objects.select_related("user__userprofile").get(user__username="test") self.assertEqual(stat.user.userprofile.state, 'KS') self.assertEqual(stat.user.userstat.posts, 150) self.assertNumQueries(1, test) def test_back_and_forward(self): def test(): u = User.objects.select_related("userstat").get(username="test") self.assertEqual(u.userstat.user.username, 'test') self.assertNumQueries(1, test) def test_not_followed_by_default(self): def test(): u = User.objects.select_related().get(username="test") self.assertEqual(u.userstat.posts, 150) self.assertNumQueries(2, test) def test_follow_from_child_class(self): def test(): stat = AdvancedUserStat.objects.select_related('user', 'statdetails').get(posts=200) self.assertEqual(stat.statdetails.comments, 250) self.assertEqual(stat.user.username, 'bob') self.assertNumQueries(1, test) def test_follow_inheritance(self): def test(): stat = UserStat.objects.select_related('user', 'advanceduserstat').get(posts=200) self.assertEqual(stat.advanceduserstat.posts, 200) self.assertEqual(stat.user.username, 'bob') self.assertEqual(stat.advanceduserstat.user.username, 'bob') self.assertNumQueries(1, test) def test_nullable_relation(self): im = Image.objects.create(name="imag1") p1 = Product.objects.create(name="Django Plushie", image=im) p2 = Product.objects.create(name="Talking Django Plushie") self.assertEqual(len(Product.objects.select_related("image")), 2)
4,044
Python
.py
76
42.315789
110
0.649469
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,760
included_urls2.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/included_urls2.py
""" These URL patterns are included in two different ways in the main urls.py, with an extra argument present in one case. Thus, there are two different ways for each name to resolve and Django must distinguish the possibilities based on the argument list. """ from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^part/(?P<value>\w+)/$', empty_view, name="part"), url(r'^part2/(?:(?P<value>\w+)/)?$', empty_view, name="part2"), )
490
Python
.py
12
39
79
0.726891
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,761
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/urls.py
from django.conf.urls.defaults import * from views import empty_view, absolute_kwargs_view other_patterns = patterns('', url(r'non_path_include/$', empty_view, name='non_path_include'), ) urlpatterns = patterns('', url(r'^places/(\d+)/$', empty_view, name='places'), url(r'^places?/$', empty_view, name="places?"), url(r'^places+/$', empty_view, name="places+"), url(r'^places*/$', empty_view, name="places*"), url(r'^(?:places/)?$', empty_view, name="places2?"), url(r'^(?:places/)+$', empty_view, name="places2+"), url(r'^(?:places/)*$', empty_view, name="places2*"), url(r'^places/(\d+|[a-z_]+)/', empty_view, name="places3"), url(r'^places/(?P<id>\d+)/$', empty_view, name="places4"), url(r'^people/(?P<name>\w+)/$', empty_view, name="people"), url(r'^people/(?:name/)', empty_view, name="people2"), url(r'^people/(?:name/(\w+)/)?', empty_view, name="people2a"), url(r'^optional/(?P<name>.*)/(?:.+/)?', empty_view, name="optional"), url(r'^hardcoded/$', 'hardcoded/', empty_view, name="hardcoded"), url(r'^hardcoded/doc\.pdf$', empty_view, name="hardcoded2"), url(r'^people/(?P<state>\w\w)/(?P<name>\w+)/$', empty_view, name="people3"), url(r'^people/(?P<state>\w\w)/(?P<name>\d)/$', empty_view, name="people4"), url(r'^people/((?P<state>\w\w)/test)?/(\w+)/$', empty_view, name="people6"), url(r'^character_set/[abcdef0-9]/$', empty_view, name="range"), url(r'^character_set/[\w]/$', empty_view, name="range2"), url(r'^price/\$(\d+)/$', empty_view, name="price"), url(r'^price/[$](\d+)/$', empty_view, name="price2"), url(r'^price/[\$](\d+)/$', empty_view, name="price3"), url(r'^product/(?P<product>\w+)\+\(\$(?P<price>\d+(\.\d+)?)\)/$', empty_view, name="product"), url(r'^headlines/(?P<year>\d+)\.(?P<month>\d+)\.(?P<day>\d+)/$', empty_view, name="headlines"), url(r'^windows_path/(?P<drive_name>[A-Z]):\\(?P<path>.+)/$', empty_view, name="windows"), url(r'^special_chars/(.+)/$', empty_view, name="special"), url(r'^(?P<name>.+)/\d+/$', empty_view, name="mixed"), url(r'^repeats/a{1,2}/$', empty_view, name="repeats"), url(r'^repeats/a{2,4}/$', empty_view, name="repeats2"), url(r'^repeats/a{2}/$', empty_view, name="repeats3"), url(r'^(?i)CaseInsensitive/(\w+)', empty_view, name="insensitive"), url(r'^test/1/?', empty_view, name="test"), url(r'^(?i)test/2/?$', empty_view, name="test2"), url(r'^outer/(?P<outer>\d+)/', include('regressiontests.urlpatterns_reverse.included_urls')), url('', include('regressiontests.urlpatterns_reverse.extra_urls')), # This is non-reversible, but we shouldn't blow up when parsing it. url(r'^(?:foo|bar)(\w+)/$', empty_view, name="disjunction"), # Regression views for #9038. See tests for more details url(r'arg_view/$', 'kwargs_view'), url(r'arg_view/(?P<arg1>\d+)/$', 'kwargs_view'), url(r'absolute_arg_view/(?P<arg1>\d+)/$', absolute_kwargs_view), url(r'absolute_arg_view/$', absolute_kwargs_view), url('^includes/', include(other_patterns)), )
3,133
Python
.py
55
51.6
80
0.582192
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,762
extra_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/extra_urls.py
""" Some extra URL patterns that are included at the top level. """ from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^e-places/(\d+)/$', empty_view, name='extra-places'), url(r'^e-people/(?P<name>\w+)/$', empty_view, name="extra-people"), url('', include('regressiontests.urlpatterns_reverse.included_urls2')), url(r'^prefix/(?P<prefix>\w+)/', include('regressiontests.urlpatterns_reverse.included_urls2')), )
481
Python
.py
11
41.090909
100
0.698718
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,763
named_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/named_urls.py
from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^$', empty_view, name="named-url1"), url(r'^extra/(?P<extra>\w+)/$', empty_view, name="named-url2"), url(r'^(?P<one>\d+)|(?P<two>\d+)/$', empty_view), (r'^included/', include('regressiontests.urlpatterns_reverse.included_named_urls')), )
357
Python
.py
8
41.5
88
0.655172
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,764
urlconf_outer.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/urlconf_outer.py
from django.conf.urls.defaults import * import urlconf_inner urlpatterns = patterns('', url(r'^test/me/$', urlconf_inner.inner_view, name='outer'), url(r'^inner_urlconf/', include(urlconf_inner.__name__)) )
217
Python
.py
6
33.5
63
0.708134
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,765
urls_without_full_import.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/urls_without_full_import.py
# A URLs file that doesn't use the default # from django.conf.urls.defaults import * # import pattern. from django.conf.urls.defaults import patterns, url from views import empty_view, bad_view urlpatterns = patterns('', url(r'^test_view/$', empty_view, name="test_view"), url(r'^bad_view/$', bad_view, name="bad_view"), )
332
Python
.py
9
34.888889
55
0.720497
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,766
included_named_urls2.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/included_named_urls2.py
from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^$', empty_view, name="named-url5"), url(r'^extra/(?P<extra>\w+)/$', empty_view, name="named-url6"), url(r'^(?P<one>\d+)|(?P<two>\d+)/$', empty_view), )
269
Python
.py
7
35.428571
67
0.623077
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,767
included_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/included_urls.py
from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^$', empty_view, name="inner-nothing"), url(r'^extra/(?P<extra>\w+)/$', empty_view, name="inner-extra"), url(r'^(?P<one>\d+)|(?P<two>\d+)/$', empty_view, name="inner-disjunction"), )
298
Python
.py
7
39.714286
79
0.641379
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,768
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/tests.py
""" Unit tests for reverse URL lookups. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, resolve, NoReverseMatch,\ Resolver404, ResolverMatch,\ RegexURLResolver, RegexURLPattern from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.shortcuts import redirect from django.test import TestCase from django.utils import unittest import urlconf_outer import urlconf_inner import middleware import views resolve_test_data = ( # These entries are in the format: (path, url_name, app_name, namespace, view_func, args, kwargs) # Simple case ('/normal/42/37/', 'normal-view', None, '', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), ('/view_class/42/37/', 'view-class', None, '', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), ('/included/normal/42/37/', 'inc-normal-view', None, '', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), ('/included/view_class/42/37/', 'inc-view-class', None, '', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), # Unnamed args are dropped if you have *any* kwargs in a pattern ('/mixed_args/42/37/', 'mixed-args', None, '', views.empty_view, tuple(), {'arg2': '37'}), ('/included/mixed_args/42/37/', 'inc-mixed-args', None, '', views.empty_view, tuple(), {'arg2': '37'}), # Unnamed views will be resolved to the function/class name ('/unnamed/normal/42/37/', 'regressiontests.urlpatterns_reverse.views.empty_view', None, '', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), ('/unnamed/view_class/42/37/', 'regressiontests.urlpatterns_reverse.views.ViewClass', None, '', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), # If you have no kwargs, you get an args list. ('/no_kwargs/42/37/', 'no-kwargs', None, '', views.empty_view, ('42','37'), {}), ('/included/no_kwargs/42/37/', 'inc-no-kwargs', None, '', views.empty_view, ('42','37'), {}), # Namespaces ('/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/ns-included1/normal/42/37/', 'inc-normal-view', None, 'inc-ns1', views.empty_view, tuple(), {'arg1': '42', 'arg2': '37'}), ('/included/test3/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns3', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/default/inner/42/37/', 'urlobject-view', 'testapp', 'testapp', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/other2/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns2', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/other1/inner/42/37/', 'urlobject-view', 'nodefault', 'other-ns1', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), # Nested namespaces ('/ns-included1/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:test-ns3', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/ns-included1/ns-included4/ns-included2/test3/inner/42/37/', 'urlobject-view', 'testapp', 'inc-ns1:inc-ns4:inc-ns2:test-ns3', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ) test_data = ( ('places', '/places/3/', [3], {}), ('places', '/places/3/', ['3'], {}), ('places', NoReverseMatch, ['a'], {}), ('places', NoReverseMatch, [], {}), ('places?', '/place/', [], {}), ('places+', '/places/', [], {}), ('places*', '/place/', [], {}), ('places2?', '/', [], {}), ('places2+', '/places/', [], {}), ('places2*', '/', [], {}), ('places3', '/places/4/', [4], {}), ('places3', '/places/harlem/', ['harlem'], {}), ('places3', NoReverseMatch, ['harlem64'], {}), ('places4', '/places/3/', [], {'id': 3}), ('people', NoReverseMatch, [], {}), ('people', '/people/adrian/', ['adrian'], {}), ('people', '/people/adrian/', [], {'name': 'adrian'}), ('people', NoReverseMatch, ['name with spaces'], {}), ('people', NoReverseMatch, [], {'name': 'name with spaces'}), ('people2', '/people/name/', [], {}), ('people2a', '/people/name/fred/', ['fred'], {}), ('optional', '/optional/fred/', [], {'name': 'fred'}), ('optional', '/optional/fred/', ['fred'], {}), ('hardcoded', '/hardcoded/', [], {}), ('hardcoded2', '/hardcoded/doc.pdf', [], {}), ('people3', '/people/il/adrian/', [], {'state': 'il', 'name': 'adrian'}), ('people3', NoReverseMatch, [], {'state': 'il'}), ('people3', NoReverseMatch, [], {'name': 'adrian'}), ('people4', NoReverseMatch, [], {'state': 'il', 'name': 'adrian'}), ('people6', '/people/il/test/adrian/', ['il/test', 'adrian'], {}), ('people6', '/people//adrian/', ['adrian'], {}), ('range', '/character_set/a/', [], {}), ('range2', '/character_set/x/', [], {}), ('price', '/price/$10/', ['10'], {}), ('price2', '/price/$10/', ['10'], {}), ('price3', '/price/$10/', ['10'], {}), ('product', '/product/chocolate+($2.00)/', [], {'price': '2.00', 'product': 'chocolate'}), ('headlines', '/headlines/2007.5.21/', [], dict(year=2007, month=5, day=21)), ('windows', r'/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/', [], dict(drive_name='C', path=r'Documents and Settings\spam')), ('special', r'/special_chars/+%5C$*/', [r'+\$*'], {}), ('special', NoReverseMatch, [''], {}), ('mixed', '/john/0/', [], {'name': 'john'}), ('repeats', '/repeats/a/', [], {}), ('repeats2', '/repeats/aa/', [], {}), ('repeats3', '/repeats/aa/', [], {}), ('insensitive', '/CaseInsensitive/fred', ['fred'], {}), ('test', '/test/1', [], {}), ('test2', '/test/2', [], {}), ('inner-nothing', '/outer/42/', [], {'outer': '42'}), ('inner-nothing', '/outer/42/', ['42'], {}), ('inner-nothing', NoReverseMatch, ['foo'], {}), ('inner-extra', '/outer/42/extra/inner/', [], {'extra': 'inner', 'outer': '42'}), ('inner-extra', '/outer/42/extra/inner/', ['42', 'inner'], {}), ('inner-extra', NoReverseMatch, ['fred', 'inner'], {}), ('disjunction', NoReverseMatch, ['foo'], {}), ('inner-disjunction', NoReverseMatch, ['10', '11'], {}), ('extra-places', '/e-places/10/', ['10'], {}), ('extra-people', '/e-people/fred/', ['fred'], {}), ('extra-people', '/e-people/fred/', [], {'name': 'fred'}), ('part', '/part/one/', [], {'value': 'one'}), ('part', '/prefix/xx/part/one/', [], {'value': 'one', 'prefix': 'xx'}), ('part2', '/part2/one/', [], {'value': 'one'}), ('part2', '/part2/', [], {}), ('part2', '/prefix/xx/part2/one/', [], {'value': 'one', 'prefix': 'xx'}), ('part2', '/prefix/xx/part2/', [], {'prefix': 'xx'}), # Regression for #9038 # These views are resolved by method name. Each method is deployed twice - # once with an explicit argument, and once using the default value on # the method. This is potentially ambiguous, as you have to pick the # correct view for the arguments provided. ('kwargs_view', '/arg_view/', [], {}), ('kwargs_view', '/arg_view/10/', [], {'arg1':10}), ('regressiontests.urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/', [], {}), ('regressiontests.urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/10/', [], {'arg1':10}), ('non_path_include', '/includes/non_path_include/', [], {}) ) class NoURLPatternsTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.no_urls' def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs): self.assertRaises(error, callable, *args, **kwargs) try: callable(*args, **kwargs) except error, e: self.assertEqual(message, str(e)) def test_no_urls_exception(self): """ RegexURLResolver should raise an exception when no urlpatterns exist. """ resolver = RegexURLResolver(r'^$', self.urls) self.assertRaisesErrorWithMessage(ImproperlyConfigured, "The included urlconf regressiontests.urlpatterns_reverse.no_urls "\ "doesn't have any patterns in it", getattr, resolver, 'url_patterns') class URLPatternReverse(TestCase): urls = 'regressiontests.urlpatterns_reverse.urls' def test_urlpattern_reverse(self): for name, expected, args, kwargs in test_data: try: got = reverse(name, args=args, kwargs=kwargs) except NoReverseMatch, e: self.assertEqual(expected, NoReverseMatch) else: self.assertEqual(got, expected) def test_reverse_none(self): # Reversing None should raise an error, not return the last un-named view. self.assertRaises(NoReverseMatch, reverse, None) class ResolverTests(unittest.TestCase): def test_non_regex(self): """ Verifies that we raise a Resolver404 if what we are resolving doesn't meet the basic requirements of a path to match - i.e., at the very least, it matches the root pattern '^/'. We must never return None from resolve, or we will get a TypeError further down the line. Regression for #10834. """ self.assertRaises(Resolver404, resolve, '') self.assertRaises(Resolver404, resolve, 'a') self.assertRaises(Resolver404, resolve, '\\') self.assertRaises(Resolver404, resolve, '.') def test_404_tried_urls_have_names(self): """ Verifies that the list of URLs that come back from a Resolver404 exception contains a list in the right format for printing out in the DEBUG 404 page with both the patterns and URL names, if available. """ urls = 'regressiontests.urlpatterns_reverse.named_urls' # this list matches the expected URL types and names returned when # you try to resolve a non-existent URL in the first level of included # URLs in named_urls.py (e.g., '/included/non-existent-url') url_types_names = [ [{'type': RegexURLPattern, 'name': 'named-url1'}], [{'type': RegexURLPattern, 'name': 'named-url2'}], [{'type': RegexURLPattern, 'name': None}], [{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': 'named-url3'}], [{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': 'named-url4'}], [{'type': RegexURLResolver}, {'type': RegexURLPattern, 'name': None}], [{'type': RegexURLResolver}, {'type': RegexURLResolver}], ] try: resolve('/included/non-existent-url', urlconf=urls) self.fail('resolve did not raise a 404') except Resolver404, e: # make sure we at least matched the root ('/') url resolver: self.assertTrue('tried' in e.args[0]) tried = e.args[0]['tried'] self.assertEqual(len(e.args[0]['tried']), len(url_types_names), 'Wrong number of tried URLs returned. Expected %s, got %s.' % (len(url_types_names), len(e.args[0]['tried']))) for tried, expected in zip(e.args[0]['tried'], url_types_names): for t, e in zip(tried, expected): self.assertTrue(isinstance(t, e['type']), '%s is not an instance of %s' % (t, e['type'])) if 'name' in e: if not e['name']: self.assertTrue(t.name is None, 'Expected no URL name but found %s.' % t.name) else: self.assertEqual(t.name, e['name'], 'Wrong URL name. Expected "%s", got "%s".' % (e['name'], t.name)) class ReverseShortcutTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.urls' def test_redirect_to_object(self): # We don't really need a model; just something with a get_absolute_url class FakeObj(object): def get_absolute_url(self): return "/hi-there/" res = redirect(FakeObj()) self.assertTrue(isinstance(res, HttpResponseRedirect)) self.assertEqual(res['Location'], '/hi-there/') res = redirect(FakeObj(), permanent=True) self.assertTrue(isinstance(res, HttpResponsePermanentRedirect)) self.assertEqual(res['Location'], '/hi-there/') def test_redirect_to_view_name(self): res = redirect('hardcoded2') self.assertEqual(res['Location'], '/hardcoded/doc.pdf') res = redirect('places', 1) self.assertEqual(res['Location'], '/places/1/') res = redirect('headlines', year='2008', month='02', day='17') self.assertEqual(res['Location'], '/headlines/2008.02.17/') self.assertRaises(NoReverseMatch, redirect, 'not-a-view') def test_redirect_to_url(self): res = redirect('/foo/') self.assertEqual(res['Location'], '/foo/') res = redirect('http://example.com/') self.assertEqual(res['Location'], 'http://example.com/') def test_redirect_view_object(self): from views import absolute_kwargs_view res = redirect(absolute_kwargs_view) self.assertEqual(res['Location'], '/absolute_arg_view/') self.assertRaises(NoReverseMatch, redirect, absolute_kwargs_view, wrong_argument=None) class NamespaceTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.namespace_urls' def test_ambiguous_object(self): "Names deployed via dynamic URL objects that require namespaces can't be resolved" self.assertRaises(NoReverseMatch, reverse, 'urlobject-view') self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', args=[37,42]) self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', kwargs={'arg1':42, 'arg2':37}) def test_ambiguous_urlpattern(self): "Names deployed via dynamic URL objects that require namespaces can't be resolved" self.assertRaises(NoReverseMatch, reverse, 'inner-nothing') self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', args=[37,42]) self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', kwargs={'arg1':42, 'arg2':37}) def test_non_existent_namespace(self): "Non-existent namespaces raise errors" self.assertRaises(NoReverseMatch, reverse, 'blahblah:urlobject-view') self.assertRaises(NoReverseMatch, reverse, 'test-ns1:blahblah:urlobject-view') def test_normal_name(self): "Normal lookups work as expected" self.assertEqual('/normal/', reverse('normal-view')) self.assertEqual('/normal/37/42/', reverse('normal-view', args=[37,42])) self.assertEqual('/normal/42/37/', reverse('normal-view', kwargs={'arg1':42, 'arg2':37})) def test_simple_included_name(self): "Normal lookups work on names included from other patterns" self.assertEqual('/included/normal/', reverse('inc-normal-view')) self.assertEqual('/included/normal/37/42/', reverse('inc-normal-view', args=[37,42])) self.assertEqual('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1':42, 'arg2':37})) def test_namespace_object(self): "Dynamic URL objects can be found using a namespace" self.assertEqual('/test1/inner/', reverse('test-ns1:urlobject-view')) self.assertEqual('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37,42])) self.assertEqual('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_embedded_namespace_object(self): "Namespaces can be installed anywhere in the URL pattern tree" self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view')) self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37,42])) self.assertEqual('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_namespace_pattern(self): "Namespaces can be applied to include()'d urlpatterns" self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view')) self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37,42])) self.assertEqual('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1':42, 'arg2':37})) def test_multiple_namespace_pattern(self): "Namespaces can be embedded" self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view')) self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37,42])) self.assertEqual('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_nested_namespace_pattern(self): "Namespaces can be nested" self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view')) self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37,42])) self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_app_lookup_object(self): "A default application namespace can be used for lookup" self.assertEqual('/default/inner/', reverse('testapp:urlobject-view')) self.assertEqual('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42])) self.assertEqual('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37})) def test_app_lookup_object_with_default(self): "A default application namespace is sensitive to the 'current' app can be used for lookup" self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3')) self.assertEqual('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42], current_app='test-ns3')) self.assertEqual('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='test-ns3')) def test_app_lookup_object_without_default(self): "An application namespace without a default is sensitive to the 'current' app can be used for lookup" self.assertEqual('/other2/inner/', reverse('nodefault:urlobject-view')) self.assertEqual('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42])) self.assertEqual('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1')) self.assertEqual('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42], current_app='other-ns1')) self.assertEqual('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='other-ns1')) class RequestURLconfTests(TestCase): def setUp(self): self.root_urlconf = settings.ROOT_URLCONF self.middleware_classes = settings.MIDDLEWARE_CLASSES settings.ROOT_URLCONF = urlconf_outer.__name__ def tearDown(self): settings.ROOT_URLCONF = self.root_urlconf settings.MIDDLEWARE_CLASSES = self.middleware_classes def test_urlconf(self): response = self.client.get('/test/me/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'outer:/test/me/,' 'inner:/inner_urlconf/second_test/') response = self.client.get('/inner_urlconf/second_test/') self.assertEqual(response.status_code, 200) response = self.client.get('/second_test/') self.assertEqual(response.status_code, 404) def test_urlconf_overridden(self): settings.MIDDLEWARE_CLASSES += ( '%s.ChangeURLconfMiddleware' % middleware.__name__, ) response = self.client.get('/test/me/') self.assertEqual(response.status_code, 404) response = self.client.get('/inner_urlconf/second_test/') self.assertEqual(response.status_code, 404) response = self.client.get('/second_test/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, 'outer:,inner:/second_test/') def test_urlconf_overridden_with_null(self): settings.MIDDLEWARE_CLASSES += ( '%s.NullChangeURLconfMiddleware' % middleware.__name__, ) self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/') class ErrorHandlerResolutionTests(TestCase): """Tests for handler404 and handler500""" def setUp(self): from django.core.urlresolvers import RegexURLResolver urlconf = 'regressiontests.urlpatterns_reverse.urls_error_handlers' urlconf_callables = 'regressiontests.urlpatterns_reverse.urls_error_handlers_callables' self.resolver = RegexURLResolver(r'^$', urlconf) self.callable_resolver = RegexURLResolver(r'^$', urlconf_callables) def test_named_handlers(self): from views import empty_view handler = (empty_view, {}) self.assertEqual(self.resolver.resolve404(), handler) self.assertEqual(self.resolver.resolve500(), handler) def test_callable_handers(self): from views import empty_view handler = (empty_view, {}) self.assertEqual(self.callable_resolver.resolve404(), handler) self.assertEqual(self.callable_resolver.resolve500(), handler) class DefaultErrorHandlerTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.urls_without_full_import' def test_default_handler(self): "If the urls.py doesn't specify handlers, the defaults are used" try: response = self.client.get('/test/') self.assertEqual(response.status_code, 404) except AttributeError: self.fail("Shouldn't get an AttributeError due to undefined 404 handler") try: self.assertRaises(ValueError, self.client.get, '/bad_view/') except AttributeError: self.fail("Shouldn't get an AttributeError due to undefined 500 handler") class NoRootUrlConfTests(TestCase): """Tests for handler404 and handler500 if urlconf is None""" urls = None def test_no_handler_exception(self): self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/') class ResolverMatchTests(TestCase): urls = 'regressiontests.urlpatterns_reverse.namespace_urls' def test_urlpattern_resolve(self): for path, name, app_name, namespace, func, args, kwargs in resolve_test_data: # Test legacy support for extracting "function, args, kwargs" match_func, match_args, match_kwargs = resolve(path) self.assertEqual(match_func, func) self.assertEqual(match_args, args) self.assertEqual(match_kwargs, kwargs) # Test ResolverMatch capabilities. match = resolve(path) self.assertEqual(match.__class__, ResolverMatch) self.assertEqual(match.url_name, name) self.assertEqual(match.args, args) self.assertEqual(match.kwargs, kwargs) self.assertEqual(match.app_name, app_name) self.assertEqual(match.namespace, namespace) self.assertEqual(match.func, func) # ... and for legacy purposes: self.assertEqual(match[0], func) self.assertEqual(match[1], args) self.assertEqual(match[2], kwargs)
23,916
Python
.py
390
53.148718
187
0.630087
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,769
included_namespace_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/included_namespace_urls.py
from django.conf.urls.defaults import * from namespace_urls import URLObject from views import view_class_instance testobj3 = URLObject('testapp', 'test-ns3') urlpatterns = patterns('regressiontests.urlpatterns_reverse.views', url(r'^normal/$', 'empty_view', name='inc-normal-view'), url(r'^normal/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view', name='inc-normal-view'), url(r'^mixed_args/(\d+)/(?P<arg2>\d+)/$', 'empty_view', name='inc-mixed-args'), url(r'^no_kwargs/(\d+)/(\d+)/$', 'empty_view', name='inc-no-kwargs'), url(r'^view_class/(?P<arg1>\d+)/(?P<arg2>\d+)/$', view_class_instance, name='inc-view-class'), (r'^test3/', include(testobj3.urls)), (r'^ns-included3/', include('regressiontests.urlpatterns_reverse.included_urls', namespace='inc-ns3')), (r'^ns-included4/', include('regressiontests.urlpatterns_reverse.namespace_urls', namespace='inc-ns4')), )
901
Python
.py
14
60.642857
108
0.673099
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,770
middleware.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/middleware.py
from django.core.urlresolvers import set_urlconf import urlconf_inner class ChangeURLconfMiddleware(object): def process_request(self, request): request.urlconf = urlconf_inner.__name__ class NullChangeURLconfMiddleware(object): def process_request(self, request): request.urlconf = None
315
Python
.py
8
35
48
0.776316
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,771
urls_error_handlers.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/urls_error_handlers.py
# Used by the ErrorHandlerResolutionTests test case. from django.conf.urls.defaults import patterns urlpatterns = patterns('') handler404 = 'regressiontests.urlpatterns_reverse.views.empty_view' handler500 = 'regressiontests.urlpatterns_reverse.views.empty_view'
266
Python
.py
5
51.6
67
0.841085
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,772
included_named_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/included_named_urls.py
from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^$', empty_view, name="named-url3"), url(r'^extra/(?P<extra>\w+)/$', empty_view, name="named-url4"), url(r'^(?P<one>\d+)|(?P<two>\d+)/$', empty_view), (r'^included/', include('regressiontests.urlpatterns_reverse.included_named_urls2')), )
359
Python
.py
8
41.625
89
0.65616
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,773
urlconf_inner.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/urlconf_inner.py
from django.conf.urls.defaults import * from django.template import Template, Context from django.http import HttpResponse def inner_view(request): content = Template('{% load url from future %}' '{% url "outer" as outer_url %}outer:{{ outer_url }},' '{% url "inner" as inner_url %}inner:{{ inner_url }}').render(Context()) return HttpResponse(content) urlpatterns = patterns('', url(r'^second_test/$', inner_view, name='inner'), )
491
Python
.py
11
38.272727
95
0.636743
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,774
urls_error_handlers_callables.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/urls_error_handlers_callables.py
# Used by the ErrorHandlerResolutionTests test case. from django.conf.urls.defaults import patterns from views import empty_view urlpatterns = patterns('') handler404 = empty_view handler500 = empty_view
207
Python
.py
6
33
52
0.833333
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,775
views.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/views.py
from django.http import HttpResponse def empty_view(request, *args, **kwargs): return HttpResponse('') def kwargs_view(request, arg1=1, arg2=2): return HttpResponse('') def absolute_kwargs_view(request, arg1=1, arg2=2): return HttpResponse('') class ViewClass(object): def __call__(self, request, *args, **kwargs): return HttpResponse('') view_class_instance = ViewClass() def bad_view(request, *args, **kwargs): raise ValueError("I don't think I'm getting good value for this view")
518
Python
.py
13
36.230769
74
0.713427
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,776
namespace_urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/urlpatterns_reverse/namespace_urls.py
from django.conf.urls.defaults import * from views import view_class_instance class URLObject(object): def __init__(self, app_name, namespace): self.app_name = app_name self.namespace = namespace def urls(self): return patterns('', url(r'^inner/$', 'empty_view', name='urlobject-view'), url(r'^inner/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view', name='urlobject-view'), ), self.app_name, self.namespace urls = property(urls) testobj1 = URLObject('testapp', 'test-ns1') testobj2 = URLObject('testapp', 'test-ns2') default_testobj = URLObject('testapp', 'testapp') otherobj1 = URLObject('nodefault', 'other-ns1') otherobj2 = URLObject('nodefault', 'other-ns2') urlpatterns = patterns('regressiontests.urlpatterns_reverse.views', url(r'^normal/$', 'empty_view', name='normal-view'), url(r'^normal/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view', name='normal-view'), url(r'^mixed_args/(\d+)/(?P<arg2>\d+)/$', 'empty_view', name='mixed-args'), url(r'^no_kwargs/(\d+)/(\d+)/$', 'empty_view', name='no-kwargs'), url(r'^view_class/(?P<arg1>\d+)/(?P<arg2>\d+)/$', view_class_instance, name='view-class'), (r'^unnamed/normal/(?P<arg1>\d+)/(?P<arg2>\d+)/$', 'empty_view'), (r'^unnamed/view_class/(?P<arg1>\d+)/(?P<arg2>\d+)/$', view_class_instance), (r'^test1/', include(testobj1.urls)), (r'^test2/', include(testobj2.urls)), (r'^default/', include(default_testobj.urls)), (r'^other1/', include(otherobj1.urls)), (r'^other2/', include(otherobj2.urls)), (r'^ns-included1/', include('regressiontests.urlpatterns_reverse.included_namespace_urls', namespace='inc-ns1')), (r'^ns-included2/', include('regressiontests.urlpatterns_reverse.included_namespace_urls', namespace='inc-ns2')), (r'^included/', include('regressiontests.urlpatterns_reverse.included_namespace_urls')), )
1,900
Python
.py
34
50.735294
117
0.646519
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,777
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/extra_regress/models.py
import datetime import django.utils.copycompat as copy from django.contrib.auth.models import User from django.db import models class RevisionableModel(models.Model): base = models.ForeignKey('self', null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.datetime.now) def __unicode__(self): return u"%s (%s, %s)" % (self.title, self.id, self.base.id) def save(self, *args, **kwargs): super(RevisionableModel, self).save(*args, **kwargs) if not self.base: self.base = self kwargs.pop('force_insert', None) kwargs.pop('force_update', None) super(RevisionableModel, self).save(*args, **kwargs) def new_revision(self): new_revision = copy.copy(self) new_revision.pk = None return new_revision class Order(models.Model): created_by = models.ForeignKey(User) text = models.TextField() class TestObject(models.Model): first = models.CharField(max_length=20) second = models.CharField(max_length=20) third = models.CharField(max_length=20) def __unicode__(self): return u'TestObject: %s,%s,%s' % (self.first,self.second,self.third)
1,241
Python
.py
30
34.966667
76
0.676103
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,778
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/extra_regress/tests.py
from django.test import TestCase from django.utils.datastructures import SortedDict from django.contrib.auth.models import User from regressiontests.extra_regress.models import TestObject, Order, \ RevisionableModel import datetime class ExtraRegressTests(TestCase): def setUp(self): self.u = User.objects.create_user( username="fred", password="secret", email="[email protected]" ) def test_regression_7314_7372(self): """ Regression tests for #7314 and #7372 """ rm = RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertEqual(rm.pk, rm.base.pk) rm2 = rm.new_revision() rm2.title = "Second Revision" rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0) rm2.save() self.assertEqual(rm2.title, 'Second Revision') self.assertEqual(rm2.base.title, 'First Revision') self.assertNotEqual(rm2.pk, rm.pk) self.assertEqual(rm2.base.pk, rm.pk) # Queryset to match most recent revision: qs = RevisionableModel.objects.extra( where=["%(table)s.id IN (SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)" % { 'table': RevisionableModel._meta.db_table, }] ) self.assertQuerysetEqual(qs, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) # Queryset to search for string in title: qs2 = RevisionableModel.objects.filter(title__contains="Revision") self.assertQuerysetEqual(qs2, [ ('First Revision', 'First Revision'), ('Second Revision', 'First Revision'), ], transform=lambda r: (r.title, r.base.title) ) # Following queryset should return the most recent revision: self.assertQuerysetEqual(qs & qs2, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) def test_extra_stay_tied(self): # Extra select parameters should stay tied to their corresponding # select portions. Applies when portions are updated or otherwise # moved around. qs = User.objects.extra( select=SortedDict((("alpha", "%s"), ("beta", "2"), ("gamma", "%s"))), select_params=(1, 3) ) qs = qs.extra(select={"beta": 4}) qs = qs.extra(select={"alpha": "%s"}, select_params=[5]) self.assertEqual( list(qs.filter(id=self.u.id).values('alpha', 'beta', 'gamma')), [{'alpha': 5, 'beta': 4, 'gamma': 3}] ) def test_regression_7957(self): """ Regression test for #7957: Combining extra() calls should leave the corresponding parameters associated with the right extra() bit. I.e. internal dictionary must remain sorted. """ self.assertEqual( User.objects.extra(select={"alpha": "%s"}, select_params=(1,) ).extra(select={"beta": "%s"}, select_params=(2,))[0].alpha, 1) self.assertEqual( User.objects.extra(select={"beta": "%s"}, select_params=(1,) ).extra(select={"alpha": "%s"}, select_params=(2,))[0].alpha, 2) def test_regression_7961(self): """ Regression test for #7961: When not using a portion of an extra(...) in a query, remove any corresponding parameters from the query as well. """ self.assertEqual( list(User.objects.extra(select={"alpha": "%s"}, select_params=(-6,) ).filter(id=self.u.id).values_list('id', flat=True)), [self.u.id] ) def test_regression_8063(self): """ Regression test for #8063: limiting a query shouldn't discard any extra() bits. """ qs = User.objects.all().extra(where=['id=%s'], params=[self.u.id]) self.assertQuerysetEqual(qs, ['<User: fred>']) self.assertQuerysetEqual(qs[:1], ['<User: fred>']) def test_regression_8039(self): """ Regression test for #8039: Ordering sometimes removed relevant tables from extra(). This test is the critical case: ordering uses a table, but then removes the reference because of an optimisation. The table should still be present because of the extra() call. """ self.assertQuerysetEqual( Order.objects.extra(where=["username=%s"], params=["fred"], tables=["auth_user"] ).order_by('created_by'), [] ) def test_regression_8819(self): """ Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...). """ self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}).distinct(), ['<User: fred>'] ) self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']), ['<User: fred>'] ) self.assertQuerysetEqual( User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']).distinct(), ['<User: fred>'] ) def test_dates_query(self): """ When calling the dates() method on a queryset with extra selection columns, we can (and should) ignore those columns. They don't change the result and cause incorrect SQL to be produced otherwise. """ rm = RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertQuerysetEqual( RevisionableModel.objects.extra(select={"the_answer": 'id'}).dates('when', 'month'), ['datetime.datetime(2008, 9, 1, 0, 0)'] ) def test_values_with_extra(self): """ Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values()), [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id': obj.pk, 'first': u'first'}] ) # Extra clauses after an empty values clause are still included self.assertEqual( list(TestObject.objects.values().extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id': obj.pk, 'first': u'first'}] ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second')), [{'second': u'second', 'first': u'first'}] ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( list(TestObject.objects.values('first', 'second').extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [{'second': u'second', 'first': u'first'}] ) # Extra columns can be partially returned self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second', 'foo')), [{'second': u'second', 'foo': u'first', 'first': u'first'}] ) # Also works if only extra columns are included self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('foo', 'whiz')), [{'foo': u'first', 'whiz': u'third'}] ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list()), [(u'first', u'second', u'third', obj.pk, u'first', u'second', u'third')] ) # Extra columns after an empty values_list() are still included self.assertEqual( list(TestObject.objects.values_list().extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [(u'first', u'second', u'third', obj.pk, u'first', u'second', u'third')] ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second')), [(u'first', u'second')] ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( list(TestObject.objects.values_list('first', 'second').extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), [(u'first', u'second')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('second', flat=True)), [u'second'] ) # Only the extra columns specified in the values_list() are returned self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second', 'whiz')), [(u'first', u'second', u'third')] ) # ...also works if only extra columns are included self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('foo','whiz')), [(u'first', u'third')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', flat=True)), [u'third'] ) # ... and values are returned in the order they are specified self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz','foo')), [(u'third', u'first')] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first','id')), [(u'first', obj.pk)] ) self.assertEqual( list(TestObject.objects.extra(select=SortedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', 'first', 'bar', 'id')), [(u'third', u'first', u'second', obj.pk)] ) def test_regression_10847(self): """ Regression for #10847: the list of extra columns can always be accurately evaluated. Using an inner query ensures that as_sql() is producing correct output without requiring full evaluation and execution of the inner query. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list(TestObject.objects.extra(select={'extra': 1}).values('pk')), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.extra(select={'extra': 1}).values('pk') ), ['<TestObject: TestObject: first,second,third>'] ) self.assertEqual( list(TestObject.objects.values('pk').extra(select={'extra': 1})), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.values('pk').extra(select={'extra': 1}) ), ['<TestObject: TestObject: first,second,third>'] ) self.assertQuerysetEqual( TestObject.objects.filter(pk=obj.pk) | TestObject.objects.extra(where=["id > %s"], params=[obj.pk]), ['<TestObject: TestObject: first,second,third>'] )
12,934
Python
.py
268
37.350746
159
0.567829
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,779
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/mail/tests.py
# coding: utf-8 import asyncore import email import os import shutil import smtpd import sys from StringIO import StringIO import tempfile import threading from django.conf import settings from django.core import mail from django.core.mail import (EmailMessage, mail_admins, mail_managers, EmailMultiAlternatives, send_mail, send_mass_mail) from django.core.mail.backends import console, dummy, locmem, filebased, smtp from django.core.mail.message import BadHeaderError from django.test import TestCase from django.utils.translation import ugettext_lazy from django.utils.functional import wraps def alter_django_settings(**kwargs): oldvalues = {} nonexistant = [] for setting, newvalue in kwargs.iteritems(): try: oldvalues[setting] = getattr(settings, setting) except AttributeError: nonexistant.append(setting) setattr(settings, setting, newvalue) return oldvalues, nonexistant def restore_django_settings(state): oldvalues, nonexistant = state for setting, oldvalue in oldvalues.iteritems(): setattr(settings, setting, oldvalue) for setting in nonexistant: delattr(settings, setting) def with_django_settings(**kwargs): def decorator(test): @wraps(test) def decorated_test(self): state = alter_django_settings(**kwargs) try: return test(self) finally: restore_django_settings(state) return decorated_test return decorator class MailTests(TestCase): """ Non-backend specific tests. """ def test_ascii(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) message = email.message() self.assertEqual(message['Subject'].encode(), 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], '[email protected]') self.assertEqual(message['To'], '[email protected]') def test_multiple_recipients(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]']) message = email.message() self.assertEqual(message['Subject'].encode(), 'Subject') self.assertEqual(message.get_payload(), 'Content') self.assertEqual(message['From'], '[email protected]') self.assertEqual(message['To'], '[email protected], [email protected]') def test_cc(self): """Regression test for #7722""" email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], cc=['[email protected]']) message = email.message() self.assertEqual(message['Cc'], '[email protected]') self.assertEqual(email.recipients(), ['[email protected]', '[email protected]']) # Test multiple CC with multiple To email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]'], cc=['[email protected]', '[email protected]']) message = email.message() self.assertEqual(message['Cc'], '[email protected], [email protected]') self.assertEqual(email.recipients(), ['[email protected]', '[email protected]', '[email protected]', '[email protected]']) # Testing with Bcc email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]', '[email protected]'], cc=['[email protected]', '[email protected]'], bcc=['[email protected]']) message = email.message() self.assertEqual(message['Cc'], '[email protected], [email protected]') self.assertEqual(email.recipients(), ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']) def test_header_injection(self): email = EmailMessage('Subject\nInjection Test', 'Content', '[email protected]', ['[email protected]']) self.assertRaises(BadHeaderError, email.message) email = EmailMessage(ugettext_lazy('Subject\nInjection Test'), 'Content', '[email protected]', ['[email protected]']) self.assertRaises(BadHeaderError, email.message) def test_space_continuation(self): """ Test for space continuation character in long (ascii) subject headers (#7747) """ email = EmailMessage('Long subject lines that get wrapped should use a space continuation character to get expected behaviour in Outlook and Thunderbird', 'Content', '[email protected]', ['[email protected]']) message = email.message() self.assertEqual(message['Subject'], 'Long subject lines that get wrapped should use a space continuation\n character to get expected behaviour in Outlook and Thunderbird') def test_message_header_overrides(self): """ Specifying dates or message-ids in the extra headers overrides the default values (#9233) """ headers = {"date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} email = EmailMessage('subject', 'content', '[email protected]', ['[email protected]'], headers=headers) self.assertEqual(email.message().as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: subject\nFrom: [email protected]\nTo: [email protected]\ndate: Fri, 09 Nov 2001 01:08:47 -0000\nMessage-ID: foo\n\ncontent') def test_from_header(self): """ Make sure we can manually set the From header (#9214) """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) message = email.message() self.assertEqual(message['From'], '[email protected]') def test_multiple_message_call(self): """ Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message() """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) message = email.message() self.assertEqual(message['From'], '[email protected]') message = email.message() self.assertEqual(message['From'], '[email protected]') def test_unicode_address_header(self): """ Regression for #11144 - When a to/from/cc header contains unicode, make sure the email addresses are parsed correctly (especially with regards to commas) """ email = EmailMessage('Subject', 'Content', '[email protected]', ['"Firstname Sürname" <[email protected]>', '[email protected]']) self.assertEqual(email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>, [email protected]') email = EmailMessage('Subject', 'Content', '[email protected]', ['"Sürname, Firstname" <[email protected]>', '[email protected]']) self.assertEqual(email.message()['To'], '=?utf-8?q?S=C3=BCrname=2C_Firstname?= <[email protected]>, [email protected]') def test_unicode_headers(self): email = EmailMessage(u"Gżegżółka", "Content", "[email protected]", ["[email protected]"], headers={"Sender": '"Firstname Sürname" <[email protected]>', "Comments": 'My Sürname is non-ASCII'}) message = email.message() self.assertEqual(message['Subject'], '=?utf-8?b?R8W8ZWfFvMOzxYJrYQ==?=') self.assertEqual(message['Sender'], '=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>') self.assertEqual(message['Comments'], '=?utf-8?q?My_S=C3=BCrname_is_non-ASCII?=') def test_safe_mime_multipart(self): """ Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well """ headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', '[email protected]', '"Sürname, Firstname" <[email protected]>' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives('Message from Firstname Sürname', text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.encoding = 'iso-8859-1' self.assertEqual(msg.message()['To'], '=?iso-8859-1?q?S=FCrname=2C_Firstname?= <[email protected]>') self.assertEqual(msg.message()['Subject'].encode(), u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=') def test_encoding(self): """ Regression for #12791 - Encode body correctly with other encodings than utf-8 """ email = EmailMessage('Subject', 'Firstname Sürname is a great guy.', '[email protected]', ['[email protected]']) email.encoding = 'iso-8859-1' message = email.message() self.assertTrue(message.as_string().startswith('Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]')) self.assertEqual(message.get_payload(), 'Firstname S=FCrname is a great guy.') # Make sure MIME attachments also works correctly with other encodings than utf-8 text_content = 'Firstname Sürname is a great guy.' html_content = '<p>Firstname Sürname is a <strong>great</strong> guy.</p>' msg = EmailMultiAlternatives('Subject', text_content, '[email protected]', ['[email protected]']) msg.encoding = 'iso-8859-1' msg.attach_alternative(html_content, "text/html") self.assertEqual(msg.message().get_payload(0).as_string(), 'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.') self.assertEqual(msg.message().get_payload(1).as_string(), 'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>') def test_attachments(self): """Regression test for #9367""" headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"} subject, from_email, to = 'hello', '[email protected]', '[email protected]' text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, "text/html") msg.attach("an attachment.pdf", "%PDF-1.4.%...", mimetype="application/pdf") msg_str = msg.message().as_string() message = email.message_from_string(msg_str) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_content_type(), 'multipart/mixed') self.assertEqual(message.get_default_type(), 'text/plain') payload = message.get_payload() self.assertEqual(payload[0].get_content_type(), 'multipart/alternative') self.assertEqual(payload[1].get_content_type(), 'application/pdf') def test_dummy_backend(self): """ Make sure that dummy backends returns correct number of sent messages """ connection = dummy.EmailBackend() email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) self.assertEqual(connection.send_messages([email, email, email]), 3) def test_arbitrary_keyword(self): """ Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends. """ c = mail.get_connection(fail_silently=True, foo='bar') self.assertTrue(c.fail_silently) def test_custom_backend(self): """Test custom backend defined in this suite.""" conn = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, 'test_outbox')) email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1) def test_backend_arg(self): """Test backend argument of mail.get_connection()""" self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend)) tmp_dir = tempfile.mkdtemp() try: self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend)) finally: shutil.rmtree(tmp_dir) self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend)) @with_django_settings( EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', ADMINS=[('nobody', '[email protected]')], MANAGERS=[('nobody', '[email protected]')]) def test_connection_arg(self): """Test connection argument to send_mail(), et. al.""" mail.outbox = [] # Send using non-default connection connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, 'Subject') connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') send_mass_mail([ ('Subject1', 'Content1', '[email protected]', ['[email protected]']), ('Subject2', 'Content2', '[email protected]', ['[email protected]']), ], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, 'Subject1') self.assertEqual(connection.test_outbox[1].subject, 'Subject2') connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') mail_admins('Admin message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Admin message') connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') mail_managers('Manager message', 'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, '[Django] Manager message') def test_dont_mangle_from_in_body(self): # Regression for #13433 - Make sure that EmailMessage doesn't mangle # 'From ' in message body. email = EmailMessage('Subject', 'From the future', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) self.assertFalse('>From the future' in email.message().as_string()) class BaseEmailBackendTests(object): email_backend = None def setUp(self): self.__settings_state = alter_django_settings(EMAIL_BACKEND=self.email_backend) def tearDown(self): restore_django_settings(self.__settings_state) def assertStartsWith(self, first, second): if not first.startswith(second): self.longMessage = True self.assertEqual(first[:len(second)], second, "First string doesn't start with the second.") def get_mailbox_content(self): raise NotImplementedError def flush_mailbox(self): raise NotImplementedError def get_the_message(self): mailbox = self.get_mailbox_content() self.assertEqual(len(mailbox), 1, "Expected exactly one message, got %d.\n%r" % (len(mailbox), [ m.as_string() for m in mailbox])) return mailbox[0] def test_send(self): email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]']) num_sent = mail.get_connection().send_messages([email]) self.assertEqual(num_sent, 1) message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "[email protected]") self.assertEqual(message.get_all("to"), ["[email protected]"]) def test_send_many(self): email1 = EmailMessage('Subject', 'Content1', '[email protected]', ['[email protected]']) email2 = EmailMessage('Subject', 'Content2', '[email protected]', ['[email protected]']) num_sent = mail.get_connection().send_messages([email1, email2]) self.assertEqual(num_sent, 2) messages = self.get_mailbox_content() self.assertEqual(len(messages), 2) self.assertEqual(messages[0].get_payload(), "Content1") self.assertEqual(messages[1].get_payload(), "Content2") def test_send_verbose_name(self): email = EmailMessage("Subject", "Content", '"Firstname Sürname" <[email protected]>', ["[email protected]"]) email.send() message = self.get_the_message() self.assertEqual(message["subject"], "Subject") self.assertEqual(message.get_payload(), "Content") self.assertEqual(message["from"], "=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>") @with_django_settings(MANAGERS=[('nobody', '[email protected]')]) def test_html_mail_managers(self): """Test html_message argument to mail_managers""" mail_managers('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @with_django_settings(ADMINS=[('nobody', '[email protected]')]) def test_html_mail_admins(self): """Test html_message argument to mail_admins """ mail_admins('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), 'Content') self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain') self.assertEqual(message.get_payload(1).get_payload(), 'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') @with_django_settings(ADMINS=[('nobody', '[email protected]')], MANAGERS=[('nobody', '[email protected]')]) def test_manager_and_admin_mail_prefix(self): """ String prefix + lazy translated subject = bad output Regression for #13494 """ mail_managers(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.flush_mailbox() mail_admins(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') @with_django_settings(ADMINS=(), MANAGERS=()) def test_empty_admins(self): """ Test that mail_admins/mail_managers doesn't connect to the mail server if there are no recipients (#9383) """ mail_admins('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) mail_managers('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) def test_message_cc_header(self): """ Regression test for #7722 """ email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], cc=['[email protected]']) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertStartsWith(message.as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nCc: [email protected]\nDate: ') def test_idn_send(self): """ Regression test for #14301 """ self.assertTrue(send_mail('Subject', 'Content', 'from@öäü.com', [u'to@öäü.com'])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') self.flush_mailbox() m = EmailMessage('Subject', 'Content', 'from@öäü.com', [u'to@öäü.com'], cc=[u'cc@öäü.com']) m.send() message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') self.assertEqual(message.get('cc'), '[email protected]') def test_recipient_without_domain(self): """ Regression test for #15042 """ self.assertTrue(send_mail("Subject", "Content", "tester", ["django"])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), "tester") self.assertEqual(message.get('to'), "django") class LocmemBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.locmem.EmailBackend' def get_mailbox_content(self): return [m.message() for m in mail.outbox] def flush_mailbox(self): mail.outbox = [] def tearDown(self): super(LocmemBackendTests, self).tearDown() mail.outbox = [] def test_locmem_shared_messages(self): """ Make sure that the locmen backend populates the outbox. """ connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox), 2) class FileBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.filebased.EmailBackend' def setUp(self): super(FileBackendTests, self).setUp() self.tmp_dir = tempfile.mkdtemp() self.__settings_state = alter_django_settings(EMAIL_FILE_PATH=self.tmp_dir) def tearDown(self): restore_django_settings(self.__settings_state) shutil.rmtree(self.tmp_dir) super(FileBackendTests, self).tearDown() def flush_mailbox(self): for filename in os.listdir(self.tmp_dir): os.unlink(os.path.join(self.tmp_dir, filename)) def get_mailbox_content(self): messages = [] for filename in os.listdir(self.tmp_dir): session = open(os.path.join(self.tmp_dir, filename)).read().split('\n' + ('-' * 79) + '\n') messages.extend(email.message_from_string(m) for m in session if m) return messages def test_file_sessions(self): """Make sure opening a connection creates a new file""" msg = EmailMessage('Subject', 'Content', '[email protected]', ['[email protected]'], headers={'From': '[email protected]'}) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) message = email.message_from_file(open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0]))) self.assertEqual(message.get_content_type(), 'text/plain') self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), '[email protected]') self.assertEqual(message.get('to'), '[email protected]') connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) class ConsoleBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.console.EmailBackend' def setUp(self): super(ConsoleBackendTests, self).setUp() self.__stdout = sys.stdout self.stream = sys.stdout = StringIO() def tearDown(self): del self.stream sys.stdout = self.__stdout del self.__stdout super(ConsoleBackendTests, self).tearDown() def flush_mailbox(self): self.stream = sys.stdout = StringIO() def get_mailbox_content(self): messages = self.stream.getvalue().split('\n' + ('-' * 79) + '\n') return [email.message_from_string(m) for m in messages if m] def test_console_stream_kwarg(self): """ Test that the console backend can be pointed at an arbitrary stream. """ s = StringIO() connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) send_mail('Subject', 'Content', '[email protected]', ['[email protected]'], connection=connection) self.assertTrue(s.getvalue().startswith('Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nDate: ')) class FakeSMTPServer(smtpd.SMTPServer, threading.Thread): """ Asyncore SMTP server wrapped into a thread. Based on DummyFTPServer from: http://svn.python.org/view/python/branches/py3k/Lib/test/test_ftplib.py?revision=86061&view=markup """ def __init__(self, *args, **kwargs): threading.Thread.__init__(self) smtpd.SMTPServer.__init__(self, *args, **kwargs) self._sink = [] self.active = False self.active_lock = threading.Lock() self.sink_lock = threading.Lock() def process_message(self, peer, mailfrom, rcpttos, data): m = email.message_from_string(data) maddr = email.Utils.parseaddr(m.get('from'))[1] if mailfrom != maddr: return "553 '%s' != '%s'" % (mailfrom, maddr) self.sink_lock.acquire() self._sink.append(m) self.sink_lock.release() def get_sink(self): self.sink_lock.acquire() try: return self._sink[:] finally: self.sink_lock.release() def flush_sink(self): self.sink_lock.acquire() self._sink[:] = [] self.sink_lock.release() def start(self): assert not self.active self.__flag = threading.Event() threading.Thread.start(self) self.__flag.wait() def run(self): self.active = True self.__flag.set() while self.active and asyncore.socket_map: self.active_lock.acquire() asyncore.loop(timeout=0.1, count=1) self.active_lock.release() asyncore.close_all() def stop(self): assert self.active self.active = False self.join() class SMTPBackendTests(BaseEmailBackendTests, TestCase): email_backend = 'django.core.mail.backends.smtp.EmailBackend' @classmethod def setUpClass(cls): cls.server = FakeSMTPServer(('127.0.0.1', 0), None) cls.settings = alter_django_settings( EMAIL_HOST="127.0.0.1", EMAIL_PORT=cls.server.socket.getsockname()[1]) cls.server.start() @classmethod def tearDownClass(cls): cls.server.stop() def setUp(self): super(SMTPBackendTests, self).setUp() self.server.flush_sink() def tearDown(self): self.server.flush_sink() super(SMTPBackendTests, self).tearDown() def flush_mailbox(self): self.server.flush_sink() def get_mailbox_content(self): return self.server.get_sink()
29,439
Python
.py
538
46.141264
291
0.657086
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,780
custombackend.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/mail/custombackend.py
"""A custom backend for testing.""" from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): super(EmailBackend, self).__init__(*args, **kwargs) self.test_outbox = [] def send_messages(self, email_messages): # Messages are stored in a instance variable for testing. self.test_outbox.extend(email_messages) return len(email_messages)
464
Python
.py
10
40.1
65
0.694878
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,781
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/inspectdb/models.py
from django.db import models class People(models.Model): name = models.CharField(max_length=255) class Message(models.Model): from_field = models.ForeignKey(People, db_column='from_id')
197
Python
.py
5
36.2
63
0.767196
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,782
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/inspectdb/tests.py
from StringIO import StringIO from django.core.management import call_command from django.test import TestCase, skipUnlessDBFeature class InspectDBTestCase(TestCase): @skipUnlessDBFeature('can_introspect_foreign_keys') def test_attribute_name_not_python_keyword(self): out = StringIO() call_command('inspectdb', stdout=out) error_message = "inspectdb generated an attribute name which is a python keyword" self.assertNotIn("from = models.ForeignKey(InspectdbPeople)", out.getvalue(), msg=error_message) self.assertIn("from_field = models.ForeignKey(InspectdbPeople)", out.getvalue()) out.close()
656
Python
.py
12
48.666667
104
0.75
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,783
test_saferef.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/dispatch/tests/test_saferef.py
from django.dispatch.saferef import * from django.utils import unittest class Test1(object): def x(self): pass def test2(obj): pass class Test2(object): def __call__(self, obj): pass class Tester(unittest.TestCase): def setUp(self): ts = [] ss = [] for x in xrange(5000): t = Test1() ts.append(t) s = safeRef(t.x, self._closure) ss.append(s) ts.append(test2) ss.append(safeRef(test2, self._closure)) for x in xrange(30): t = Test2() ts.append(t) s = safeRef(t, self._closure) ss.append(s) self.ts = ts self.ss = ss self.closureCount = 0 def tearDown(self): del self.ts del self.ss def testIn(self): """Test the "in" operator for safe references (cmp)""" for t in self.ts[:50]: self.assertTrue(safeRef(t.x) in self.ss) def testValid(self): """Test that the references are valid (return instance methods)""" for s in self.ss: self.assertTrue(s()) def testShortCircuit (self): """Test that creation short-circuits to reuse existing references""" sd = {} for s in self.ss: sd[s] = 1 for t in self.ts: if hasattr(t, 'x'): self.assertTrue(sd.has_key(safeRef(t.x))) self.assertTrue(safeRef(t.x) in sd) else: self.assertTrue(sd.has_key(safeRef(t))) self.assertTrue(safeRef(t) in sd) def testRepresentation (self): """Test that the reference object's representation works XXX Doesn't currently check the results, just that no error is raised """ repr(self.ss[-1]) def _closure(self, ref): """Dumb utility mechanism to increment deletion counter""" self.closureCount +=1 def getSuite(): return unittest.makeSuite(Tester,'test') if __name__ == "__main__": unittest.main()
2,107
Python
.py
65
23.015385
76
0.560743
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,784
__init__.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/dispatch/tests/__init__.py
""" Unit-tests for the dispatch project """ from test_saferef import * from test_dispatcher import *
102
Python
.py
5
19.2
35
0.78125
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,785
test_dispatcher.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/dispatch/tests/test_dispatcher.py
import gc import sys from django.dispatch import Signal from django.utils import unittest import django.utils.copycompat as copy if sys.platform.startswith('java'): def garbage_collect(): """Run the garbage collector and wait a bit to let it do his work""" import time gc.collect() time.sleep(0.1) else: def garbage_collect(): gc.collect() def receiver_1_arg(val, **kwargs): return val class Callable(object): def __call__(self, val, **kwargs): return val def a(self, val, **kwargs): return val a_signal = Signal(providing_args=["val"]) class DispatcherTests(unittest.TestCase): """Test suite for dispatcher (barely started)""" def _testIsClean(self, signal): """Assert that everything has been cleaned up automatically""" self.assertEqual(signal.receivers, []) # force cleanup just in case signal.receivers = [] def testExact(self): a_signal.connect(receiver_1_arg, sender=self) expected = [(receiver_1_arg,"test")] result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) a_signal.disconnect(receiver_1_arg, sender=self) self._testIsClean(a_signal) def testIgnoredSender(self): a_signal.connect(receiver_1_arg) expected = [(receiver_1_arg,"test")] result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) a_signal.disconnect(receiver_1_arg) self._testIsClean(a_signal) def testGarbageCollected(self): a = Callable() a_signal.connect(a.a, sender=self) expected = [] del a garbage_collect() result = a_signal.send(sender=self, val="test") self.assertEqual(result, expected) self._testIsClean(a_signal) def testMultipleRegistration(self): a = Callable() a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) a_signal.connect(a) result = a_signal.send(sender=self, val="test") self.assertEqual(len(result), 1) self.assertEqual(len(a_signal.receivers), 1) del a del result garbage_collect() self._testIsClean(a_signal) def testUidRegistration(self): def uid_based_receiver_1(**kwargs): pass def uid_based_receiver_2(**kwargs): pass a_signal.connect(uid_based_receiver_1, dispatch_uid = "uid") a_signal.connect(uid_based_receiver_2, dispatch_uid = "uid") self.assertEqual(len(a_signal.receivers), 1) a_signal.disconnect(dispatch_uid = "uid") self._testIsClean(a_signal) def testRobust(self): """Test the sendRobust function""" def fails(val, **kwargs): raise ValueError('this') a_signal.connect(fails) result = a_signal.send_robust(sender=self, val="test") err = result[0][1] self.assertTrue(isinstance(err, ValueError)) self.assertEqual(err.args, ('this',)) a_signal.disconnect(fails) self._testIsClean(a_signal) def testDisconnection(self): receiver_1 = Callable() receiver_2 = Callable() receiver_3 = Callable() a_signal.connect(receiver_1) a_signal.connect(receiver_2) a_signal.connect(receiver_3) a_signal.disconnect(receiver_1) del receiver_2 garbage_collect() a_signal.disconnect(receiver_3) self._testIsClean(a_signal) def getSuite(): return unittest.makeSuite(DispatcherTests,'test') if __name__ == "__main__": unittest.main()
3,726
Python
.py
104
28.134615
76
0.633259
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,786
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/builtin_server/tests.py
from StringIO import StringIO from django.core.servers.basehttp import ServerHandler from django.utils.unittest import TestCase # # Tests for #9659: wsgi.file_wrapper in the builtin server. # We need to mock a couple of of handlers and keep track of what # gets called when using a couple kinds of WSGI apps. # class DummyHandler(object): def log_request(*args, **kwargs): pass class FileWrapperHandler(ServerHandler): def __init__(self, *args, **kwargs): ServerHandler.__init__(self, *args, **kwargs) self.request_handler = DummyHandler() self._used_sendfile = False def sendfile(self): self._used_sendfile = True return True def wsgi_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!'] def wsgi_app_file_wrapper(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return environ['wsgi.file_wrapper'](StringIO('foo')) class WSGIFileWrapperTests(TestCase): """ Test that the wsgi.file_wrapper works for the builting server. """ def test_file_wrapper_uses_sendfile(self): env = {'SERVER_PROTOCOL': 'HTTP/1.0'} err = StringIO() handler = FileWrapperHandler(None, StringIO(), err, env) handler.run(wsgi_app_file_wrapper) self.assertTrue(handler._used_sendfile) def test_file_wrapper_no_sendfile(self): env = {'SERVER_PROTOCOL': 'HTTP/1.0'} err = StringIO() handler = FileWrapperHandler(None, StringIO(), err, env) handler.run(wsgi_app) self.assertFalse(handler._used_sendfile) self.assertEqual(handler.stdout.getvalue().splitlines()[-1],'Hello World!')
1,738
Python
.py
42
35.761905
83
0.685053
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,787
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_fields/models.py
import os import tempfile # Try to import PIL in either of the two ways it can end up installed. # Checking for the existence of Image is enough for CPython, but for PyPy, # you need to check for the underlying modules. try: from PIL import Image, _imaging except ImportError: try: import Image, _imaging except ImportError: Image = None from django.core.files.storage import FileSystemStorage from django.db import models from django.db.models.fields.files import ImageFieldFile, ImageField class Foo(models.Model): a = models.CharField(max_length=10) d = models.DecimalField(max_digits=5, decimal_places=3) def get_foo(): return Foo.objects.get(id=1) class Bar(models.Model): b = models.CharField(max_length=10) a = models.ForeignKey(Foo, default=get_foo) class Whiz(models.Model): CHOICES = ( ('Group 1', ( (1,'First'), (2,'Second'), ) ), ('Group 2', ( (3,'Third'), (4,'Fourth'), ) ), (0,'Other'), ) c = models.IntegerField(choices=CHOICES, null=True) class BigD(models.Model): d = models.DecimalField(max_digits=38, decimal_places=30) class BigS(models.Model): s = models.SlugField(max_length=255) class BigInt(models.Model): value = models.BigIntegerField() null_value = models.BigIntegerField(null = True, blank = True) class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() class NullBooleanModel(models.Model): nbfield = models.NullBooleanField() class BooleanModel(models.Model): bfield = models.BooleanField() string = models.CharField(max_length=10, default='abc') ############################################################################### # FileField class Document(models.Model): myfile = models.FileField(upload_to='unused') ############################################################################### # ImageField # If PIL available, do these tests. if Image: class TestImageFieldFile(ImageFieldFile): """ Custom Field File class that records whether or not the underlying file was opened. """ def __init__(self, *args, **kwargs): self.was_opened = False super(TestImageFieldFile, self).__init__(*args,**kwargs) def open(self): self.was_opened = True super(TestImageFieldFile, self).open() class TestImageField(ImageField): attr_class = TestImageFieldFile # Set up a temp directory for file storage. temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) temp_upload_to_dir = os.path.join(temp_storage.location, 'tests') class Person(models.Model): """ Model that defines an ImageField with no dimension fields. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests') class PersonWithHeight(models.Model): """ Model that defines an ImageField with only one dimension field. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height') mugshot_height = models.PositiveSmallIntegerField() class PersonWithHeightAndWidth(models.Model): """ Model that defines height and width fields after the ImageField. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() class PersonDimensionsFirst(models.Model): """ Model that defines height and width fields before the ImageField. """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') class PersonTwoImages(models.Model): """ Model that: * Defines two ImageFields * Defines the height/width fields before the ImageFields * Has a nullalble ImageField """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField(storage=temp_storage, upload_to='tests', height_field='mugshot_height', width_field='mugshot_width') headshot_height = models.PositiveSmallIntegerField( blank=True, null=True) headshot_width = models.PositiveSmallIntegerField( blank=True, null=True) headshot = TestImageField(blank=True, null=True, storage=temp_storage, upload_to='tests', height_field='headshot_height', width_field='headshot_width') ###############################################################################
5,575
Python
.py
134
32.61194
79
0.608495
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,788
imagefield.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_fields/imagefield.py
import os import shutil from django.core.files import File from django.core.files.base import ContentFile from django.core.files.images import ImageFile from django.test import TestCase from models import Image, Person, PersonWithHeight, PersonWithHeightAndWidth, \ PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile # If PIL available, do these tests. if Image: from models import temp_storage_dir class ImageFieldTestMixin(object): """ Mixin class to provide common functionality to ImageField test classes. """ # Person model to use for tests. PersonModel = PersonWithHeightAndWidth # File class to use for file instances. File = ImageFile def setUp(self): """ Creates a pristine temp directory (or deletes and recreates if it already exists) that the model uses as its storage directory. Sets up two ImageFile instances for use in tests. """ if os.path.exists(temp_storage_dir): shutil.rmtree(temp_storage_dir) os.mkdir(temp_storage_dir) file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png") self.file1 = self.File(open(file_path1, 'rb')) file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png") self.file2 = self.File(open(file_path2, 'rb')) def tearDown(self): """ Removes temp directory and all its contents. """ shutil.rmtree(temp_storage_dir) def check_dimensions(self, instance, width, height, field_name='mugshot'): """ Asserts that the given width and height values match both the field's height and width attributes and the height and width fields (if defined) the image field is caching to. Note, this method will check for dimension fields named by adding "_width" or "_height" to the name of the ImageField. So, the models used in these tests must have their fields named accordingly. By default, we check the field named "mugshot", but this can be specified by passing the field_name parameter. """ field = getattr(instance, field_name) # Check height/width attributes of field. if width is None and height is None: self.assertRaises(ValueError, getattr, field, 'width') self.assertRaises(ValueError, getattr, field, 'height') else: self.assertEqual(field.width, width) self.assertEqual(field.height, height) # Check height/width fields of model, if defined. width_field_name = field_name + '_width' if hasattr(instance, width_field_name): self.assertEqual(getattr(instance, width_field_name), width) height_field_name = field_name + '_height' if hasattr(instance, height_field_name): self.assertEqual(getattr(instance, height_field_name), height) class ImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests for ImageField that don't need to be run with each of the different test model classes. """ def test_equal_notequal_hash(self): """ Bug #9786: Ensure '==' and '!=' work correctly. Bug #9508: make sure hash() works as expected (equal items must hash to the same value). """ # Create two Persons with different mugshots. p1 = self.PersonModel(name="Joe") p1.mugshot.save("mug", self.file1) p2 = self.PersonModel(name="Bob") p2.mugshot.save("mug", self.file2) self.assertEqual(p1.mugshot == p2.mugshot, False) self.assertEqual(p1.mugshot != p2.mugshot, True) # Test again with an instance fetched from the db. p1_db = self.PersonModel.objects.get(name="Joe") self.assertEqual(p1_db.mugshot == p2.mugshot, False) self.assertEqual(p1_db.mugshot != p2.mugshot, True) # Instance from db should match the local instance. self.assertEqual(p1_db.mugshot == p1.mugshot, True) self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot)) self.assertEqual(p1_db.mugshot != p1.mugshot, False) def test_instantiate_missing(self): """ If the underlying file is unavailable, still create instantiate the object without error. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) p = self.PersonModel.objects.get(name="Joan") path = p.mugshot.path shutil.move(path, path + '.moved') p2 = self.PersonModel.objects.get(name="Joan") def test_delete_when_missing(self): """ Bug #8175: correctly delete an object where the file no longer exists on the file system. """ p = self.PersonModel(name="Fred") p.mugshot.save("shot", self.file1) os.remove(p.mugshot.path) p.delete() def test_size_method(self): """ Bug #8534: FileField.size should not leave the file open. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) # Get a "clean" model instance p = self.PersonModel.objects.get(name="Joan") # It won't have an opened file. self.assertEqual(p.mugshot.closed, True) # After asking for the size, the file should still be closed. _ = p.mugshot.size self.assertEqual(p.mugshot.closed, True) def test_pickle(self): """ Tests that ImageField can be pickled, unpickled, and that the image of the unpickled version is the same as the original. """ import pickle p = Person(name="Joe") p.mugshot.save("mug", self.file1) dump = pickle.dumps(p) p2 = Person(name="Bob") p2.mugshot = self.file1 loaded_p = pickle.loads(dump) self.assertEqual(p.mugshot, loaded_p.mugshot) class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase): """ Tests behavior of an ImageField and its dimensions fields. """ def test_constructor(self): """ Tests assigning an image field through the model's constructor. """ p = self.PersonModel(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) p.save() self.check_dimensions(p, 4, 8) def test_image_after_constructor(self): """ Tests behavior when image is not passed in constructor. """ p = self.PersonModel(name='Joe') # TestImageField value will default to being an instance of its # attr_class, a TestImageFieldFile, with name == None, which will # cause it to evaluate as False. self.assertEqual(isinstance(p.mugshot, TestImageFieldFile), True) self.assertEqual(bool(p.mugshot), False) # Test setting a fresh created model instance. p = self.PersonModel(name='Joe') p.mugshot = self.file1 self.check_dimensions(p, 4, 8) def test_create(self): """ Tests assigning an image in Manager.create(). """ p = self.PersonModel.objects.create(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) def test_default_value(self): """ Tests that the default value for an ImageField is an instance of the field's attr_class (TestImageFieldFile in this case) with no name (name set to None). """ p = self.PersonModel() self.assertEqual(isinstance(p.mugshot, TestImageFieldFile), True) self.assertEqual(bool(p.mugshot), False) def test_assignment_to_None(self): """ Tests that assigning ImageField to None clears dimensions. """ p = self.PersonModel(name='Joe', mugshot=self.file1) self.check_dimensions(p, 4, 8) # If image assigned to None, dimension fields should be cleared. p.mugshot = None self.check_dimensions(p, None, None) p.mugshot = self.file2 self.check_dimensions(p, 8, 4) def test_field_save_and_delete_methods(self): """ Tests assignment using the field's save method and deletion using the field's delete method. """ p = self.PersonModel(name='Joe') p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # A new file should update dimensions. p.mugshot.save("mug", self.file2) self.check_dimensions(p, 8, 4) # Field and dimensions should be cleared after a delete. p.mugshot.delete(save=False) self.assertEqual(p.mugshot, None) self.check_dimensions(p, None, None) def test_dimensions(self): """ Checks that dimensions are updated correctly in various situations. """ p = self.PersonModel(name='Joe') # Dimensions should get set if file is saved. p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name='Joe') # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertEqual(p.mugshot.was_opened, False) self.check_dimensions(p, 4, 8) # After checking dimensions on the image field, the file will have # opened. self.assertEqual(p.mugshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False self.check_dimensions(p, 4, 8) self.assertEqual(p.mugshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 self.check_dimensions(p, 8, 4) # Dimensions were recalculated, and hence file should have opened. self.assertEqual(p.mugshot.was_opened, True) class ImageFieldNoDimensionsTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with no dimension fields. """ PersonModel = Person class ImageFieldOneDimensionTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with one dimensions field. """ PersonModel = PersonWithHeight class ImageFieldDimensionsFirstTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField where the dimensions fields are defined before the ImageField. """ PersonModel = PersonDimensionsFirst class ImageFieldUsingFileTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField when assigning it a File instance rather than an ImageFile instance. """ PersonModel = PersonDimensionsFirst File = File class TwoImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests a model with two ImageFields. """ PersonModel = PersonTwoImages def test_constructor(self): p = self.PersonModel(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') p.save() self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') def test_create(self): p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8) self.check_dimensions(p, 8, 4, 'headshot') def test_assignment(self): p = self.PersonModel() self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.mugshot = self.file1 self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.headshot = self.file2 self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # Clear the ImageFields one at a time. p.mugshot = None self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') p.headshot = None self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') def test_field_save_and_delete_methods(self): p = self.PersonModel(name='Joe') p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # We can use save=True when deleting the image field with null=True # dimension fields and the other field has an image. p.headshot.delete(save=True) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, None, None, 'headshot') p.mugshot.delete(save=False) self.check_dimensions(p, None, None, 'mugshot') self.check_dimensions(p, None, None, 'headshot') def test_dimensions(self): """ Checks that dimensions are updated correctly in various situations. """ p = self.PersonModel(name='Joe') # Dimensions should get set for the saved file. p.mugshot.save("mug", self.file1) p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name='Joe') # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertEqual(p.mugshot.was_opened, False) self.assertEqual(p.headshot.was_opened, False) self.check_dimensions(p, 4, 8,'mugshot') self.check_dimensions(p, 8, 4, 'headshot') # After checking dimensions on the image fields, the files will # have been opened. self.assertEqual(p.mugshot.was_opened, True) self.assertEqual(p.headshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False p.headshot.was_opened = False self.check_dimensions(p, 4, 8,'mugshot') self.check_dimensions(p, 8, 4, 'headshot') self.assertEqual(p.mugshot.was_opened, False) self.assertEqual(p.headshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 p.headshot = self.file1 self.check_dimensions(p, 8, 4, 'mugshot') self.check_dimensions(p, 4, 8, 'headshot') # Dimensions were recalculated, and hence file should have opened. self.assertEqual(p.mugshot.was_opened, True) self.assertEqual(p.headshot.was_opened, True)
16,535
Python
.py
346
35.531792
79
0.59485
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,789
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/model_fields/tests.py
import datetime from decimal import Decimal from django import test from django import forms from django.core.exceptions import ValidationError from django.db import models from django.db.models.fields.files import FieldFile from django.utils import unittest from models import Foo, Bar, Whiz, BigD, BigS, Image, BigInt, Post, NullBooleanModel, BooleanModel, Document # If PIL available, do these tests. if Image: from imagefield import \ ImageFieldTests, \ ImageFieldTwoDimensionsTests, \ ImageFieldNoDimensionsTests, \ ImageFieldOneDimensionTests, \ ImageFieldDimensionsFirstTests, \ ImageFieldUsingFileTests, \ TwoImageFieldTests class BasicFieldTests(test.TestCase): def test_show_hidden_initial(self): """ Regression test for #12913. Make sure fields with choices respect show_hidden_initial as a kwarg to models.Field.formfield() """ choices = [(0, 0), (1, 1)] model_field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial) def test_nullbooleanfield_blank(self): """ Regression test for #13071: NullBooleanField should not throw a validation error when given a value of None. """ nullboolean = NullBooleanModel(nbfield=None) try: nullboolean.full_clean() except ValidationError, e: self.fail("NullBooleanField failed validation with value of None: %s" % e.messages) class DecimalFieldTests(test.TestCase): def test_to_python(self): f = models.DecimalField(max_digits=4, decimal_places=2) self.assertEqual(f.to_python(3), Decimal("3")) self.assertEqual(f.to_python("3.14"), Decimal("3.14")) self.assertRaises(ValidationError, f.to_python, "abc") def test_default(self): f = models.DecimalField(default=Decimal("0.00")) self.assertEqual(f.get_default(), Decimal("0.00")) def test_format(self): f = models.DecimalField(max_digits=5, decimal_places=1) self.assertEqual(f._format(f.to_python(2)), u'2.0') self.assertEqual(f._format(f.to_python('2.6')), u'2.6') self.assertEqual(f._format(None), None) def test_get_db_prep_lookup(self): from django.db import connection f = models.DecimalField(max_digits=5, decimal_places=1) self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None]) def test_filter_with_strings(self): """ We should be able to filter decimal fields using strings (#8023) """ Foo.objects.create(id=1, a='abc', d=Decimal("12.34")) self.assertEqual(list(Foo.objects.filter(d=u'1.23')), []) def test_save_without_float_conversion(self): """ Ensure decimals don't go through a corrupting float conversion during save (#5079). """ bd = BigD(d="12.9") bd.save() bd = BigD.objects.get(pk=bd.pk) self.assertEqual(bd.d, Decimal("12.9")) def test_lookup_really_big_value(self): """ Ensure that really big values can be used in a filter statement, even with older Python versions. """ # This should not crash. That counts as a win for our purposes. Foo.objects.filter(d__gte=100000000000) class ForeignKeyTests(test.TestCase): def test_callable_default(self): """Test the use of a lazy callable for ForeignKey.default""" a = Foo.objects.create(id=1, a='abc', d=Decimal("12.34")) b = Bar.objects.create(b="bcd") self.assertEqual(b.a, a) class DateTimeFieldTests(unittest.TestCase): def test_datetimefield_to_python_usecs(self): """DateTimeField.to_python should support usecs""" f = models.DateTimeField() self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'), datetime.datetime(2001, 1, 2, 3, 4, 5, 6)) self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'), datetime.datetime(2001, 1, 2, 3, 4, 5, 999999)) def test_timefield_to_python_usecs(self): """TimeField.to_python should support usecs""" f = models.TimeField() self.assertEqual(f.to_python('01:02:03.000004'), datetime.time(1, 2, 3, 4)) self.assertEqual(f.to_python('01:02:03.999999'), datetime.time(1, 2, 3, 999999)) class BooleanFieldTests(unittest.TestCase): def _test_get_db_prep_lookup(self, f): from django.db import connection self.assertEqual(f.get_db_prep_lookup('exact', True, connection=connection), [True]) self.assertEqual(f.get_db_prep_lookup('exact', '1', connection=connection), [True]) self.assertEqual(f.get_db_prep_lookup('exact', 1, connection=connection), [True]) self.assertEqual(f.get_db_prep_lookup('exact', False, connection=connection), [False]) self.assertEqual(f.get_db_prep_lookup('exact', '0', connection=connection), [False]) self.assertEqual(f.get_db_prep_lookup('exact', 0, connection=connection), [False]) self.assertEqual(f.get_db_prep_lookup('exact', None, connection=connection), [None]) def _test_to_python(self, f): self.assertTrue(f.to_python(1) is True) self.assertTrue(f.to_python(0) is False) def test_booleanfield_get_db_prep_lookup(self): self._test_get_db_prep_lookup(models.BooleanField()) def test_nullbooleanfield_get_db_prep_lookup(self): self._test_get_db_prep_lookup(models.NullBooleanField()) def test_booleanfield_to_python(self): self._test_to_python(models.BooleanField()) def test_nullbooleanfield_to_python(self): self._test_to_python(models.NullBooleanField()) def test_booleanfield_choices_blank(self): """ Test that BooleanField with choices and defaults doesn't generate a formfield with the blank option (#9640, #10549). """ choices = [(1, u'Si'), (2, 'No')] f = models.BooleanField(choices=choices, default=1, null=True) self.assertEqual(f.formfield().choices, [('', '---------')] + choices) f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices) def test_return_type(self): b = BooleanModel() b.bfield = True b.save() b2 = BooleanModel.objects.get(pk=b.pk) self.assertTrue(isinstance(b2.bfield, bool)) self.assertEqual(b2.bfield, True) b3 = BooleanModel() b3.bfield = False b3.save() b4 = BooleanModel.objects.get(pk=b3.pk) self.assertTrue(isinstance(b4.bfield, bool)) self.assertEqual(b4.bfield, False) b = NullBooleanModel() b.nbfield = True b.save() b2 = NullBooleanModel.objects.get(pk=b.pk) self.assertTrue(isinstance(b2.nbfield, bool)) self.assertEqual(b2.nbfield, True) b3 = NullBooleanModel() b3.nbfield = False b3.save() b4 = NullBooleanModel.objects.get(pk=b3.pk) self.assertTrue(isinstance(b4.nbfield, bool)) self.assertEqual(b4.nbfield, False) # http://code.djangoproject.com/ticket/13293 # Verify that when an extra clause exists, the boolean # conversions are applied with an offset b5 = BooleanModel.objects.all().extra( select={'string_length': 'LENGTH(string)'})[0] self.assertFalse(isinstance(b5.pk, bool)) class ChoicesTests(test.TestCase): def test_choices_and_field_display(self): """ Check that get_choices and get_flatchoices interact with get_FIELD_display to return the expected values (#7913). """ self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value class SlugFieldTests(test.TestCase): def test_slugfield_max_length(self): """ Make sure SlugField honors max_length (#9706) """ bs = BigS.objects.create(s = 'slug'*50) bs = BigS.objects.get(pk=bs.pk) self.assertEqual(bs.s, 'slug'*50) class ValidationTest(test.TestCase): def test_charfield_raises_error_on_empty_string(self): f = models.CharField() self.assertRaises(ValidationError, f.clean, "", None) def test_charfield_cleans_empty_string_when_blank_true(self): f = models.CharField(blank=True) self.assertEqual('', f.clean('', None)) def test_integerfield_cleans_valid_string(self): f = models.IntegerField() self.assertEqual(2, f.clean('2', None)) def test_integerfield_raises_error_on_invalid_intput(self): f = models.IntegerField() self.assertRaises(ValidationError, f.clean, "a", None) def test_charfield_with_choices_cleans_valid_choice(self): f = models.CharField(max_length=1, choices=[('a','A'), ('b','B')]) self.assertEqual('a', f.clean('a', None)) def test_charfield_with_choices_raises_error_on_invalid_choice(self): f = models.CharField(choices=[('a','A'), ('b','B')]) self.assertRaises(ValidationError, f.clean, "not a", None) def test_choices_validation_supports_named_groups(self): f = models.IntegerField(choices=(('group',((10,'A'),(20,'B'))),(30,'C'))) self.assertEqual(10, f.clean(10, None)) def test_nullable_integerfield_raises_error_with_blank_false(self): f = models.IntegerField(null=True, blank=False) self.assertRaises(ValidationError, f.clean, None, None) def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self): f = models.IntegerField(null=True, blank=True) self.assertEqual(None, f.clean(None, None)) def test_integerfield_raises_error_on_empty_input(self): f = models.IntegerField(null=False) self.assertRaises(ValidationError, f.clean, None, None) self.assertRaises(ValidationError, f.clean, '', None) def test_charfield_raises_error_on_empty_input(self): f = models.CharField(null=False) self.assertRaises(ValidationError, f.clean, None, None) def test_datefield_cleans_date(self): f = models.DateField() self.assertEqual(datetime.date(2008, 10, 10), f.clean('2008-10-10', None)) def test_boolean_field_doesnt_accept_empty_input(self): f = models.BooleanField() self.assertRaises(ValidationError, f.clean, None, None) class BigIntegerFieldTests(test.TestCase): def test_limits(self): # Ensure that values that are right at the limits can be saved # and then retrieved without corruption. maxval = 9223372036854775807 minval = -maxval - 1 BigInt.objects.create(value=maxval) qs = BigInt.objects.filter(value__gte=maxval) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, maxval) BigInt.objects.create(value=minval) qs = BigInt.objects.filter(value__lte=minval) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, minval) def test_types(self): b = BigInt(value = 0) self.assertTrue(isinstance(b.value, (int, long))) b.save() self.assertTrue(isinstance(b.value, (int, long))) b = BigInt.objects.all()[0] self.assertTrue(isinstance(b.value, (int, long))) def test_coercing(self): BigInt.objects.create(value ='10') b = BigInt.objects.get(value = '10') self.assertEqual(b.value, 10) class TypeCoercionTests(test.TestCase): """ Test that database lookups can accept the wrong types and convert them with no error: especially on Postgres 8.3+ which does not do automatic casting at the DB level. See #10015. """ def test_lookup_integer_in_charfield(self): self.assertEqual(Post.objects.filter(title=9).count(), 0) def test_lookup_integer_in_textfield(self): self.assertEqual(Post.objects.filter(body=24).count(), 0) class FileFieldTests(unittest.TestCase): def test_clearable(self): """ Test that FileField.save_form_data will clear its instance attribute value if passed False. """ d = Document(myfile='something.txt') self.assertEqual(d.myfile, 'something.txt') field = d._meta.get_field('myfile') field.save_form_data(d, False) self.assertEqual(d.myfile, '') def test_unchanged(self): """ Test that FileField.save_form_data considers None to mean "no change" rather than "clear". """ d = Document(myfile='something.txt') self.assertEqual(d.myfile, 'something.txt') field = d._meta.get_field('myfile') field.save_form_data(d, None) self.assertEqual(d.myfile, 'something.txt') def test_changed(self): """ Test that FileField.save_form_data, if passed a truthy value, updates its instance attribute. """ d = Document(myfile='something.txt') self.assertEqual(d.myfile, 'something.txt') field = d._meta.get_field('myfile') field.save_form_data(d, 'else.txt') self.assertEqual(d.myfile, 'else.txt')
13,789
Python
.py
290
39.251724
108
0.651983
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,790
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/fixtures_regress/models.py
from django.db import models, DEFAULT_DB_ALIAS, connection from django.contrib.auth.models import User from django.conf import settings class Animal(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatField() # use a non-default name for the default manager specimens = models.Manager() def __unicode__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=150) class Meta: # For testing when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" class Stuff(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return unicode(self.name) + u' is owned by ' + unicode(self.owner) class Absolute(models.Model): name = models.CharField(max_length=40) load_count = 0 def __init__(self, *args, **kwargs): super(Absolute, self).__init__(*args, **kwargs) Absolute.load_count += 1 class Parent(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ('id',) class Child(Parent): data = models.CharField(max_length=10) # Models to regression test #7572 class Channel(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta: ordering = ('id',) # Models to regression test #11428 class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward references in FKs and M2Ms with natural keys class TestManager(models.Manager): def get_by_natural_key(self, key): return self.get(name=key) class Store(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name def natural_key(self): return (self.name,) class Person(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name # Person doesn't actually have a dependency on store, but we need to define # one to test the behaviour of the dependency resolution algorithm. def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.store'] class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person) stores = models.ManyToManyField(Store) class Meta: ordering = ('name',) def __unicode__(self): return u'%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) ) class NKManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) class NKChild(Parent): data = models.CharField(max_length=10, unique=True) objects = NKManager() def natural_key(self): return self.data def __unicode__(self): return u'NKChild %s:%s' % (self.name, self.data) class RefToNKChild(models.Model): text = models.CharField(max_length=10) nk_fk = models.ForeignKey(NKChild, related_name='ref_fks') nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __unicode__(self): return u'%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) ) # ome models with pathological circular dependencies class Circle1(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle2'] class Circle2(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle1'] class Circle3(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle3'] class Circle4(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle5'] class Circle5(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle6'] class Circle6(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle4'] class ExternalDependency(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.book'] # Model for regression test of #11101 class Thingy(models.Model): name = models.CharField(max_length=255)
5,411
Python
.py
148
30.716216
79
0.681836
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,791
tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/fixtures_regress/tests.py
# -*- coding: utf-8 -*- # Unittests for fixtures. import os import re import sys try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.core import management from django.core.management.commands.dumpdata import sort_dependencies from django.core.management.base import CommandError from django.db.models import signals from django.db import transaction from django.test import TestCase, TransactionTestCase, skipIfDBFeature, \ skipUnlessDBFeature from models import Animal, Stuff from models import Absolute, Parent, Child from models import Article, Widget from models import Store, Person, Book from models import NKChild, RefToNKChild from models import Circle1, Circle2, Circle3 from models import ExternalDependency from models import Thingy pre_save_checks = [] def animal_pre_save_check(signal, sender, instance, **kwargs): "A signal that is used to check the type of data loaded from fixtures" pre_save_checks.append( ( 'Count = %s (%s)' % (instance.count, type(instance.count)), 'Weight = %s (%s)' % (instance.weight, type(instance.weight)), ) ) class TestFixtures(TestCase): def test_duplicate_pk(self): """ This is a regression test for ticket #3790. """ # Load a fixture that uses PK=1 management.call_command( 'loaddata', 'sequence', verbosity=0, commit=False ) # Create a new animal. Without a sequence reset, this new object # will take a PK of 1 (on Postgres), and the save will fail. animal = Animal( name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2 ) animal.save() self.assertGreater(animal.id, 1) @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_pretty_print_xml(self): """ Regression test for ticket #4558 -- pretty printing of XML fixtures doesn't affect parsing of None values. """ # Load a pretty-printed XML fixture with Nulls. management.call_command( 'loaddata', 'pretty.xml', verbosity=0, commit=False ) self.assertEqual(Stuff.objects.all()[0].name, None) self.assertEqual(Stuff.objects.all()[0].owner, None) @skipUnlessDBFeature('interprets_empty_strings_as_nulls') def test_pretty_print_xml_empty_strings(self): """ Regression test for ticket #4558 -- pretty printing of XML fixtures doesn't affect parsing of None values. """ # Load a pretty-printed XML fixture with Nulls. management.call_command( 'loaddata', 'pretty.xml', verbosity=0, commit=False ) self.assertEqual(Stuff.objects.all()[0].name, u'') self.assertEqual(Stuff.objects.all()[0].owner, None) def test_absolute_path(self): """ Regression test for ticket #6436 -- os.path.join will throw away the initial parts of a path if it encounters an absolute path. This means that if a fixture is specified as an absolute path, we need to make sure we don't discover the absolute path in every fixture directory. """ load_absolute_path = os.path.join( os.path.dirname(__file__), 'fixtures', 'absolute.json' ) management.call_command( 'loaddata', load_absolute_path, verbosity=0, commit=False ) self.assertEqual(Absolute.load_count, 1) def test_unknown_format(self): """ Test for ticket #4371 -- Loading data of an unknown format should fail Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture1.unkn', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "Problem installing fixture 'bad_fixture1': unkn is not a known serialization format.\n" ) def test_invalid_data(self): """ Test for ticket #4371 -- Loading a fixture file with invalid data using explicit filename. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture2.xml', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n" ) def test_invalid_data_no_ext(self): """ Test for ticket #4371 -- Loading a fixture file with invalid data without file extension. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture2', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n" ) def test_empty(self): """ Test for ticket #4371 -- Loading a fixture file with no data returns an error. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'empty', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n" ) def test_abort_loaddata_on_error(self): """ Test for ticket #4371 -- If any of the fixtures contain an error, loading is aborted. Validate that error conditions are caught correctly """ stderr = StringIO() management.call_command( 'loaddata', 'empty', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n" ) def test_error_message(self): """ (Regression for #9011 - error message is correct) """ stderr = StringIO() management.call_command( 'loaddata', 'bad_fixture2', 'animal', verbosity=0, commit=False, stderr=stderr, ) self.assertEqual( stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n" ) def test_pg_sequence_resetting_checks(self): """ Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't ascend to parent models when inheritance is used (since they are treated individually). """ management.call_command( 'loaddata', 'model-inheritance.json', verbosity=0, commit=False ) self.assertEqual(Parent.objects.all()[0].id, 1) self.assertEqual(Child.objects.all()[0].id, 1) def test_close_connection_after_loaddata(self): """ Test for ticket #7572 -- MySQL has a problem if the same connection is used to create tables, load data, and then query over that data. To compensate, we close the connection after running loaddata. This ensures that a new connection is opened when test queries are issued. """ management.call_command( 'loaddata', 'big-fixture.json', verbosity=0, commit=False ) articles = Article.objects.exclude(id=9) self.assertEqual( list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8] ) # Just for good measure, run the same query again. # Under the influence of ticket #7572, this will # give a different result to the previous call. self.assertEqual( list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8] ) def test_field_value_coerce(self): """ Test for tickets #8298, #9942 - Field values should be coerced into the correct type by the deserializer, not as part of the database write. """ global pre_save_checks pre_save_checks = [] signals.pre_save.connect(animal_pre_save_check) management.call_command( 'loaddata', 'animal.xml', verbosity=0, commit=False, ) self.assertEqual( pre_save_checks, [ ("Count = 42 (<type 'int'>)", "Weight = 1.2 (<type 'float'>)") ] ) signals.pre_save.disconnect(animal_pre_save_check) def test_dumpdata_uses_default_manager(self): """ Regression for #11286 Ensure that dumpdata honors the default manager Dump the current contents of the database as a JSON fixture """ management.call_command( 'loaddata', 'animal.xml', verbosity=0, commit=False, ) management.call_command( 'loaddata', 'sequence.json', verbosity=0, commit=False, ) animal = Animal( name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2 ) animal.save() stdout = StringIO() management.call_command( 'dumpdata', 'fixtures_regress.animal', format='json', stdout=stdout ) # Output order isn't guaranteed, so check for parts data = stdout.getvalue() # Get rid of artifacts like '000000002' to eliminate the differences # between different Python versions. data = re.sub('0{6,}\d', '', data) lion_json = '{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}' emu_json = '{"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}' platypus_json = '{"pk": %d, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}' platypus_json = platypus_json % animal.pk self.assertEqual(len(data), len('[%s]' % ', '.join([lion_json, emu_json, platypus_json]))) self.assertTrue(lion_json in data) self.assertTrue(emu_json in data) self.assertTrue(platypus_json in data) def test_proxy_model_included(self): """ Regression for #11428 - Proxy models aren't included when you dumpdata """ stdout = StringIO() # Create an instance of the concrete class widget = Widget.objects.create(name='grommet') management.call_command( 'dumpdata', 'fixtures_regress.widget', 'fixtures_regress.widgetproxy', format='json', stdout=stdout ) self.assertEqual( stdout.getvalue(), """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]""" % widget.pk ) class NaturalKeyFixtureTests(TestCase): def assertRaisesMessage(self, exc, msg, func, *args, **kwargs): try: func(*args, **kwargs) except Exception, e: self.assertEqual(msg, str(e)) self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e))) def test_nk_deserialize(self): """ Test for ticket #13030 - Python based parser version natural keys deserialize with fk to inheriting model """ management.call_command( 'loaddata', 'model-inheritance.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'nk-inheritance.json', verbosity=0, commit=False ) self.assertEqual( NKChild.objects.get(pk=1).data, 'apple' ) self.assertEqual( RefToNKChild.objects.get(pk=1).nk_fk.data, 'apple' ) def test_nk_deserialize_xml(self): """ Test for ticket #13030 - XML version natural keys deserialize with fk to inheriting model """ management.call_command( 'loaddata', 'model-inheritance.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'nk-inheritance.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'nk-inheritance2.xml', verbosity=0, commit=False ) self.assertEqual( NKChild.objects.get(pk=2).data, 'banana' ) self.assertEqual( RefToNKChild.objects.get(pk=2).nk_fk.data, 'apple' ) def test_nk_on_serialize(self): """ Check that natural key requirements are taken into account when serializing models """ management.call_command( 'loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False ) stdout = StringIO() management.call_command( 'dumpdata', 'fixtures_regress.book', 'fixtures_regress.person', 'fixtures_regress.store', verbosity=0, format='json', use_natural_keys=True, stdout=stdout, ) self.assertEqual( stdout.getvalue(), """[{"pk": 2, "model": "fixtures_regress.store", "fields": {"name": "Amazon"}}, {"pk": 3, "model": "fixtures_regress.store", "fields": {"name": "Borders"}}, {"pk": 4, "model": "fixtures_regress.person", "fields": {"name": "Neal Stephenson"}}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]""" ) def test_dependency_sorting(self): """ Now lets check the dependency sorting explicitly It doesn't matter what order you mention the models Store *must* be serialized before then Person, and both must be serialized before Book. """ sorted_deps = sort_dependencies( [('fixtures_regress', [Book, Person, Store])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_2(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Book, Store, Person])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_3(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Store, Book, Person])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_4(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Store, Person, Book])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_5(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, Book, Store])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_6(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, Store, Book])] ) self.assertEqual( sorted_deps, [Store, Person, Book] ) def test_dependency_sorting_dangling(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, Circle1, Store, Book])] ) self.assertEqual( sorted_deps, [Circle1, Store, Person, Book] ) def test_dependency_sorting_tight_circular(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Person, Circle2, Circle1, Store, Book])], ) def test_dependency_sorting_tight_circular_2(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Circle1, Book, Circle2])], ) def test_dependency_self_referential(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle3 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Book, Circle3])], ) def test_dependency_sorting_long(self): self.assertRaisesMessage( CommandError, """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized app list.""", sort_dependencies, [('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])], ) def test_dependency_sorting_normal(self): sorted_deps = sort_dependencies( [('fixtures_regress', [Person, ExternalDependency, Book])] ) self.assertEqual( sorted_deps, [Person, Book, ExternalDependency] ) def test_normal_pk(self): """ Check that normal primary keys still work on a model with natural key capabilities """ management.call_command( 'loaddata', 'non_natural_1.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False ) management.call_command( 'loaddata', 'non_natural_2.xml', verbosity=0, commit=False ) books = Book.objects.all() self.assertEqual( books.__repr__(), """[<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>, <Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>, <Book: Permutation City by Greg Egan (available at Angus and Robertson)>]""" ) class TestTicket11101(TransactionTestCase): def ticket_11101(self): management.call_command( 'loaddata', 'thingy.json', verbosity=0, commit=False ) self.assertEqual(Thingy.objects.count(), 1) transaction.rollback() self.assertEqual(Thingy.objects.count(), 0) transaction.commit() @skipUnlessDBFeature('supports_transactions') def test_ticket_11101(self): """Test that fixtures can be rolled back (ticket #11101).""" ticket_11101 = transaction.commit_manually(self.ticket_11101) ticket_11101()
20,147
Python
.py
568
25.512324
407
0.572541
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,792
models.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/models.py
""" Comments may be attached to any object. See the comment documentation for more information. """ from django.db import models from django.test import TestCase class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return '%s %s' % (self.first_name, self.last_name) class Article(models.Model): author = models.ForeignKey(Author) headline = models.CharField(max_length=100) def __str__(self): return self.headline class Entry(models.Model): title = models.CharField(max_length=250) body = models.TextField() pub_date = models.DateField() enable_comments = models.BooleanField() def __str__(self): return self.title class Book(models.Model): dewey_decimal = models.DecimalField(primary_key = True, decimal_places=2, max_digits=5)
896
Python
.py
25
31.48
91
0.715949
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,793
urls.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/urls.py
from django.conf.urls.defaults import * from django.contrib.comments.feeds import LatestCommentFeed feeds = { 'comments': LatestCommentFeed, } urlpatterns = patterns('regressiontests.comment_tests.custom_comments.views', url(r'^post/$', 'custom_submit_comment'), url(r'^flag/(\d+)/$', 'custom_flag_comment'), url(r'^delete/(\d+)/$', 'custom_delete_comment'), url(r'^approve/(\d+)/$', 'custom_approve_comment'), ) urlpatterns += patterns('', (r'^rss/legacy/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}), (r'^rss/comments/$', LatestCommentFeed()), )
626
Python
.py
15
38.6
98
0.662829
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,794
urls_admin.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/urls_admin.py
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.comments.admin import CommentsAdmin from django.contrib.comments.models import Comment # Make a new AdminSite to avoid picking up the deliberately broken admin # modules in other tests. admin_site = admin.AdminSite() admin_site.register(Comment, CommentsAdmin) # To demonstrate proper functionality even when ``delete_selected`` is removed. admin_site2 = admin.AdminSite() admin_site2.disable_action('delete_selected') admin_site2.register(Comment, CommentsAdmin) urlpatterns = patterns('', (r'^admin/', include(admin_site.urls)), (r'^admin2/', include(admin_site2.urls)), )
679
Python
.py
16
40.75
79
0.79697
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,795
feed_tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/tests/feed_tests.py
import warnings from django.test.utils import get_warnings_state, restore_warnings_state from regressiontests.comment_tests.tests import CommentTestCase class CommentFeedTests(CommentTestCase): urls = 'regressiontests.comment_tests.urls' feed_url = '/rss/comments/' def test_feed(self): response = self.client.get(self.feed_url) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/rss+xml') self.assertContains(response, '<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">') self.assertContains(response, '<title>example.com comments</title>') self.assertContains(response, '<link>http://example.com/</link>') self.assertContains(response, '</rss>') class LegacyCommentFeedTests(CommentFeedTests): feed_url = '/rss/legacy/comments/' def setUp(self): self._warnings_state = get_warnings_state() warnings.filterwarnings("ignore", category=DeprecationWarning, module='django.contrib.syndication.views') warnings.filterwarnings("ignore", category=DeprecationWarning, module='django.contrib.syndication.feeds') def tearDown(self): restore_warnings_state(self._warnings_state)
1,314
Python
.py
24
46.041667
101
0.698673
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,796
comment_view_tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/tests/comment_view_tests.py
import re from django.conf import settings from django.contrib.auth.models import User from django.contrib.comments import signals from django.contrib.comments.models import Comment from regressiontests.comment_tests.models import Article, Book from regressiontests.comment_tests.tests import CommentTestCase post_redirect_re = re.compile(r'^http://testserver/posted/\?c=(?P<pk>\d+$)') class CommentViewTests(CommentTestCase): def testPostCommentHTTPMethods(self): a = Article.objects.get(pk=1) data = self.getValidData(a) response = self.client.get("/post/", data) self.assertEqual(response.status_code, 405) self.assertEqual(response["Allow"], "POST") def testPostCommentMissingCtype(self): a = Article.objects.get(pk=1) data = self.getValidData(a) del data["content_type"] response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testPostCommentBadCtype(self): a = Article.objects.get(pk=1) data = self.getValidData(a) data["content_type"] = "Nobody expects the Spanish Inquisition!" response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testPostCommentMissingObjectPK(self): a = Article.objects.get(pk=1) data = self.getValidData(a) del data["object_pk"] response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testPostCommentBadObjectPK(self): a = Article.objects.get(pk=1) data = self.getValidData(a) data["object_pk"] = "14" response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testPostInvalidIntegerPK(self): a = Article.objects.get(pk=1) data = self.getValidData(a) data["comment"] = "This is another comment" data["object_pk"] = u'\ufffd' response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testPostInvalidDecimalPK(self): b = Book.objects.get(pk='12.34') data = self.getValidData(b) data["comment"] = "This is another comment" data["object_pk"] = 'cookies' response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testCommentPreview(self): a = Article.objects.get(pk=1) data = self.getValidData(a) data["preview"] = "Preview" response = self.client.post("/post/", data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "comments/preview.html") def testHashTampering(self): a = Article.objects.get(pk=1) data = self.getValidData(a) data["security_hash"] = "Nobody expects the Spanish Inquisition!" response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) def testDebugCommentErrors(self): """The debug error template should be shown only if DEBUG is True""" olddebug = settings.DEBUG settings.DEBUG = True a = Article.objects.get(pk=1) data = self.getValidData(a) data["security_hash"] = "Nobody expects the Spanish Inquisition!" response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) self.assertTemplateUsed(response, "comments/400-debug.html") settings.DEBUG = False response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) self.assertTemplateNotUsed(response, "comments/400-debug.html") settings.DEBUG = olddebug def testCreateValidComment(self): a = Article.objects.get(pk=1) data = self.getValidData(a) self.response = self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4") self.assertEqual(self.response.status_code, 302) self.assertEqual(Comment.objects.count(), 1) c = Comment.objects.all()[0] self.assertEqual(c.ip_address, "1.2.3.4") self.assertEqual(c.comment, "This is my comment") def testPostAsAuthenticatedUser(self): a = Article.objects.get(pk=1) data = self.getValidData(a) data['name'] = data['email'] = '' self.client.login(username="normaluser", password="normaluser") self.response = self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4") self.assertEqual(self.response.status_code, 302) self.assertEqual(Comment.objects.count(), 1) c = Comment.objects.all()[0] self.assertEqual(c.ip_address, "1.2.3.4") u = User.objects.get(username='normaluser') self.assertEqual(c.user, u) self.assertEqual(c.user_name, u.get_full_name()) self.assertEqual(c.user_email, u.email) def testPostAsAuthenticatedUserWithoutFullname(self): """ Check that the user's name in the comment is populated for authenticated users without first_name and last_name. """ user = User.objects.create_user(username='jane_other', email='[email protected]', password='jane_other') a = Article.objects.get(pk=1) data = self.getValidData(a) data['name'] = data['email'] = '' self.client.login(username="jane_other", password="jane_other") self.response = self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4") c = Comment.objects.get(user=user) self.assertEqual(c.ip_address, "1.2.3.4") self.assertEqual(c.user_name, 'jane_other') user.delete() def testPreventDuplicateComments(self): """Prevent posting the exact same comment twice""" a = Article.objects.get(pk=1) data = self.getValidData(a) self.client.post("/post/", data) self.client.post("/post/", data) self.assertEqual(Comment.objects.count(), 1) # This should not trigger the duplicate prevention self.client.post("/post/", dict(data, comment="My second comment.")) self.assertEqual(Comment.objects.count(), 2) def testCommentSignals(self): """Test signals emitted by the comment posting view""" # callback def receive(sender, **kwargs): self.assertEqual(kwargs['comment'].comment, "This is my comment") self.assertTrue('request' in kwargs) received_signals.append(kwargs.get('signal')) # Connect signals and keep track of handled ones received_signals = [] expected_signals = [ signals.comment_will_be_posted, signals.comment_was_posted ] for signal in expected_signals: signal.connect(receive) # Post a comment and check the signals self.testCreateValidComment() self.assertEqual(received_signals, expected_signals) for signal in expected_signals: signal.disconnect(receive) def testWillBePostedSignal(self): """ Test that the comment_will_be_posted signal can prevent the comment from actually getting saved """ def receive(sender, **kwargs): return False signals.comment_will_be_posted.connect(receive, dispatch_uid="comment-test") a = Article.objects.get(pk=1) data = self.getValidData(a) response = self.client.post("/post/", data) self.assertEqual(response.status_code, 400) self.assertEqual(Comment.objects.count(), 0) signals.comment_will_be_posted.disconnect(dispatch_uid="comment-test") def testWillBePostedSignalModifyComment(self): """ Test that the comment_will_be_posted signal can modify a comment before it gets posted """ def receive(sender, **kwargs): # a bad but effective spam filter :)... kwargs['comment'].is_public = False signals.comment_will_be_posted.connect(receive) self.testCreateValidComment() c = Comment.objects.all()[0] self.assertFalse(c.is_public) def testCommentNext(self): """Test the different "next" actions the comment view can take""" a = Article.objects.get(pk=1) data = self.getValidData(a) response = self.client.post("/post/", data) location = response["Location"] match = post_redirect_re.match(location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location) data["next"] = "/somewhere/else/" data["comment"] = "This is another comment" response = self.client.post("/post/", data) location = response["Location"] match = re.search(r"^http://testserver/somewhere/else/\?c=\d+$", location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location) def testCommentDoneView(self): a = Article.objects.get(pk=1) data = self.getValidData(a) response = self.client.post("/post/", data) location = response["Location"] match = post_redirect_re.match(location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location) pk = int(match.group('pk')) response = self.client.get(location) self.assertTemplateUsed(response, "comments/posted.html") self.assertEqual(response.context[0]["comment"], Comment.objects.get(pk=pk)) def testCommentNextWithQueryString(self): """ The `next` key needs to handle already having a query string (#10585) """ a = Article.objects.get(pk=1) data = self.getValidData(a) data["next"] = "/somewhere/else/?foo=bar" data["comment"] = "This is another comment" response = self.client.post("/post/", data) location = response["Location"] match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+$", location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location) def testCommentPostRedirectWithInvalidIntegerPK(self): """ Tests that attempting to retrieve the location specified in the post redirect, after adding some invalid data to the expected querystring it ends with, doesn't cause a server error. """ a = Article.objects.get(pk=1) data = self.getValidData(a) data["comment"] = "This is another comment" response = self.client.post("/post/", data) location = response["Location"] broken_location = location + u"\ufffd" response = self.client.get(broken_location) self.assertEqual(response.status_code, 200) def testCommentNextWithQueryStringAndAnchor(self): """ The `next` key needs to handle already having an anchor. Refs #13411. """ # With a query string also. a = Article.objects.get(pk=1) data = self.getValidData(a) data["next"] = "/somewhere/else/?foo=bar#baz" data["comment"] = "This is another comment" response = self.client.post("/post/", data) location = response["Location"] match = re.search(r"^http://testserver/somewhere/else/\?foo=bar&c=\d+#baz$", location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location) # Without a query string a = Article.objects.get(pk=1) data = self.getValidData(a) data["next"] = "/somewhere/else/#baz" data["comment"] = "This is another comment" response = self.client.post("/post/", data) location = response["Location"] match = re.search(r"^http://testserver/somewhere/else/\?c=\d+#baz$", location) self.assertTrue(match != None, "Unexpected redirect location: %s" % location)
11,809
Python
.py
247
39.149798
94
0.647003
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,797
templatetag_tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/tests/templatetag_tests.py
from django.contrib.comments.forms import CommentForm from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.template import Template, Context from regressiontests.comment_tests.models import Article, Author from regressiontests.comment_tests.tests import CommentTestCase class CommentTemplateTagTests(CommentTestCase): def render(self, t, **c): ctx = Context(c) out = Template(t).render(ctx) return ctx, out def testCommentFormTarget(self): ctx, out = self.render("{% load comments %}{% comment_form_target %}") self.assertEqual(out, "/post/") def testGetCommentForm(self, tag=None): t = "{% load comments %}" + (tag or "{% get_comment_form for comment_tests.article a.id as form %}") ctx, out = self.render(t, a=Article.objects.get(pk=1)) self.assertEqual(out, "") self.assertTrue(isinstance(ctx["form"], CommentForm)) def testGetCommentFormFromLiteral(self): self.testGetCommentForm("{% get_comment_form for comment_tests.article 1 as form %}") def testGetCommentFormFromObject(self): self.testGetCommentForm("{% get_comment_form for a as form %}") def testRenderCommentForm(self, tag=None): t = "{% load comments %}" + (tag or "{% render_comment_form for comment_tests.article a.id %}") ctx, out = self.render(t, a=Article.objects.get(pk=1)) self.assertTrue(out.strip().startswith("<form action=")) self.assertTrue(out.strip().endswith("</form>")) def testRenderCommentFormFromLiteral(self): self.testRenderCommentForm("{% render_comment_form for comment_tests.article 1 %}") def testRenderCommentFormFromObject(self): self.testRenderCommentForm("{% render_comment_form for a %}") def testGetCommentCount(self, tag=None): self.createSomeComments() t = "{% load comments %}" + (tag or "{% get_comment_count for comment_tests.article a.id as cc %}") + "{{ cc }}" ctx, out = self.render(t, a=Article.objects.get(pk=1)) self.assertEqual(out, "2") def testGetCommentCountFromLiteral(self): self.testGetCommentCount("{% get_comment_count for comment_tests.article 1 as cc %}") def testGetCommentCountFromObject(self): self.testGetCommentCount("{% get_comment_count for a as cc %}") def testGetCommentList(self, tag=None): c1, c2, c3, c4 = self.createSomeComments() t = "{% load comments %}" + (tag or "{% get_comment_list for comment_tests.author a.id as cl %}") ctx, out = self.render(t, a=Author.objects.get(pk=1)) self.assertEqual(out, "") self.assertEqual(list(ctx["cl"]), [c2]) def testGetCommentListFromLiteral(self): self.testGetCommentList("{% get_comment_list for comment_tests.author 1 as cl %}") def testGetCommentListFromObject(self): self.testGetCommentList("{% get_comment_list for a as cl %}") def testGetCommentPermalink(self): c1, c2, c3, c4 = self.createSomeComments() t = "{% load comments %}{% get_comment_list for comment_tests.author author.id as cl %}" t += "{% get_comment_permalink cl.0 %}" ct = ContentType.objects.get_for_model(Author) author = Author.objects.get(pk=1) ctx, out = self.render(t, author=author) self.assertEqual(out, "/cr/%s/%s/#c%s" % (ct.id, author.id, c2.id)) def testGetCommentPermalinkFormatted(self): c1, c2, c3, c4 = self.createSomeComments() t = "{% load comments %}{% get_comment_list for comment_tests.author author.id as cl %}" t += "{% get_comment_permalink cl.0 '#c%(id)s-by-%(user_name)s' %}" ct = ContentType.objects.get_for_model(Author) author = Author.objects.get(pk=1) ctx, out = self.render(t, author=author) self.assertEqual(out, "/cr/%s/%s/#c%s-by-Joe Somebody" % (ct.id, author.id, c2.id)) def testRenderCommentList(self, tag=None): t = "{% load comments %}" + (tag or "{% render_comment_list for comment_tests.article a.id %}") ctx, out = self.render(t, a=Article.objects.get(pk=1)) self.assertTrue(out.strip().startswith("<dl id=\"comments\">")) self.assertTrue(out.strip().endswith("</dl>")) def testRenderCommentListFromLiteral(self): self.testRenderCommentList("{% render_comment_list for comment_tests.article 1 %}") def testRenderCommentListFromObject(self): self.testRenderCommentList("{% render_comment_list for a %}")
4,556
Python
.py
76
52.407895
120
0.669657
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,798
model_tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/tests/model_tests.py
from django.contrib.comments.models import Comment from regressiontests.comment_tests.models import Author, Article from regressiontests.comment_tests.tests import CommentTestCase class CommentModelTests(CommentTestCase): def testSave(self): for c in self.createSomeComments(): self.assertNotEqual(c.submit_date, None) def testUserProperties(self): c1, c2, c3, c4 = self.createSomeComments() self.assertEqual(c1.name, "Joe Somebody") self.assertEqual(c2.email, "[email protected]") self.assertEqual(c3.name, "Frank Nobody") self.assertEqual(c3.url, "http://example.com/~frank/") self.assertEqual(c1.user, None) self.assertEqual(c3.user, c4.user) class CommentManagerTests(CommentTestCase): def testInModeration(self): """Comments that aren't public are considered in moderation""" c1, c2, c3, c4 = self.createSomeComments() c1.is_public = False c2.is_public = False c1.save() c2.save() moderated_comments = list(Comment.objects.in_moderation().order_by("id")) self.assertEqual(moderated_comments, [c1, c2]) def testRemovedCommentsNotInModeration(self): """Removed comments are not considered in moderation""" c1, c2, c3, c4 = self.createSomeComments() c1.is_public = False c2.is_public = False c2.is_removed = True c1.save() c2.save() moderated_comments = list(Comment.objects.in_moderation()) self.assertEqual(moderated_comments, [c1]) def testForModel(self): c1, c2, c3, c4 = self.createSomeComments() article_comments = list(Comment.objects.for_model(Article).order_by("id")) author_comments = list(Comment.objects.for_model(Author.objects.get(pk=1))) self.assertEqual(article_comments, [c1, c3]) self.assertEqual(author_comments, [c2])
1,924
Python
.py
41
39.097561
83
0.681067
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)
1,799
comment_utils_moderators_tests.py
gabrielfalcao_lettuce/tests/integration/lib/Django-1.3/tests/regressiontests/comment_tests/tests/comment_utils_moderators_tests.py
from regressiontests.comment_tests.tests import CommentTestCase, CT, Site from django.contrib.comments.forms import CommentForm from django.contrib.comments.models import Comment from django.contrib.comments.moderation import moderator, CommentModerator, AlreadyModerated from regressiontests.comment_tests.models import Entry from django.core import mail class EntryModerator1(CommentModerator): email_notification = True class EntryModerator2(CommentModerator): enable_field = 'enable_comments' class EntryModerator3(CommentModerator): auto_close_field = 'pub_date' close_after = 7 class EntryModerator4(CommentModerator): auto_moderate_field = 'pub_date' moderate_after = 7 class EntryModerator5(CommentModerator): auto_moderate_field = 'pub_date' moderate_after = 0 class EntryModerator6(CommentModerator): auto_close_field = 'pub_date' close_after = 0 class CommentUtilsModeratorTests(CommentTestCase): fixtures = ["comment_utils.xml"] def createSomeComments(self): # Tests for the moderation signals must actually post data # through the comment views, because only the comment views # emit the custom signals moderation listens for. e = Entry.objects.get(pk=1) data = self.getValidData(e) self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4") # We explicitly do a try/except to get the comment we've just # posted because moderation may have disallowed it, in which # case we can just return it as None. try: c1 = Comment.objects.all()[0] except IndexError: c1 = None self.client.post("/post/", data, REMOTE_ADDR="1.2.3.4") try: c2 = Comment.objects.all()[0] except IndexError: c2 = None return c1, c2 def tearDown(self): moderator.unregister(Entry) def testRegisterExistingModel(self): moderator.register(Entry, EntryModerator1) self.assertRaises(AlreadyModerated, moderator.register, Entry, EntryModerator1) def testEmailNotification(self): moderator.register(Entry, EntryModerator1) self.createSomeComments() self.assertEqual(len(mail.outbox), 2) def testCommentsEnabled(self): moderator.register(Entry, EntryModerator2) self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 1) def testAutoCloseField(self): moderator.register(Entry, EntryModerator3) self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 0) def testAutoModerateField(self): moderator.register(Entry, EntryModerator4) c1, c2 = self.createSomeComments() self.assertEqual(c2.is_public, False) def testAutoModerateFieldImmediate(self): moderator.register(Entry, EntryModerator5) c1, c2 = self.createSomeComments() self.assertEqual(c2.is_public, False) def testAutoCloseFieldImmediate(self): moderator.register(Entry, EntryModerator6) c1, c2 = self.createSomeComments() self.assertEqual(Comment.objects.all().count(), 0)
3,170
Python
.py
73
36.465753
92
0.714425
gabrielfalcao/lettuce
1,274
325
102
GPL-3.0
9/5/2024, 5:08:58 PM (Europe/Amsterdam)