hash
stringlengths
64
64
content
stringlengths
0
1.51M
988a1a384261cea1cc0dd71e76924afa2469e7e0d88b0504f35f6f924a211c13
from datetime import datetime from django.forms import CharField, DateTimeInput, Form from django.utils import translation from .base import WidgetTest class DateTimeInputTest(WidgetTest): widget = DateTimeInput() def test_render_none(self): self.check_html(self.widget, "date", None, '<input type="text" name="date">') def test_render_value(self): """ The microseconds are trimmed on display, by default. """ d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.assertEqual(str(d), "2007-09-17 12:51:34.482548") self.check_html( self.widget, "date", d, html=('<input type="text" name="date" value="2007-09-17 12:51:34">'), ) self.check_html( self.widget, "date", datetime(2007, 9, 17, 12, 51, 34), html=('<input type="text" name="date" value="2007-09-17 12:51:34">'), ) self.check_html( self.widget, "date", datetime(2007, 9, 17, 12, 51), html=('<input type="text" name="date" value="2007-09-17 12:51:00">'), ) def test_render_formatted(self): """ Use 'format' to change the way a value is displayed. """ widget = DateTimeInput( format="%d/%m/%Y %H:%M", attrs={"type": "datetime"}, ) d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.check_html( widget, "date", d, html='<input type="datetime" name="date" value="17/09/2007 12:51">', ) @translation.override("de-at") def test_l10n(self): d = datetime(2007, 9, 17, 12, 51, 34, 482548) self.check_html( self.widget, "date", d, html=('<input type="text" name="date" value="17.09.2007 12:51:34">'), ) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = CharField(widget=self.widget) form = TestForm() self.assertIs(self.widget.use_fieldset, False) self.assertHTMLEqual( '<div><label for="id_field">Field:</label>' '<input id="id_field" name="field" required type="text"></div>', form.render(), )
017f896bf2b0731184e38ae53b546ac21664d111fb90ef933d73bdeedf190917
from datetime import date from django.forms import DateField, Form, SelectDateWidget from django.test import override_settings from django.utils import translation from django.utils.dates import MONTHS_AP from .base import WidgetTest class SelectDateWidgetTest(WidgetTest): maxDiff = None widget = SelectDateWidget( years=( "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", ), ) def test_render_empty(self): self.check_html( self.widget, "mydate", "", html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ ), ) def test_render_none(self): """ Rendering the None or '' values should yield the same output. """ self.assertHTMLEqual( self.widget.render("mydate", None), self.widget.render("mydate", ""), ) def test_render_string(self): self.check_html( self.widget, "mydate", "2010-04-15", html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4" selected>April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15" selected>15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ ), ) def test_render_datetime(self): self.assertHTMLEqual( self.widget.render("mydate", date(2010, 4, 15)), self.widget.render("mydate", "2010-04-15"), ) def test_render_invalid_date(self): """ Invalid dates should still render the failed date. """ self.check_html( self.widget, "mydate", "2010-02-31", html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="">---</option> <option value="1">January</option> <option value="2" selected>February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31" selected>31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ ), ) def test_custom_months(self): widget = SelectDateWidget(months=MONTHS_AP, years=("2013",)) self.check_html( widget, "mydate", "", html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">Jan.</option> <option value="2">Feb.</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">Aug.</option> <option value="9">Sept.</option> <option value="10">Oct.</option> <option value="11">Nov.</option> <option value="12">Dec.</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2013">2013</option> </select> """ ), ) def test_selectdate_required(self): class GetNotRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=False) class GetRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=True) self.assertFalse(GetNotRequiredDate().fields["mydate"].widget.is_required) self.assertTrue(GetRequiredDate().fields["mydate"].widget.is_required) def test_selectdate_empty_label(self): w = SelectDateWidget(years=("2014",), empty_label="empty_label") # Rendering the default state with empty_label set as string. self.assertInHTML( '<option selected value="">empty_label</option>', w.render("mydate", ""), count=3, ) w = SelectDateWidget( years=("2014",), empty_label=("empty_year", "empty_month", "empty_day") ) # Rendering the default state with empty_label tuple. self.assertHTMLEqual( w.render("mydate", ""), """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">empty_month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">empty_day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">empty_year</option> <option value="2014">2014</option> </select> """, ) with self.assertRaisesMessage( ValueError, "empty_label list/tuple must have 3 elements." ): SelectDateWidget(years=("2014",), empty_label=("not enough", "values")) @translation.override("nl") def test_l10n(self): w = SelectDateWidget( years=( "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", ) ) self.assertEqual( w.value_from_datadict( {"date_year": "2010", "date_month": "8", "date_day": "13"}, {}, "date" ), "13-08-2010", ) self.assertHTMLEqual( w.render("date", "13-08-2010"), """ <select name="date_day" id="id_date_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13" selected>13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="date_month" id="id_date_month"> <option value="">---</option> <option value="1">januari</option> <option value="2">februari</option> <option value="3">maart</option> <option value="4">april</option> <option value="5">mei</option> <option value="6">juni</option> <option value="7">juli</option> <option value="8" selected>augustus</option> <option value="9">september</option> <option value="10">oktober</option> <option value="11">november</option> <option value="12">december</option> </select> <select name="date_year" id="id_date_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """, ) # Even with an invalid date, the widget should reflect the entered # value. self.assertEqual(w.render("mydate", "2010-02-30").count("selected"), 3) # Years before 1900 should work. w = SelectDateWidget(years=("1899",)) self.assertEqual( w.value_from_datadict( {"date_year": "1899", "date_month": "8", "date_day": "13"}, {}, "date" ), "13-08-1899", ) # And years before 1000 (demonstrating the need for # sanitize_strftime_format). w = SelectDateWidget(years=("0001",)) self.assertEqual( w.value_from_datadict( {"date_year": "0001", "date_month": "8", "date_day": "13"}, {}, "date" ), "13-08-0001", ) @override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y"]) def test_custom_input_format(self): w = SelectDateWidget(years=("0001", "1899", "2009", "2010")) with translation.override(None): for values, expected_value in ( (("0001", "8", "13"), "13.08.0001"), (("1899", "7", "11"), "11.07.1899"), (("2009", "3", "7"), "07.03.2009"), ): with self.subTest(values=values): data = { "field_%s" % field: value for field, value in zip(("year", "month", "day"), values) } self.assertEqual( w.value_from_datadict(data, {}, "field"), expected_value ) expected_dict = { field: int(value) for field, value in zip(("year", "month", "day"), values) } self.assertEqual(w.format_value(expected_value), expected_dict) def test_format_value(self): valid_formats = [ "2000-1-1", "2000-10-15", "2000-01-01", "2000-01-0", "2000-0-01", "2000-0-0", "0-01-01", "0-01-0", "0-0-01", "0-0-0", ] for value in valid_formats: year, month, day = (int(x) or "" for x in value.split("-")) with self.subTest(value=value): self.assertEqual( self.widget.format_value(value), {"day": day, "month": month, "year": year}, ) invalid_formats = [ "2000-01-001", "2000-001-01", "2-01-01", "20-01-01", "200-01-01", "20000-01-01", ] for value in invalid_formats: with self.subTest(value=value): self.assertEqual( self.widget.format_value(value), {"day": None, "month": None, "year": None}, ) def test_value_from_datadict(self): tests = [ (("2000", "12", "1"), "2000-12-01"), (("", "12", "1"), "0-12-1"), (("2000", "", "1"), "2000-0-1"), (("2000", "12", ""), "2000-12-0"), (("", "", "", ""), None), ((None, "12", "1"), None), (("2000", None, "1"), None), (("2000", "12", None), None), ] for values, expected in tests: with self.subTest(values=values): data = {} for field_name, value in zip(("year", "month", "day"), values): if value is not None: data["field_%s" % field_name] = value self.assertEqual( self.widget.value_from_datadict(data, {}, "field"), expected ) def test_value_omitted_from_data(self): self.assertIs(self.widget.value_omitted_from_data({}, {}, "field"), True) self.assertIs( self.widget.value_omitted_from_data({"field_month": "12"}, {}, "field"), False, ) self.assertIs( self.widget.value_omitted_from_data({"field_year": "2000"}, {}, "field"), False, ) self.assertIs( self.widget.value_omitted_from_data({"field_day": "1"}, {}, "field"), False ) data = {"field_day": "1", "field_month": "12", "field_year": "2000"} self.assertIs(self.widget.value_omitted_from_data(data, {}, "field"), False) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_years_rendered_without_separator(self): widget = SelectDateWidget(years=(2007,)) self.check_html( widget, "mydate", "", html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2007">2007</option> </select> """ ), ) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = DateField(widget=self.widget) form = TestForm() self.assertIs(self.widget.use_fieldset, True) self.assertHTMLEqual( '<div><fieldset><legend for="id_field_month">Field:</legend>' '<select name="field_month" required id="id_field_month">' '<option value="1">January</option><option value="2">February</option>' '<option value="3">March</option><option value="4">April</option>' '<option value="5">May</option><option value="6">June</option>' '<option value="7">July</option><option value="8">August</option>' '<option value="9">September</option><option value="10">October</option>' '<option value="11">November</option><option value="12">December</option>' '</select><select name="field_day" required id="id_field_day">' '<option value="1">1</option><option value="2">2</option>' '<option value="3">3</option><option value="4">4</option>' '<option value="5">5</option><option value="6">6</option>' '<option value="7">7</option><option value="8">8</option>' '<option value="9">9</option><option value="10">10</option>' '<option value="11">11</option><option value="12">12</option>' '<option value="13">13</option><option value="14">14</option>' '<option value="15">15</option><option value="16">16</option>' '<option value="17">17</option><option value="18">18</option>' '<option value="19">19</option><option value="20">20</option>' '<option value="21">21</option><option value="22">22</option>' '<option value="23">23</option><option value="24">24</option>' '<option value="25">25</option><option value="26">26</option>' '<option value="27">27</option><option value="28">28</option>' '<option value="29">29</option><option value="30">30</option>' '<option value="31">31</option></select>' '<select name="field_year" required id="id_field_year">' '<option value="2007">2007</option><option value="2008">2008</option>' '<option value="2009">2009</option><option value="2010">2010</option>' '<option value="2011">2011</option><option value="2012">2012</option>' '<option value="2013">2013</option><option value="2014">2014</option>' '<option value="2015">2015</option><option value="2016">2016</option>' "</select></fieldset></div>", form.render(), )
b3bff017e559fb68b738a9af808488427e10edab30006ea3f49c7a7277b20aed
import decimal from django.core.exceptions import ValidationError from django.forms import DecimalField, NumberInput, Widget from django.test import SimpleTestCase, override_settings from django.utils import formats, translation from . import FormFieldAssertionsMixin class DecimalFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_decimalfield_1(self): f = DecimalField(max_digits=4, decimal_places=2) self.assertWidgetRendersTo( f, '<input id="id_f" step="0.01" type="number" name="f" required>' ) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(f.clean("1"), decimal.Decimal("1")) self.assertIsInstance(f.clean("1"), decimal.Decimal) self.assertEqual(f.clean("23"), decimal.Decimal("23")) self.assertEqual(f.clean("3.14"), decimal.Decimal("3.14")) self.assertEqual(f.clean(3.14), decimal.Decimal("3.14")) self.assertEqual(f.clean(decimal.Decimal("3.14")), decimal.Decimal("3.14")) self.assertEqual(f.clean("1.0 "), decimal.Decimal("1.0")) self.assertEqual(f.clean(" 1.0"), decimal.Decimal("1.0")) self.assertEqual(f.clean(" 1.0 "), decimal.Decimal("1.0")) with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 4 digits in total.'" ): f.clean("123.45") with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 2 decimal places.'" ): f.clean("1.234") msg = "'Ensure that there are no more than 2 digits before the decimal point.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("123.4") self.assertEqual(f.clean("-12.34"), decimal.Decimal("-12.34")) with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 4 digits in total.'" ): f.clean("-123.45") self.assertEqual(f.clean("-.12"), decimal.Decimal("-0.12")) self.assertEqual(f.clean("-00.12"), decimal.Decimal("-0.12")) self.assertEqual(f.clean("-000.12"), decimal.Decimal("-0.12")) with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 2 decimal places.'" ): f.clean("-000.123") with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 4 digits in total.'" ): f.clean("-000.12345") self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_enter_a_number_error(self): f = DecimalField(max_value=1, max_digits=4, decimal_places=2) values = ( "-NaN", "NaN", "+NaN", "-sNaN", "sNaN", "+sNaN", "-Inf", "Inf", "+Inf", "-Infinity", "Infinity", "+Infinity", "a", "łąść", "1.0a", "--0.12", ) for value in values: with self.subTest(value=value), self.assertRaisesMessage( ValidationError, "'Enter a number.'" ): f.clean(value) def test_decimalfield_2(self): f = DecimalField(max_digits=4, decimal_places=2, required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertEqual(f.clean("1"), decimal.Decimal("1")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_decimalfield_3(self): f = DecimalField( max_digits=4, decimal_places=2, max_value=decimal.Decimal("1.5"), min_value=decimal.Decimal("0.5"), ) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" ' "required>", ) with self.assertRaisesMessage( ValidationError, "'Ensure this value is less than or equal to 1.5.'" ): f.clean("1.6") with self.assertRaisesMessage( ValidationError, "'Ensure this value is greater than or equal to 0.5.'" ): f.clean("0.4") self.assertEqual(f.clean("1.5"), decimal.Decimal("1.5")) self.assertEqual(f.clean("0.5"), decimal.Decimal("0.5")) self.assertEqual(f.clean(".5"), decimal.Decimal("0.5")) self.assertEqual(f.clean("00.50"), decimal.Decimal("0.50")) self.assertEqual(f.max_digits, 4) self.assertEqual(f.decimal_places, 2) self.assertEqual(f.max_value, decimal.Decimal("1.5")) self.assertEqual(f.min_value, decimal.Decimal("0.5")) def test_decimalfield_4(self): f = DecimalField(decimal_places=2) with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 2 decimal places.'" ): f.clean("0.00000001") def test_decimalfield_5(self): f = DecimalField(max_digits=3) # Leading whole zeros "collapse" to one digit. self.assertEqual(f.clean("0000000.10"), decimal.Decimal("0.1")) # But a leading 0 before the . doesn't count toward max_digits self.assertEqual(f.clean("0000000.100"), decimal.Decimal("0.100")) # Only leading whole zeros "collapse" to one digit. self.assertEqual(f.clean("000000.02"), decimal.Decimal("0.02")) with self.assertRaisesMessage( ValidationError, "'Ensure that there are no more than 3 digits in total.'" ): f.clean("000000.0002") self.assertEqual(f.clean(".002"), decimal.Decimal("0.002")) def test_decimalfield_6(self): f = DecimalField(max_digits=2, decimal_places=2) self.assertEqual(f.clean(".01"), decimal.Decimal(".01")) msg = "'Ensure that there are no more than 0 digits before the decimal point.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("1.1") def test_decimalfield_scientific(self): f = DecimalField(max_digits=4, decimal_places=2) with self.assertRaisesMessage(ValidationError, "Ensure that there are no more"): f.clean("1E+2") self.assertEqual(f.clean("1E+1"), decimal.Decimal("10")) self.assertEqual(f.clean("1E-1"), decimal.Decimal("0.1")) self.assertEqual(f.clean("0.546e+2"), decimal.Decimal("54.6")) def test_decimalfield_widget_attrs(self): f = DecimalField(max_digits=6, decimal_places=2) self.assertEqual(f.widget_attrs(Widget()), {}) self.assertEqual(f.widget_attrs(NumberInput()), {"step": "0.01"}) f = DecimalField(max_digits=10, decimal_places=0) self.assertEqual(f.widget_attrs(NumberInput()), {"step": "1"}) f = DecimalField(max_digits=19, decimal_places=19) self.assertEqual(f.widget_attrs(NumberInput()), {"step": "1e-19"}) f = DecimalField(max_digits=20) self.assertEqual(f.widget_attrs(NumberInput()), {"step": "any"}) f = DecimalField(max_digits=6, widget=NumberInput(attrs={"step": "0.01"})) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" type="number" id="id_f" required>' ) def test_decimalfield_localized(self): """ A localized DecimalField's widget renders to a text input without number input specific attributes. """ f = DecimalField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>') def test_decimalfield_changed(self): f = DecimalField(max_digits=2, decimal_places=2) d = decimal.Decimal("0.1") self.assertFalse(f.has_changed(d, "0.10")) self.assertTrue(f.has_changed(d, "0.101")) with translation.override("fr"): f = DecimalField(max_digits=2, decimal_places=2, localize=True) localized_d = formats.localize_input(d) # -> '0,1' in French self.assertFalse(f.has_changed(d, localized_d)) @override_settings(DECIMAL_SEPARATOR=",") def test_decimalfield_support_decimal_separator(self): with translation.override(None): f = DecimalField(localize=True) self.assertEqual(f.clean("1001,10"), decimal.Decimal("1001.10")) self.assertEqual(f.clean("1001.10"), decimal.Decimal("1001.10")) @override_settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR=".", ) def test_decimalfield_support_thousands_separator(self): with translation.override(None): f = DecimalField(localize=True) self.assertEqual(f.clean("1.001,10"), decimal.Decimal("1001.10")) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("1,001.1")
ab4a7673504339cd102328257a54c4ee5aefb3e4dce03178d24097e361a907a3
from django.core.exceptions import ValidationError from django.forms import FloatField, NumberInput from django.test import SimpleTestCase from django.test.selenium import SeleniumTestCase from django.test.utils import override_settings from django.urls import reverse from django.utils import formats, translation from . import FormFieldAssertionsMixin class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo( f, '<input step="any" type="number" name="f" id="id_f" required>' ) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1.0, f.clean("1")) self.assertIsInstance(f.clean("1"), float) self.assertEqual(23.0, f.clean("23")) self.assertEqual(3.1400000000000001, f.clean("3.14")) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("a") self.assertEqual(1.0, f.clean("1.0 ")) self.assertEqual(1.0, f.clean(" 1.0")) self.assertEqual(1.0, f.clean(" 1.0 ")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("1.0a") self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("Infinity") with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("NaN") with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("-Inf") def test_floatfield_2(self): f = FloatField(required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertEqual(1.0, f.clean("1")) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo( f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" ' "required>", ) with self.assertRaisesMessage( ValidationError, "'Ensure this value is less than or equal to 1.5.'" ): f.clean("1.6") with self.assertRaisesMessage( ValidationError, "'Ensure this value is greater than or equal to 0.5.'" ): f.clean("0.4") self.assertEqual(1.5, f.clean("1.5")) self.assertEqual(0.5, f.clean("0.5")) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5) def test_floatfield_4(self): f = FloatField(step_size=0.02) self.assertWidgetRendersTo( f, '<input name="f" step="0.02" type="number" id="id_f" required>', ) msg = "'Ensure this value is a multiple of step size 0.02.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("0.01") self.assertEqual(2.34, f.clean("2.34")) self.assertEqual(2.1, f.clean("2.1")) self.assertEqual(-0.50, f.clean("-.5")) self.assertEqual(-1.26, f.clean("-1.26")) self.assertEqual(f.step_size, 0.02) def test_floatfield_widget_attrs(self): f = FloatField(widget=NumberInput(attrs={"step": 0.01, "max": 1.0, "min": 0.0})) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" ' "required>", ) def test_floatfield_localized(self): """ A localized FloatField's widget renders to a text input without any number input specific attributes. """ f = FloatField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>') def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, "4.3500")) with translation.override("fr"): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n)) @override_settings(DECIMAL_SEPARATOR=",") def test_floatfield_support_decimal_separator(self): with translation.override(None): f = FloatField(localize=True) self.assertEqual(f.clean("1001,10"), 1001.10) self.assertEqual(f.clean("1001.10"), 1001.10) @override_settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR=".", ) def test_floatfield_support_thousands_separator(self): with translation.override(None): f = FloatField(localize=True) self.assertEqual(f.clean("1.001,10"), 1001.10) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("1,001.1") @override_settings(ROOT_URLCONF="forms_tests.urls") class FloatFieldHTMLTest(SeleniumTestCase): available_apps = ["forms_tests"] def test_float_field_rendering_passes_client_side_validation(self): """ Rendered widget allows non-integer value with the client-side validation. """ from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("form_view")) number_input = self.selenium.find_element(By.ID, "id_number") number_input.send_keys("0.5") is_valid = self.selenium.execute_script( "return document.getElementById('id_number').checkValidity()" ) self.assertTrue(is_valid)
01bb32400587cb0b2c21302286ac0e2d4df55affae499c40a315bea761f17141
import os.path from django.core.exceptions import ValidationError from django.forms import FilePathField from django.test import SimpleTestCase PATH = os.path.dirname(os.path.abspath(__file__)) def fix_os_paths(x): if isinstance(x, str): return x.removeprefix(PATH).replace("\\", "/") elif isinstance(x, tuple): return tuple(fix_os_paths(list(x))) elif isinstance(x, list): return [fix_os_paths(y) for y in x] else: return x class FilePathFieldTest(SimpleTestCase): expected_choices = [ ("/filepathfield_test_dir/__init__.py", "__init__.py"), ("/filepathfield_test_dir/a.py", "a.py"), ("/filepathfield_test_dir/ab.py", "ab.py"), ("/filepathfield_test_dir/b.py", "b.py"), ("/filepathfield_test_dir/c/__init__.py", "__init__.py"), ("/filepathfield_test_dir/c/d.py", "d.py"), ("/filepathfield_test_dir/c/e.py", "e.py"), ("/filepathfield_test_dir/c/f/__init__.py", "__init__.py"), ("/filepathfield_test_dir/c/f/g.py", "g.py"), ("/filepathfield_test_dir/h/__init__.py", "__init__.py"), ("/filepathfield_test_dir/j/__init__.py", "__init__.py"), ] path = os.path.join(PATH, "filepathfield_test_dir") + "/" def assertChoices(self, field, expected_choices): self.assertEqual(fix_os_paths(field.choices), expected_choices) def test_fix_os_paths(self): self.assertEqual(fix_os_paths(self.path), ("/filepathfield_test_dir/")) def test_nonexistent_path(self): with self.assertRaisesMessage(FileNotFoundError, "nonexistent"): FilePathField(path="nonexistent") def test_no_options(self): f = FilePathField(path=self.path) expected = [ ("/filepathfield_test_dir/README", "README"), ] + self.expected_choices[:4] self.assertChoices(f, expected) def test_clean(self): f = FilePathField(path=self.path) msg = "'Select a valid choice. a.py is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("a.py") self.assertEqual( fix_os_paths(f.clean(self.path + "a.py")), "/filepathfield_test_dir/a.py" ) def test_match(self): f = FilePathField(path=self.path, match=r"^.*?\.py$") self.assertChoices(f, self.expected_choices[:4]) def test_recursive(self): f = FilePathField(path=self.path, recursive=True, match=r"^.*?\.py$") expected = [ ("/filepathfield_test_dir/__init__.py", "__init__.py"), ("/filepathfield_test_dir/a.py", "a.py"), ("/filepathfield_test_dir/ab.py", "ab.py"), ("/filepathfield_test_dir/b.py", "b.py"), ("/filepathfield_test_dir/c/__init__.py", "c/__init__.py"), ("/filepathfield_test_dir/c/d.py", "c/d.py"), ("/filepathfield_test_dir/c/e.py", "c/e.py"), ("/filepathfield_test_dir/c/f/__init__.py", "c/f/__init__.py"), ("/filepathfield_test_dir/c/f/g.py", "c/f/g.py"), ("/filepathfield_test_dir/h/__init__.py", "h/__init__.py"), ("/filepathfield_test_dir/j/__init__.py", "j/__init__.py"), ] self.assertChoices(f, expected) def test_allow_folders(self): f = FilePathField(path=self.path, allow_folders=True, allow_files=False) self.assertChoices( f, [ ("/filepathfield_test_dir/c", "c"), ("/filepathfield_test_dir/h", "h"), ("/filepathfield_test_dir/j", "j"), ], ) def test_recursive_no_folders_or_files(self): f = FilePathField( path=self.path, recursive=True, allow_folders=False, allow_files=False ) self.assertChoices(f, []) def test_recursive_folders_without_files(self): f = FilePathField( path=self.path, recursive=True, allow_folders=True, allow_files=False ) self.assertChoices( f, [ ("/filepathfield_test_dir/c", "c"), ("/filepathfield_test_dir/h", "h"), ("/filepathfield_test_dir/j", "j"), ("/filepathfield_test_dir/c/f", "c/f"), ], )
d419ab0aa2b87096ff4fff148fa7d7179f1bdea2f10d56facb3bdcec85f4c1ec
import datetime from collections import Counter from unittest import mock from django.core.exceptions import ValidationError from django.forms import ( BaseForm, CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, formsets, ) from django.forms.formsets import ( INITIAL_FORM_COUNT, MAX_NUM_FORM_COUNT, MIN_NUM_FORM_COUNT, TOTAL_FORM_COUNT, BaseFormSet, ManagementForm, all_valid, formset_factory, ) from django.forms.renderers import TemplatesSetting from django.forms.utils import ErrorList from django.forms.widgets import HiddenInput from django.test import SimpleTestCase from . import jinja2_tests class Choice(Form): choice = CharField() votes = IntegerField() ChoiceFormSet = formset_factory(Choice) class ChoiceFormsetWithNonFormError(ChoiceFormSet): def clean(self): super().clean() raise ValidationError("non-form error") class FavoriteDrinkForm(Form): name = CharField() class BaseFavoriteDrinksFormSet(BaseFormSet): def clean(self): seen_drinks = [] for drink in self.cleaned_data: if drink["name"] in seen_drinks: raise ValidationError("You may only specify a drink once.") seen_drinks.append(drink["name"]) # A FormSet that takes a list of favorite drinks and raises an error if # there are any duplicates. FavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3 ) class CustomKwargForm(Form): def __init__(self, *args, custom_kwarg, **kwargs): self.custom_kwarg = custom_kwarg super().__init__(*args, **kwargs) class FormsFormsetTestCase(SimpleTestCase): def make_choiceformset( self, formset_data=None, formset_class=ChoiceFormSet, total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs, ): """ Make a ChoiceFormset from the given formset_data. The data should be given as a list of (choice, votes) tuples. """ kwargs.setdefault("prefix", "choices") kwargs.setdefault("auto_id", False) if formset_data is None: return formset_class(**kwargs) if total_forms is None: total_forms = len(formset_data) def prefixed(*args): args = (kwargs["prefix"],) + args return "-".join(args) data = { prefixed("TOTAL_FORMS"): str(total_forms), prefixed("INITIAL_FORMS"): str(initial_forms), prefixed("MAX_NUM_FORMS"): str(max_num_forms), prefixed("MIN_NUM_FORMS"): str(min_num_forms), } for i, (choice, votes) in enumerate(formset_data): data[prefixed(str(i), "choice")] = choice data[prefixed(str(i), "votes")] = votes return formset_class(data, **kwargs) def test_basic_formset(self): """ A FormSet constructor takes the same arguments as Form. Create a FormSet for adding data. By default, it displays 1 blank form. """ formset = self.make_choiceformset() self.assertHTMLEqual( str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1"> <input type="hidden" name="choices-INITIAL_FORMS" value="0"> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0"> <input type="hidden" name="choices-MAX_NUM_FORMS" value="1000"> <div>Choice:<input type="text" name="choices-0-choice"></div> <div>Votes:<input type="number" name="choices-0-votes"></div>""", ) # FormSet are treated similarly to Forms. FormSet has an is_valid() # method, and a cleaned_data or errors attribute depending on whether # all the forms passed validation. However, unlike a Form, cleaned_data # and errors will be a list of dicts rather than a single dict. formset = self.make_choiceformset([("Calexico", "100")]) self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}], ) # If a FormSet wasn't passed any data, is_valid() and has_changed() # return False. formset = self.make_choiceformset() self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) def test_form_kwargs_formset(self): """ Custom kwargs set on the formset instance are passed to the underlying forms. """ FormSet = formset_factory(CustomKwargForm, extra=2) formset = FormSet(form_kwargs={"custom_kwarg": 1}) for form in formset: self.assertTrue(hasattr(form, "custom_kwarg")) self.assertEqual(form.custom_kwarg, 1) def test_form_kwargs_formset_dynamic(self): """Form kwargs can be passed dynamically in a formset.""" class DynamicBaseFormSet(BaseFormSet): def get_form_kwargs(self, index): return {"custom_kwarg": index} DynamicFormSet = formset_factory( CustomKwargForm, formset=DynamicBaseFormSet, extra=2 ) formset = DynamicFormSet(form_kwargs={"custom_kwarg": "ignored"}) for i, form in enumerate(formset): self.assertTrue(hasattr(form, "custom_kwarg")) self.assertEqual(form.custom_kwarg, i) def test_form_kwargs_empty_form(self): FormSet = formset_factory(CustomKwargForm) formset = FormSet(form_kwargs={"custom_kwarg": 1}) self.assertTrue(hasattr(formset.empty_form, "custom_kwarg")) self.assertEqual(formset.empty_form.custom_kwarg, 1) def test_empty_permitted_ignored_empty_form(self): formset = ArticleFormSet(form_kwargs={"empty_permitted": False}) self.assertIs(formset.empty_form.empty_permitted, True) def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms. formset = self.make_choiceformset([("Calexico", "")]) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{"votes": ["This field is required."]}]) def test_formset_validation_count(self): """ A formset's ManagementForm is validated once per FormSet.is_valid() call and each form of the formset is cleaned once. """ def make_method_counter(func): """Add a counter to func for the number of times it's called.""" counter = Counter() counter.call_count = 0 def mocked_func(*args, **kwargs): counter.call_count += 1 return func(*args, **kwargs) return mocked_func, counter mocked_is_valid, is_valid_counter = make_method_counter( formsets.ManagementForm.is_valid ) mocked_full_clean, full_clean_counter = make_method_counter(BaseForm.full_clean) formset = self.make_choiceformset( [("Calexico", "100"), ("Any1", "42"), ("Any2", "101")] ) with mock.patch( "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid ), mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) def test_formset_has_changed(self): """ FormSet.has_changed() is True if any data is passed to its forms, even if the formset didn't validate. """ blank_formset = self.make_choiceformset([("", "")]) self.assertFalse(blank_formset.has_changed()) # invalid formset invalid_formset = self.make_choiceformset([("Calexico", "")]) self.assertFalse(invalid_formset.is_valid()) self.assertTrue(invalid_formset.has_changed()) # valid formset valid_formset = self.make_choiceformset([("Calexico", "100")]) self.assertTrue(valid_formset.is_valid()) self.assertTrue(valid_formset.has_changed()) def test_formset_initial_data(self): """ A FormSet can be prefilled with existing data by providing a list of dicts to the `initial` argument. By default, an extra blank form is included. """ formset = self.make_choiceformset( initial=[{"choice": "Calexico", "votes": 100}] ) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Choice: <input type="text" name="choices-1-choice"></li>' '<li>Votes: <input type="number" name="choices-1-votes"></li>', ) def test_blank_form_unfilled(self): """A form that's displayed as blank may be submitted as blank.""" formset = self.make_choiceformset( [("Calexico", "100"), ("", "")], initial_forms=1 ) self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}, {}], ) def test_second_form_partially_filled(self): """ If at least one field is filled out on a blank form, it will be validated. """ formset = self.make_choiceformset( [("Calexico", "100"), ("The Decemberists", "")], initial_forms=1 ) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {"votes": ["This field is required."]}]) def test_delete_prefilled_data(self): """ Deleting prefilled data is an error. Removing data from form fields isn't the proper way to delete it. """ formset = self.make_choiceformset([("", ""), ("", "")], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [ { "votes": ["This field is required."], "choice": ["This field is required."], }, {}, ], ) def test_displaying_more_than_one_blank_form(self): """ More than 1 empty form can be displayed using formset_factory's `extra` argument. """ ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""", ) # Since every form was displayed as blank, they are also accepted as # blank. This may seem a little strange, but min_num is used to require # a minimum number of forms to be completed. data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "", "choices-0-votes": "", "choices-1-choice": "", "choices-1-votes": "", "choices-2-choice": "", "choices-2-votes": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}]) def test_min_num_displaying_more_than_one_blank_form(self): """ More than 1 empty form can also be displayed using formset_factory's min_num argument. It will (essentially) increment the extra argument. """ ChoiceFormSet = formset_factory(Choice, extra=1, min_num=1) formset = ChoiceFormSet(auto_id=False, prefix="choices") # Min_num forms are required; extra forms can be empty. self.assertFalse(formset.forms[0].empty_permitted) self.assertTrue(formset.forms[1].empty_permitted) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li>""", ) def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self): """More than 1 empty form can be displayed using min_num.""" ChoiceFormSet = formset_factory(Choice, extra=0, min_num=3) formset = ChoiceFormSet(auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""", ) def test_single_form_completed(self): """Just one form may be completed.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-1-choice": "", "choices-1-votes": "", "choices-2-choice": "", "choices-2-votes": "", } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}, {}, {}], ) def test_formset_validate_max_flag(self): """ If validate_max is set and max_num is less than TOTAL_FORMS in the data, a ValidationError is raised. MAX_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at most 1 form."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>Please submit at most 1 form.</li></ul>', ) def test_formset_validate_max_flag_custom_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "2", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_many_forms": "Number of submitted forms should be at most %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at most 1."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at most 1.</li></ul>", ) def test_formset_validate_min_flag(self): """ If validate_min is set and min_num is more than TOTAL_FORMS in the data, a ValidationError is raised. MIN_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at least 3 forms."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "Please submit at least 3 forms.</li></ul>", ) def test_formset_validate_min_flag_custom_formatted_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_few_forms": "Number of submitted forms should be at least %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at least 3."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at least 3.</li></ul>", ) def test_formset_validate_min_unchanged_forms(self): """ min_num validation doesn't consider unchanged forms with initial data as "empty". """ initial = [ {"choice": "Zero", "votes": 0}, {"choice": "One", "votes": 0}, ] data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "2", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "2", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", # changed from initial } ChoiceFormSet = formset_factory(Choice, min_num=2, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices", initial=initial) self.assertFalse(formset.forms[0].has_changed()) self.assertTrue(formset.forms[1].has_changed()) self.assertTrue(formset.is_valid()) def test_formset_validate_min_excludes_empty_forms(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", } ChoiceFormSet = formset_factory( Choice, extra=2, min_num=1, validate_min=True, can_delete=True ) formset = ChoiceFormSet(data, prefix="choices") self.assertFalse(formset.has_changed()) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at least 1 form."]) def test_second_form_partially_filled_2(self): """A partially completed form is invalid.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-1-choice": "The Decemberists", "choices-1-votes": "", # missing value "choices-2-choice": "", "choices-2-votes": "", } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [{}, {"votes": ["This field is required."]}, {}] ) def test_more_initial_data(self): """ The extra argument works when the formset is pre-filled with initial data. """ initial = [{"choice": "Calexico", "votes": 100}] ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Choice: <input type="text" name="choices-1-choice"></li>' '<li>Votes: <input type="number" name="choices-1-votes"></li>' '<li>Choice: <input type="text" name="choices-2-choice"></li>' '<li>Votes: <input type="number" name="choices-2-votes"></li>' '<li>Choice: <input type="text" name="choices-3-choice"></li>' '<li>Votes: <input type="number" name="choices-3-votes"></li>', ) # Retrieving an empty form works. Tt shows up in the form list. self.assertTrue(formset.empty_form.empty_permitted) self.assertHTMLEqual( formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice"></li> <li>Votes: <input type="number" name="choices-__prefix__-votes"></li>""", ) def test_formset_with_deletion(self): """ formset_factory's can_delete argument adds a boolean "delete" field to each form. When that boolean field is True, the form will be in formset.deleted_forms. """ ChoiceFormSet = formset_factory(Choice, can_delete=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Delete: <input type="checkbox" name="choices-0-DELETE"></li>' '<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">' "</li>" '<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>' '<li>Delete: <input type="checkbox" name="choices-1-DELETE"></li>' '<li>Choice: <input type="text" name="choices-2-choice"></li>' '<li>Votes: <input type="number" name="choices-2-votes"></li>' '<li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>', ) # To delete something, set that form's special delete field to 'on'. # Let's go ahead and delete Fergie. data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-DELETE": "", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-DELETE": "on", "choices-2-choice": "", "choices-2-votes": "", "choices-2-DELETE": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [ {"votes": 100, "DELETE": False, "choice": "Calexico"}, {"votes": 900, "DELETE": True, "choice": "Fergie"}, {}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{"votes": 900, "DELETE": True, "choice": "Fergie"}], ) def test_formset_with_deletion_remove_deletion_flag(self): """ If a form is filled with something and can_delete is also checked, that form's errors shouldn't make the entire formset invalid since it's going to be deleted. """ class CheckForm(Form): field = IntegerField(min_value=100) data = { "check-TOTAL_FORMS": "3", # the number of forms rendered "check-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "check-MAX_NUM_FORMS": "0", # max number of forms "check-0-field": "200", "check-0-DELETE": "", "check-1-field": "50", "check-1-DELETE": "on", "check-2-field": "", "check-2-DELETE": "", } CheckFormSet = formset_factory(CheckForm, can_delete=True) formset = CheckFormSet(data, prefix="check") self.assertTrue(formset.is_valid()) # If the deletion flag is removed, validation is enabled. data["check-1-DELETE"] = "" formset = CheckFormSet(data, prefix="check") self.assertFalse(formset.is_valid()) def test_formset_with_deletion_invalid_deleted_form(self): """ deleted_forms works on a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True) formset = FavoriteDrinkFormset( { "form-0-name": "", "form-0-DELETE": "on", # no name! "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_NUM_FORMS": 0, "form-MAX_NUM_FORMS": 1, } ) self.assertTrue(formset.is_valid()) self.assertEqual(formset._errors, []) self.assertEqual(len(formset.deleted_forms), 1) def test_formset_with_deletion_custom_widget(self): class DeletionAttributeFormSet(BaseFormSet): deletion_widget = HiddenInput class DeletionMethodFormSet(BaseFormSet): def get_deletion_widget(self): return HiddenInput(attrs={"class": "deletion"}) tests = [ (DeletionAttributeFormSet, '<input type="hidden" name="form-0-DELETE">'), ( DeletionMethodFormSet, '<input class="deletion" type="hidden" name="form-0-DELETE">', ), ] for formset_class, delete_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_delete=True, ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join([form.as_ul() for form in formset.forms]), ( f'<li>Title: <input type="text" name="form-0-title"></li>' f'<li>Pub date: <input type="text" name="form-0-pub_date">' f"{delete_html}</li>" ), ) def test_formsets_with_ordering(self): """ formset_factory's can_order argument adds an integer field to each form. When form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct order specified by the ordering fields. If a number is duplicated in the set of ordering fields, for instance form 0 and form 3 are both marked as 1, then the form index used as a secondary ordering criteria. In order to put something at the front of the list, you'd need to set its order to 0. """ ChoiceFormSet = formset_factory(Choice, can_order=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Order: <input type="number" name="choices-0-ORDER" value="1"></li>' '<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">' "</li>" '<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>' '<li>Order: <input type="number" name="choices-1-ORDER" value="2"></li>' '<li>Choice: <input type="text" name="choices-2-choice"></li>' '<li>Votes: <input type="number" name="choices-2-votes"></li>' '<li>Order: <input type="number" name="choices-2-ORDER"></li>', ) data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "0", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {"votes": 500, "ORDER": 0, "choice": "The Decemberists"}, {"votes": 100, "ORDER": 1, "choice": "Calexico"}, {"votes": 900, "ORDER": 2, "choice": "Fergie"}, ], ) def test_formsets_with_ordering_custom_widget(self): class OrderingAttributeFormSet(BaseFormSet): ordering_widget = HiddenInput class OrderingMethodFormSet(BaseFormSet): def get_ordering_widget(self): return HiddenInput(attrs={"class": "ordering"}) tests = ( (OrderingAttributeFormSet, '<input type="hidden" name="form-0-ORDER">'), ( OrderingMethodFormSet, '<input class="ordering" type="hidden" name="form-0-ORDER">', ), ) for formset_class, order_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_order=True ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), ( '<li>Title: <input type="text" name="form-0-title"></li>' '<li>Pub date: <input type="text" name="form-0-pub_date">' "%s</li>" % order_html ), ) def test_empty_ordered_fields(self): """ Ordering fields are allowed to be left blank. If they are left blank, they'll be sorted below everything else. """ data = { "choices-TOTAL_FORMS": "4", # the number of forms rendered "choices-INITIAL_FORMS": "3", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "", "choices-3-choice": "Basia Bulat", "choices-3-votes": "50", "choices-3-ORDER": "", } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {"votes": 100, "ORDER": 1, "choice": "Calexico"}, {"votes": 900, "ORDER": 2, "choice": "Fergie"}, {"votes": 500, "ORDER": None, "choice": "The Decemberists"}, {"votes": 50, "ORDER": None, "choice": "Basia Bulat"}, ], ) def test_ordering_blank_fieldsets(self): """Ordering works with blank fieldsets.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_formset_with_ordering_and_deletion(self): """FormSets with ordering + deletion.""" ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, {"choice": "The Decemberists", "votes": 500}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Order: <input type="number" name="choices-0-ORDER" value="1"></li>' '<li>Delete: <input type="checkbox" name="choices-0-DELETE"></li>' '<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">' "</li>" '<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>' '<li>Order: <input type="number" name="choices-1-ORDER" value="2"></li>' '<li>Delete: <input type="checkbox" name="choices-1-DELETE"></li>' '<li>Choice: <input type="text" name="choices-2-choice" ' 'value="The Decemberists"></li>' '<li>Votes: <input type="number" name="choices-2-votes" value="500"></li>' '<li>Order: <input type="number" name="choices-2-ORDER" value="3"></li>' '<li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>' '<li>Choice: <input type="text" name="choices-3-choice"></li>' '<li>Votes: <input type="number" name="choices-3-votes"></li>' '<li>Order: <input type="number" name="choices-3-ORDER"></li>' '<li>Delete: <input type="checkbox" name="choices-3-DELETE"></li>', ) # Let's delete Fergie, and put The Decemberists ahead of Calexico. data = { "choices-TOTAL_FORMS": "4", # the number of forms rendered "choices-INITIAL_FORMS": "3", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-0-DELETE": "", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-1-DELETE": "on", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "0", "choices-2-DELETE": "", "choices-3-choice": "", "choices-3-votes": "", "choices-3-ORDER": "", "choices-3-DELETE": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ { "votes": 500, "DELETE": False, "ORDER": 0, "choice": "The Decemberists", }, {"votes": 100, "DELETE": False, "ORDER": 1, "choice": "Calexico"}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{"votes": 900, "DELETE": True, "ORDER": 2, "choice": "Fergie"}], ) def test_invalid_deleted_form_with_ordering(self): """ Can get ordered_forms from a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory( form=FavoriteDrinkForm, can_delete=True, can_order=True ) formset = FavoriteDrinkFormset( { "form-0-name": "", "form-0-DELETE": "on", # no name! "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_NUM_FORMS": 0, "form-MAX_NUM_FORMS": 1, } ) self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_clean_hook(self): """ FormSets have a clean() hook for doing extra validation that isn't tied to any form. It follows the same pattern as the clean() hook on Forms. """ # Start out with a some duplicate data. data = { "drinks-TOTAL_FORMS": "2", # the number of forms rendered "drinks-INITIAL_FORMS": "0", # the number of forms with initial data "drinks-MIN_NUM_FORMS": "0", # min number of forms "drinks-MAX_NUM_FORMS": "0", # max number of forms "drinks-0-name": "Gin and Tonic", "drinks-1-name": "Gin and Tonic", } formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertFalse(formset.is_valid()) # Any errors raised by formset.clean() are available via the # formset.non_form_errors() method. for error in formset.non_form_errors(): self.assertEqual(str(error), "You may only specify a drink once.") # The valid case still works. data["drinks-1-name"] = "Bloody Mary" formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertTrue(formset.is_valid()) self.assertEqual(formset.non_form_errors(), []) def test_limiting_max_forms(self): """Limiting the maximum number of forms with max_num.""" # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the extra parameter. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div> <div><label for="id_form-2-name">Name:</label> <input type="text" name="form-2-name" id="id_form-2-name"></div>""", ) # If max_num is 0 then no form is rendered at all. LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=3, max_num=0 ) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_limited_max_forms_two(self): LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=5, max_num=2 ) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div>""", ) def test_limiting_extra_lest_than_max_num(self): """max_num has no effect when extra is less than max_num.""" LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=2 ) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div>""", ) def test_max_num_with_initial_data(self): # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the initial and extra # parameters. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Fernet and Coke"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div> """, ) def test_max_num_zero(self): """ If max_num is 0 then no form is rendered at all, regardless of extra, unless initial data is present. """ LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=0 ) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_max_num_zero_with_initial(self): # initial trumps max_num initial = [ {"name": "Fernet and Coke"}, {"name": "Bloody Mary"}, ] LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=0 ) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke"></div> <div><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></div> """, ) def test_more_initial_than_max_num(self): """ More initial forms than max_num results in all initial forms being displayed (but no extra forms). """ initial = [ {"name": "Gin Tonic"}, {"name": "Bloody Mary"}, {"name": "Jack and Coke"}, ] LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=2 ) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic"> </div> <div><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></div> <div><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke"></div> """, ) def test_default_absolute_max(self): # absolute_max defaults to 2 * DEFAULT_MAX_NUM if max_num is None. data = { "form-TOTAL_FORMS": 2001, "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = FavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) self.assertEqual(formset.absolute_max, 2000) def test_absolute_max(self): data = { "form-TOTAL_FORMS": "2001", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } AbsoluteMaxFavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, absolute_max=3000, ) formset = AbsoluteMaxFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), True) self.assertEqual(len(formset.forms), 2001) # absolute_max provides a hard limit. data["form-TOTAL_FORMS"] = "3001" formset = AbsoluteMaxFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 3000) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) def test_absolute_max_with_max_num(self): data = { "form-TOTAL_FORMS": "1001", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } LimitedFavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, max_num=30, absolute_max=1000, ) formset = LimitedFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 1000) self.assertEqual( formset.non_form_errors(), ["Please submit at most 30 forms."], ) def test_absolute_max_invalid(self): msg = "'absolute_max' must be greater or equal to 'max_num'." for max_num in [None, 31]: with self.subTest(max_num=max_num): with self.assertRaisesMessage(ValueError, msg): formset_factory(FavoriteDrinkForm, max_num=max_num, absolute_max=30) def test_more_initial_form_result_in_one(self): """ One form from initial and extra=3 with max_num=2 results in the one initial form and one extra. """ LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=3, max_num=2 ) formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name"> </div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div>""", ) def test_management_form_field_names(self): """The management form class has field names matching the constants.""" self.assertCountEqual( ManagementForm.base_fields, [ TOTAL_FORM_COUNT, INITIAL_FORM_COUNT, MIN_NUM_FORM_COUNT, MAX_NUM_FORM_COUNT, ], ) def test_management_form_prefix(self): """The management form has the correct prefix.""" formset = FavoriteDrinksFormSet() self.assertEqual(formset.management_form.prefix, "form") data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = FavoriteDrinksFormSet(data=data) self.assertEqual(formset.management_form.prefix, "form") formset = FavoriteDrinksFormSet(initial={}) self.assertEqual(formset.management_form.prefix, "form") def test_non_form_errors(self): data = { "drinks-TOTAL_FORMS": "2", # the number of forms rendered "drinks-INITIAL_FORMS": "0", # the number of forms with initial data "drinks-MIN_NUM_FORMS": "0", # min number of forms "drinks-MAX_NUM_FORMS": "0", # max number of forms "drinks-0-name": "Gin and Tonic", "drinks-1-name": "Gin and Tonic", } formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["You may only specify a drink once."] ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "You may only specify a drink once.</li></ul>", ) def test_formset_iteration(self): """Formset instances are iterable.""" ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # An iterated formset yields formset.forms. forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # A formset may be indexed to retrieve its forms. self.assertEqual(formset[0], forms[0]) with self.assertRaises(IndexError): formset[3] # Formsets can override the default iteration order class BaseReverseFormSet(BaseFormSet): def __iter__(self): return reversed(self.forms) def __getitem__(self, idx): return super().__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # __iter__() modifies the rendering order. # Compare forms from "reverse" formset with forms from original formset self.assertEqual(str(reverse_formset[0]), str(forms[-1])) self.assertEqual(str(reverse_formset[1]), str(forms[-2])) self.assertEqual(len(reverse_formset), len(forms)) def test_formset_nonzero(self): """A formsets without any forms evaluates as True.""" ChoiceFormset = formset_factory(Choice, extra=0) formset = ChoiceFormset() self.assertEqual(len(formset.forms), 0) self.assertTrue(formset) def test_formset_splitdatetimefield(self): """ Formset works with SplitDateTimeField(initial=datetime.datetime.now). """ class SplitDateTimeForm(Form): when = SplitDateTimeField(initial=datetime.datetime.now) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-when_0": "1904-06-16", "form-0-when_1": "15:51:33", } formset = SplitDateTimeFormSet(data) self.assertTrue(formset.is_valid()) def test_formset_error_class(self): """Formset's forms use the formset's error_class.""" class CustomErrorList(ErrorList): pass formset = FavoriteDrinksFormSet(error_class=CustomErrorList) self.assertEqual(formset.forms[0].error_class, CustomErrorList) def test_formset_calls_forms_is_valid(self): """Formsets call is_valid() on each form.""" class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True return super().is_valid() AnotherChoiceFormSet = formset_factory(AnotherChoice) data = { "choices-TOTAL_FORMS": "1", # number of forms rendered "choices-INITIAL_FORMS": "0", # number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", } formset = AnotherChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertTrue(all(form.is_valid_called for form in formset.forms)) def test_hard_limit_on_instantiated_forms(self): """A formset has a hard limit on the number of forms instantiated.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 2 ChoiceFormSet = formset_factory(Choice, max_num=1) # someone fiddles with the mgmt form data... formset = ChoiceFormSet( { "choices-TOTAL_FORMS": "4", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "4", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", "choices-2-choice": "Two", "choices-2-votes": "2", "choices-3-choice": "Three", "choices-3-votes": "3", }, prefix="choices", ) # But we still only instantiate 3 forms self.assertEqual(len(formset.forms), 3) # and the formset isn't valid self.assertFalse(formset.is_valid()) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_increase_hard_limit(self): """Can increase the built-in forms limit via a higher max_num.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 # for this form, we want a limit of 4 ChoiceFormSet = formset_factory(Choice, max_num=4) formset = ChoiceFormSet( { "choices-TOTAL_FORMS": "4", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "4", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", "choices-2-choice": "Two", "choices-2-votes": "2", "choices-3-choice": "Three", "choices-3-votes": "3", }, prefix="choices", ) # Four forms are instantiated and no exception is raised self.assertEqual(len(formset.forms), 4) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_non_form_errors_run_full_clean(self): """ If non_form_errors() is called without calling is_valid() first, it should ensure that full_clean() is called. """ class BaseCustomFormSet(BaseFormSet): def clean(self): raise ValidationError("This is a non-form error") ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIsInstance(formset.non_form_errors(), ErrorList) self.assertEqual(list(formset.non_form_errors()), ["This is a non-form error"]) def test_validate_max_ignores_forms_marked_for_deletion(self): class CheckForm(Form): field = IntegerField() data = { "check-TOTAL_FORMS": "2", "check-INITIAL_FORMS": "0", "check-MAX_NUM_FORMS": "1", "check-0-field": "200", "check-0-DELETE": "", "check-1-field": "50", "check-1-DELETE": "on", } CheckFormSet = formset_factory( CheckForm, max_num=1, validate_max=True, can_delete=True ) formset = CheckFormSet(data, prefix="check") self.assertTrue(formset.is_valid()) def test_formset_total_error_count(self): """A valid formset should have 0 total errors.""" data = [ # formset_data, expected error count ([("Calexico", "100")], 0), ([("Calexico", "")], 1), ([("", "invalid")], 2), ([("Calexico", "100"), ("Calexico", "")], 1), ([("Calexico", ""), ("Calexico", "")], 2), ] for formset_data, expected_error_count in data: formset = self.make_choiceformset(formset_data) self.assertEqual(formset.total_error_count(), expected_error_count) def test_formset_total_error_count_with_non_form_errors(self): data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.total_error_count(), 1) data["choices-1-votes"] = "" formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.total_error_count(), 2) def test_html_safe(self): formset = self.make_choiceformset() self.assertTrue(hasattr(formset, "__html__")) self.assertEqual(str(formset), formset.__html__()) def test_can_delete_extra_formset_forms(self): ChoiceFormFormset = formset_factory(form=Choice, can_delete=True, extra=2) formset = ChoiceFormFormset() self.assertEqual(len(formset), 2) self.assertIn("DELETE", formset.forms[0].fields) self.assertIn("DELETE", formset.forms[1].fields) def test_disable_delete_extra_formset_forms(self): ChoiceFormFormset = formset_factory( form=Choice, can_delete=True, can_delete_extra=False, extra=2, ) formset = ChoiceFormFormset() self.assertEqual(len(formset), 2) self.assertNotIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) formset = ChoiceFormFormset(initial=[{"choice": "Zero", "votes": "1"}]) self.assertEqual(len(formset), 3) self.assertIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) self.assertNotIn("DELETE", formset.forms[2].fields) formset = ChoiceFormFormset( data={ "form-0-choice": "Zero", "form-0-votes": "0", "form-0-DELETE": "on", "form-1-choice": "One", "form-1-votes": "1", "form-2-choice": "", "form-2-votes": "", "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "1", }, initial=[{"choice": "Zero", "votes": "1"}], ) self.assertEqual( formset.cleaned_data, [ {"choice": "Zero", "votes": 0, "DELETE": True}, {"choice": "One", "votes": 1}, {}, ], ) self.assertIs(formset._should_delete_form(formset.forms[0]), True) self.assertIs(formset._should_delete_form(formset.forms[1]), False) self.assertIs(formset._should_delete_form(formset.forms[2]), False) def test_template_name_uses_renderer_value(self): class CustomRenderer(TemplatesSetting): formset_template_name = "a/custom/formset/template.html" ChoiceFormSet = formset_factory(Choice, renderer=CustomRenderer) self.assertEqual( ChoiceFormSet().template_name, "a/custom/formset/template.html" ) def test_template_name_can_be_overridden(self): class CustomFormSet(BaseFormSet): template_name = "a/custom/formset/template.html" ChoiceFormSet = formset_factory(Choice, formset=CustomFormSet) self.assertEqual( ChoiceFormSet().template_name, "a/custom/formset/template.html" ) def test_custom_renderer(self): """ A custom renderer passed to a formset_factory() is passed to all forms and ErrorList. """ from django.forms.renderers import Jinja2 renderer = Jinja2() data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "", "choices-1-choice": "One", "choices-1-votes": "", } ChoiceFormSet = formset_factory(Choice, renderer=renderer) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.renderer, renderer) self.assertEqual(formset.forms[0].renderer, renderer) self.assertEqual(formset.management_form.renderer, renderer) self.assertEqual(formset.non_form_errors().renderer, renderer) self.assertEqual(formset.empty_form.renderer, renderer) def test_repr(self): valid_formset = self.make_choiceformset([("test", 1)]) valid_formset.full_clean() invalid_formset = self.make_choiceformset([("test", "")]) invalid_formset.full_clean() partially_invalid_formset = self.make_choiceformset( [("test", "1"), ("test", "")], ) partially_invalid_formset.full_clean() invalid_formset_non_form_errors_only = self.make_choiceformset( [("test", "")], formset_class=ChoiceFormsetWithNonFormError, ) invalid_formset_non_form_errors_only.full_clean() cases = [ ( self.make_choiceformset(), "<ChoiceFormSet: bound=False valid=Unknown total_forms=1>", ), ( self.make_choiceformset( formset_class=formset_factory(Choice, extra=10), ), "<ChoiceFormSet: bound=False valid=Unknown total_forms=10>", ), ( self.make_choiceformset([]), "<ChoiceFormSet: bound=True valid=Unknown total_forms=0>", ), ( self.make_choiceformset([("test", 1)]), "<ChoiceFormSet: bound=True valid=Unknown total_forms=1>", ), (valid_formset, "<ChoiceFormSet: bound=True valid=True total_forms=1>"), (invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=1>"), ( partially_invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=2>", ), ( invalid_formset_non_form_errors_only, "<ChoiceFormsetWithNonFormError: bound=True valid=False total_forms=1>", ), ] for formset, expected_repr in cases: with self.subTest(expected_repr=expected_repr): self.assertEqual(repr(formset), expected_repr) def test_repr_do_not_trigger_validation(self): formset = self.make_choiceformset([("test", 1)]) with mock.patch.object(formset, "full_clean") as mocked_full_clean: repr(formset) mocked_full_clean.assert_not_called() formset.is_valid() mocked_full_clean.assert_called() @jinja2_tests class Jinja2FormsFormsetTestCase(FormsFormsetTestCase): pass class FormsetAsTagTests(SimpleTestCase): def setUp(self): data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "choices-0-choice": "Calexico", "choices-0-votes": "100", } self.formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.management_form_html = ( '<input type="hidden" name="choices-TOTAL_FORMS" value="1">' '<input type="hidden" name="choices-INITIAL_FORMS" value="0">' '<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">' '<input type="hidden" name="choices-MAX_NUM_FORMS" value="0">' ) def test_as_table(self): self.assertHTMLEqual( self.formset.as_table(), self.management_form_html + ( "<tr><th>Choice:</th><td>" '<input type="text" name="choices-0-choice" value="Calexico"></td></tr>' "<tr><th>Votes:</th><td>" '<input type="number" name="choices-0-votes" value="100"></td></tr>' ), ) def test_as_p(self): self.assertHTMLEqual( self.formset.as_p(), self.management_form_html + ( "<p>Choice: " '<input type="text" name="choices-0-choice" value="Calexico"></p>' '<p>Votes: <input type="number" name="choices-0-votes" value="100"></p>' ), ) def test_as_ul(self): self.assertHTMLEqual( self.formset.as_ul(), self.management_form_html + ( "<li>Choice: " '<input type="text" name="choices-0-choice" value="Calexico"></li>' "<li>Votes: " '<input type="number" name="choices-0-votes" value="100"></li>' ), ) def test_as_div(self): self.assertHTMLEqual( self.formset.as_div(), self.management_form_html + ( "<div>Choice: " '<input type="text" name="choices-0-choice" value="Calexico"></div>' '<div>Votes: <input type="number" name="choices-0-votes" value="100">' "</div>" ), ) @jinja2_tests class Jinja2FormsetAsTagTests(FormsetAsTagTests): pass class ArticleForm(Form): title = CharField() pub_date = DateField() ArticleFormSet = formset_factory(ArticleForm) class TestIsBoundBehavior(SimpleTestCase): def test_no_data_error(self): formset = ArticleFormSet({}) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), [ "ManagementForm data is missing or has been tampered with. " "Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. " "You may need to file a bug report if the issue persists.", ], ) self.assertEqual(formset.errors, []) # Can still render the formset. self.assertHTMLEqual( str(formset), '<ul class="errorlist nonfield">' "<li>(Hidden field TOTAL_FORMS) This field is required.</li>" "<li>(Hidden field INITIAL_FORMS) This field is required.</li>" "</ul>" "<div>" '<input type="hidden" name="form-TOTAL_FORMS" id="id_form-TOTAL_FORMS">' '<input type="hidden" name="form-INITIAL_FORMS" id="id_form-INITIAL_FORMS">' '<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">' '<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">' "</div>\n", ) def test_management_form_invalid_data(self): data = { "form-TOTAL_FORMS": "two", "form-INITIAL_FORMS": "one", } formset = ArticleFormSet(data) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), [ "ManagementForm data is missing or has been tampered with. " "Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. " "You may need to file a bug report if the issue persists.", ], ) self.assertEqual(formset.errors, []) # Can still render the formset. self.assertHTMLEqual( str(formset), '<ul class="errorlist nonfield">' "<li>(Hidden field TOTAL_FORMS) Enter a whole number.</li>" "<li>(Hidden field INITIAL_FORMS) Enter a whole number.</li>" "</ul>" "<div>" '<input type="hidden" name="form-TOTAL_FORMS" value="two" ' 'id="id_form-TOTAL_FORMS">' '<input type="hidden" name="form-INITIAL_FORMS" value="one" ' 'id="id_form-INITIAL_FORMS">' '<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">' '<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">' "</div>\n", ) def test_customize_management_form_error(self): formset = ArticleFormSet( {}, error_messages={"missing_management_form": "customized"} ) self.assertIs(formset.is_valid(), False) self.assertEqual(formset.non_form_errors(), ["customized"]) self.assertEqual(formset.errors, []) def test_with_management_data_attrs_work_fine(self): data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", } formset = ArticleFormSet(data) self.assertEqual(0, formset.initial_form_count()) self.assertEqual(1, formset.total_form_count()) self.assertTrue(formset.is_bound) self.assertTrue(formset.forms[0].is_bound) self.assertTrue(formset.is_valid()) self.assertTrue(formset.forms[0].is_valid()) self.assertEqual([{}], formset.cleaned_data) def test_form_errors_are_caught_by_formset(self): data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-0-title": "Test", "form-0-pub_date": "1904-06-16", "form-1-title": "Test", "form-1-pub_date": "", # <-- this date is missing but required } formset = ArticleFormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( [{}, {"pub_date": ["This field is required."]}], formset.errors ) def test_empty_forms_are_unbound(self): data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-title": "Test", "form-0-pub_date": "1904-06-16", } unbound_formset = ArticleFormSet() bound_formset = ArticleFormSet(data) empty_forms = [unbound_formset.empty_form, bound_formset.empty_form] # Empty forms should be unbound self.assertFalse(empty_forms[0].is_bound) self.assertFalse(empty_forms[1].is_bound) # The empty forms should be equal. self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) @jinja2_tests class TestIsBoundBehavior(TestIsBoundBehavior): pass class TestEmptyFormSet(SimpleTestCase): def test_empty_formset_is_valid(self): """An empty formset still calls clean()""" class EmptyFsetWontValidate(BaseFormSet): def clean(self): raise ValidationError("Clean method called") EmptyFsetWontValidateFormset = formset_factory( FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate ) formset = EmptyFsetWontValidateFormset( data={"form-INITIAL_FORMS": "0", "form-TOTAL_FORMS": "0"}, prefix="form", ) formset2 = EmptyFsetWontValidateFormset( data={ "form-INITIAL_FORMS": "0", "form-TOTAL_FORMS": "1", "form-0-name": "bah", }, prefix="form", ) self.assertFalse(formset.is_valid()) self.assertFalse(formset2.is_valid()) def test_empty_formset_media(self): """Media is available on empty formset.""" class MediaForm(Form): class Media: js = ("some-file.js",) self.assertIn("some-file.js", str(formset_factory(MediaForm, extra=0)().media)) def test_empty_formset_is_multipart(self): """is_multipart() works with an empty formset.""" class FileForm(Form): file = FileField() self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart()) class AllValidTests(SimpleTestCase): def test_valid(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix="choices") formset2 = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIs(all_valid((formset1, formset2)), True) expected_errors = [{}, {}] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors) def test_invalid(self): """all_valid() validates all forms, even when some are invalid.""" data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "", "choices-1-choice": "One", "choices-1-votes": "", } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix="choices") formset2 = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIs(all_valid((formset1, formset2)), False) expected_errors = [ {"votes": ["This field is required."]}, {"votes": ["This field is required."]}, ] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors)
d147c773f5704ae58693d4de9eb9bc2b75b01d308596424dc187d0f705af8082
import os import unittest from django.forms.renderers import ( BaseRenderer, DjangoDivFormRenderer, DjangoTemplates, Jinja2, Jinja2DivFormRenderer, TemplatesSetting, ) from django.test import SimpleTestCase from django.utils.deprecation import RemovedInDjango60Warning try: import jinja2 except ImportError: jinja2 = None class SharedTests: expected_widget_dir = "templates" def test_installed_apps_template_found(self): """Can find a custom template in INSTALLED_APPS.""" renderer = self.renderer() # Found because forms_tests is . tpl = renderer.get_template("forms_tests/custom_widget.html") expected_path = os.path.abspath( os.path.join( os.path.dirname(__file__), "..", self.expected_widget_dir + "/forms_tests/custom_widget.html", ) ) self.assertEqual(tpl.origin.name, expected_path) class BaseTemplateRendererTests(SimpleTestCase): def test_get_renderer(self): with self.assertRaisesMessage( NotImplementedError, "subclasses must implement get_template()" ): BaseRenderer().get_template("") class DjangoTemplatesTests(SharedTests, SimpleTestCase): renderer = DjangoTemplates @unittest.skipIf(jinja2 is None, "jinja2 required") class Jinja2Tests(SharedTests, SimpleTestCase): renderer = Jinja2 expected_widget_dir = "jinja2" class TemplatesSettingTests(SharedTests, SimpleTestCase): renderer = TemplatesSetting class DeprecationTests(SimpleTestCase): def test_django_div_renderer_warning(self): msg = ( "The DjangoDivFormRenderer transitional form renderer is deprecated. Use " "DjangoTemplates instead." ) with self.assertRaisesMessage(RemovedInDjango60Warning, msg): DjangoDivFormRenderer() def test_jinja2_div_renderer_warning(self): msg = ( "The Jinja2DivFormRenderer transitional form renderer is deprecated. Use " "Jinja2 instead." ) with self.assertRaisesMessage(RemovedInDjango60Warning, msg): Jinja2DivFormRenderer()
5443e4f8d70ba61d9351bcdb8397853a8a4aab2138f719f236518c918991a76f
from datetime import date, datetime, time from django import forms from django.core.exceptions import ValidationError from django.test import SimpleTestCase, override_settings from django.utils import translation from django.utils.translation import activate, deactivate class LocalizedTimeTests(SimpleTestCase): def setUp(self): # nl/formats.py has customized TIME_INPUT_FORMATS: # ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M'] activate("nl") def tearDown(self): deactivate() def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid, but non-default format, get a parsed result result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") # ISO formats are accepted, even if not specified in formats.py result = f.clean("13:30:05.000155") self.assertEqual(result, time(13, 30, 5, 155)) def test_localized_timeField(self): "Localized TimeFields act as unlocalized widgets" f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField_with_inputformat(self): """ Localized TimeFields with manually specified input formats can accept those formats. """ f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") @translation.override(None) @override_settings(TIME_INPUT_FORMATS=["%I:%M:%S %p", "%I:%M %p"]) class CustomTimeInputFormatsTests(SimpleTestCase): def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid, but non-default format, get a parsed result result = f.clean("1:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") def test_localized_timeField(self): "Localized TimeFields act as unlocalized widgets" f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("01:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") def test_localized_timeField_with_inputformat(self): """ Localized TimeFields with manually specified input formats can accept those formats. """ f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM") class SimpleTimeFormatTests(SimpleTestCase): def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid, but non-default format, get a parsed result result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField(self): "Localized TimeFields in a non-localized environment act as unlocalized widgets" f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_timeField_with_inputformat(self): "TimeFields with manually specified input formats can accept those formats" f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("1:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") def test_localized_timeField_with_inputformat(self): """ Localized TimeFields with manually specified input formats can accept those formats. """ f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result result = f.clean("1:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "13:30:00") class LocalizedDateTests(SimpleTestCase): def setUp(self): activate("de") def tearDown(self): deactivate() def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("21/12/2010") # ISO formats are accepted, even if not specified in formats.py self.assertEqual(f.clean("2010-12-21"), date(2010, 12, 21)) # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean("21.12.10") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField(self): "Localized DateFields act as unlocalized widgets" f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.10") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21") with self.assertRaises(ValidationError): f.clean("21/12/2010") with self.assertRaises(ValidationError): f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField_with_inputformat(self): """ Localized DateFields with manually specified input formats can accept those formats. """ f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21") with self.assertRaises(ValidationError): f.clean("21/12/2010") with self.assertRaises(ValidationError): f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") @translation.override(None) @override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y", "%d-%m-%Y"]) class CustomDateInputFormatsTests(SimpleTestCase): def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField(self): "Localized DateFields act as unlocalized widgets" f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("21.12.2010") with self.assertRaises(ValidationError): f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") def test_localized_dateField_with_inputformat(self): """ Localized DateFields with manually specified input formats can accept those formats. """ f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("21.12.2010") with self.assertRaises(ValidationError): f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010") class SimpleDateFormatTests(SimpleTestCase): def test_dateField(self): "DateFields can parse dates in the default format" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("2010-12-21") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean("12/21/2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") def test_localized_dateField(self): "Localized DateFields in a non-localized environment act as unlocalized widgets" f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("2010-12-21") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("12/21/2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") def test_dateField_with_inputformat(self): "DateFields with manually specified input formats can accept those formats" f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") def test_localized_dateField_with_inputformat(self): """ Localized DateFields with manually specified input formats can accept those formats. """ f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21") class LocalizedDateTimeTests(SimpleTestCase): def setUp(self): activate("de") def tearDown(self): deactivate() def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM 21/12/2010") # ISO formats are accepted, even if not specified in formats.py self.assertEqual( f.clean("2010-12-21 13:30:05"), datetime(2010, 12, 21, 13, 30, 5) ) # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean("21.12.2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_localized_dateTimeField(self): "Localized DateTimeFields act as unlocalized widgets" f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("1:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("21.12.2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010-12-21 13:30:05 13:30:05") with self.assertRaises(ValidationError): f.clean("1:30:05 PM 21/12/2010") with self.assertRaises(ValidationError): f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("13.30.05 12.21.2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("13.30 12-21-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") def test_localized_dateTimeField_with_inputformat(self): """ Localized DateTimeFields with manually specified input formats can accept those formats. """ f = forms.DateTimeField( input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") with self.assertRaises(ValidationError): f.clean("1:30:05 PM 21/12/2010") with self.assertRaises(ValidationError): f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("13.30.05 12.21.2010") self.assertEqual(datetime(2010, 12, 21, 13, 30, 5), result) # ISO format is always valid. self.assertEqual( f.clean("2010-12-21 13:30:05"), datetime(2010, 12, 21, 13, 30, 5), ) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("13.30 12-21-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "21.12.2010 13:30:00") @translation.override(None) @override_settings(DATETIME_INPUT_FORMATS=["%I:%M:%S %p %d/%m/%Y", "%I:%M %p %d-%m-%Y"]) class CustomDateTimeInputFormatsTests(SimpleTestCase): def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("1:30:05 PM 21/12/2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_localized_dateTimeField(self): "Localized DateTimeFields act as unlocalized widgets" f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("1:30:05 PM 21/12/2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05 21.12.2010") with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("12.21.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean("12-21-2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") def test_localized_dateTimeField_with_inputformat(self): """ Localized DateTimeFields with manually specified input formats can accept those formats. """ f = forms.DateTimeField( input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05 21.12.2010") with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("12.21.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result result = f.clean("12-21-2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") class SimpleDateTimeFormatTests(SimpleTestCase): def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("2010-12-21 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid, but non-default format, get a parsed result result = f.clean("12/21/2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") def test_localized_dateTimeField(self): """ Localized DateTimeFields in a non-localized environment act as unlocalized widgets. """ f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result result = f.clean("2010-12-21 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("12/21/2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" f = forms.DateTimeField( input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"] ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("1:30:05 PM 21.12.2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:00") def test_localized_dateTimeField_with_inputformat(self): """ Localized DateTimeFields with manually specified input formats can accept those formats. """ f = forms.DateTimeField( input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("1:30:05 PM 21.12.2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format text = f.widget.format_value(result) self.assertEqual(text, "2010-12-21 13:30:00")
906d6d538bd7d2649b3e75a9e0e571e7ec31c0831f8f8fab268d1cdb13cdf658
from django.contrib.admin.tests import AdminSeleniumTestCase from django.test import override_settings from django.urls import reverse from ..models import Article @override_settings(ROOT_URLCONF="forms_tests.urls") class LiveWidgetTests(AdminSeleniumTestCase): available_apps = ["forms_tests"] + AdminSeleniumTestCase.available_apps def test_textarea_trailing_newlines(self): """ A roundtrip on a ModelForm doesn't alter the TextField value """ from selenium.webdriver.common.by import By article = Article.objects.create(content="\nTst\n") self.selenium.get( self.live_server_url + reverse("article_form", args=[article.pk]) ) self.selenium.find_element(By.ID, "submit").click() article = Article.objects.get(pk=article.pk) self.assertEqual(article.content, "\r\nTst\r\n")
a62ed90f7fbea46bb3328b8c0e85184440884bbeabc981292a01905e4d6c8e1f
from django.forms import CharField, Form, Media, MultiWidget, TextInput from django.template import Context, Template from django.templatetags.static import static from django.test import SimpleTestCase, override_settings from django.utils.html import format_html, html_safe @override_settings( STATIC_URL="http://media.example.com/static/", ) class FormsMediaTestCase(SimpleTestCase): """Tests for the media handling on widgets and forms""" def test_construction(self): # Check construction of media objects m = Media( css={"all": ("path/to/css1", "/path/to/css2")}, js=( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ), ) self.assertEqual( str(m), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) self.assertEqual( repr(m), "Media(css={'all': ['path/to/css1', '/path/to/css2']}, " "js=['/path/to/js1', 'http://media.other.com/path/to/js2', " "'https://secure.other.com/path/to/js3'])", ) class Foo: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) m3 = Media(Foo) self.assertEqual( str(m3), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # A widget can exist without a media definition class MyWidget(TextInput): pass w = MyWidget() self.assertEqual(str(w.media), "") def test_media_dsl(self): ############################################################### # DSL Class-based media definitions ############################################################### # A widget can define media if it needs to. # Any absolute path will be preserved; relative paths are combined # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) w1 = MyWidget1() self.assertEqual( str(w1.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # Media objects can be interrogated by media type self.assertEqual( str(w1.media["css"]), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">', ) self.assertEqual( str(w1.media["js"]), """<script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script src="https://secure.other.com/path/to/js3"></script>""", ) def test_combine_media(self): # Media objects can be combined. Any given media resource will appear only # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget2(TextInput): class Media: css = {"all": ("/path/to/css2", "/path/to/css3")} js = ("/path/to/js1", "/path/to/js4") class MyWidget3(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css3")} js = ("/path/to/js1", "/path/to/js4") w1 = MyWidget1() w2 = MyWidget2() w3 = MyWidget3() self.assertEqual( str(w1.media + w2.media + w3.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # media addition hasn't affected the original objects self.assertEqual( str(w1.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # Regression check for #12879: specifying the same CSS or JS file # multiple times in a single Media instance should result in that file # only being included once. class MyWidget4(TextInput): class Media: css = {"all": ("/path/to/css1", "/path/to/css1")} js = ("/path/to/js1", "/path/to/js1") w4 = MyWidget4() self.assertEqual( str(w4.media), """<link href="/path/to/css1" media="all" rel="stylesheet"> <script src="/path/to/js1"></script>""", ) def test_media_deduplication(self): # A deduplication test applied directly to a Media object, to confirm # that the deduplication doesn't only happen at the point of merging # two or more media objects. media = Media( css={"all": ("/path/to/css1", "/path/to/css1")}, js=("/path/to/js1", "/path/to/js1"), ) self.assertEqual( str(media), """<link href="/path/to/css1" media="all" rel="stylesheet"> <script src="/path/to/js1"></script>""", ) def test_media_property(self): ############################################################### # Property-based media definitions ############################################################### # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): return Media(css={"all": ("/some/path",)}, js=("/some/js",)) media = property(_media) w4 = MyWidget4() self.assertEqual( str(w4.media), """<link href="/some/path" media="all" rel="stylesheet"> <script src="/some/js"></script>""", ) # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): return super().media + Media( css={"all": ("/other/path",)}, js=("/other/js",) ) media = property(_media) w5 = MyWidget5() self.assertEqual( str(w5.media), """<link href="/some/path" media="all" rel="stylesheet"> <link href="/other/path" media="all" rel="stylesheet"> <script src="/some/js"></script> <script src="/other/js"></script>""", ) def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget6(MyWidget1): def _media(self): return super().media + Media( css={"all": ("/other/path",)}, js=("/other/js",) ) media = property(_media) w6 = MyWidget6() self.assertEqual( str(w6.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/other/path" media="all" rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="/other/js"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) def test_media_inheritance(self): ############################################################### # Inheritance of media ############################################################### # If a widget extends another but provides no media definition, it # inherits the parent widget's media. class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget7(MyWidget1): pass w7 = MyWidget7() self.assertEqual( str(w7.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # If a widget extends another but defines media, it extends the parent # widget's media by default. class MyWidget8(MyWidget1): class Media: css = {"all": ("/path/to/css3", "path/to/css1")} js = ("/path/to/js1", "/path/to/js4") w8 = MyWidget8() self.assertEqual( str(w8.media), """<link href="/path/to/css3" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script src="/path/to/js4"></script> <script src="https://secure.other.com/path/to/js3"></script>""", ) def test_media_inheritance_from_property(self): # If a widget extends another but defines media, it extends the parents # widget's media, even if the parent defined media using a property. class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget4(TextInput): def _media(self): return Media(css={"all": ("/some/path",)}, js=("/some/js",)) media = property(_media) class MyWidget9(MyWidget4): class Media: css = {"all": ("/other/path",)} js = ("/other/js",) w9 = MyWidget9() self.assertEqual( str(w9.media), """<link href="/some/path" media="all" rel="stylesheet"> <link href="/other/path" media="all" rel="stylesheet"> <script src="/some/js"></script> <script src="/other/js"></script>""", ) # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False css = {"all": ("/path/to/css3", "path/to/css1")} js = ("/path/to/js1", "/path/to/js4") w10 = MyWidget10() self.assertEqual( str(w10.media), """<link href="/path/to/css3" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="/path/to/js4"></script>""", ) def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying # 'extend=True'. class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget11(MyWidget1): class Media: extend = True css = {"all": ("/path/to/css3", "path/to/css1")} js = ("/path/to/js1", "/path/to/js4") w11 = MyWidget11() self.assertEqual( str(w11.media), """<link href="/path/to/css3" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="http://media.other.com/path/to/js2"></script> <script src="/path/to/js4"></script> <script src="https://secure.other.com/path/to/js3"></script>""", ) def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying # extend as a tuple. class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget12(MyWidget1): class Media: extend = ("css",) css = {"all": ("/path/to/css3", "path/to/css1")} js = ("/path/to/js1", "/path/to/js4") w12 = MyWidget12() self.assertEqual( str(w12.media), """<link href="/path/to/css3" media="all" rel="stylesheet"> <link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet"> <link href="/path/to/css2" media="all" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="/path/to/js4"></script>""", ) def test_multi_media(self): ############################################################### # Multi-media handling for CSS ############################################################### # A widget can define CSS media for multiple output media types class MultimediaWidget(TextInput): class Media: css = { "screen, print": ("/file1", "/file2"), "screen": ("/file3",), "print": ("/file4",), } js = ("/path/to/js1", "/path/to/js4") multimedia = MultimediaWidget() self.assertEqual( str(multimedia.media), """<link href="/file4" media="print" rel="stylesheet"> <link href="/file3" media="screen" rel="stylesheet"> <link href="/file1" media="screen, print" rel="stylesheet"> <link href="/file2" media="screen, print" rel="stylesheet"> <script src="/path/to/js1"></script> <script src="/path/to/js4"></script>""", ) def test_multi_widget(self): ############################################################### # Multiwidget media handling ############################################################### class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget2(TextInput): class Media: css = {"all": ("/path/to/css2", "/path/to/css3")} js = ("/path/to/js1", "/path/to/js4") class MyWidget3(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css3")} js = ("/path/to/js1", "/path/to/js4") # MultiWidgets have a default media definition that gets all the # media from the component widgets class MyMultiWidget(MultiWidget): def __init__(self, attrs=None): widgets = [MyWidget1, MyWidget2, MyWidget3] super().__init__(widgets, attrs) mymulti = MyMultiWidget() self.assertEqual( str(mymulti.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) def test_form_media(self): ############################################################### # Media processing for forms ############################################################### class MyWidget1(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", ) class MyWidget2(TextInput): class Media: css = {"all": ("/path/to/css2", "/path/to/css3")} js = ("/path/to/js1", "/path/to/js4") class MyWidget3(TextInput): class Media: css = {"all": ("path/to/css1", "/path/to/css3")} js = ("/path/to/js1", "/path/to/js4") # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) f1 = MyForm() self.assertEqual( str(f1.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) f2 = AnotherForm() self.assertEqual( str(f1.media + f2.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # Forms can also define media, following the same rules as widgets. class FormWithMedia(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) class Media: js = ("/some/form/javascript",) css = {"all": ("/some/form/css",)} f3 = FormWithMedia() self.assertEqual( str(f3.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/some/form/css" media="all" rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="/some/form/javascript"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>', ) # Media works in templates self.assertEqual( Template("{{ form.media.js }}{{ form.media.css }}").render( Context({"form": f3}) ), '<script src="/path/to/js1"></script>\n' '<script src="/some/form/javascript"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="/path/to/js4"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>' '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/some/form/css" media="all" rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">', ) def test_html_safe(self): media = Media(css={"all": ["/path/to/css"]}, js=["/path/to/js"]) self.assertTrue(hasattr(Media, "__html__")) self.assertEqual(str(media), media.__html__()) def test_merge(self): test_values = ( (([1, 2], [3, 4]), [1, 3, 2, 4]), (([1, 2], [2, 3]), [1, 2, 3]), (([2, 3], [1, 2]), [1, 2, 3]), (([1, 3], [2, 3]), [1, 2, 3]), (([1, 2], [1, 3]), [1, 2, 3]), (([1, 2], [3, 2]), [1, 3, 2]), (([1, 2], [1, 2]), [1, 2]), ( [[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], [1, 5, 8, 2, 6, 3, 7, 9], ), ((), []), (([1, 2],), [1, 2]), ) for lists, expected in test_values: with self.subTest(lists=lists): self.assertEqual(Media.merge(*lists), expected) def test_merge_warning(self): msg = "Detected duplicate Media files in an opposite order: [1, 2], [2, 1]" with self.assertWarnsMessage(RuntimeWarning, msg): self.assertEqual(Media.merge([1, 2], [2, 1], None), [1, 2]) def test_merge_js_three_way(self): """ The relative order of scripts is preserved in a three-way merge. """ widget1 = Media(js=["color-picker.js"]) widget2 = Media(js=["text-editor.js"]) widget3 = Media( js=["text-editor.js", "text-editor-extras.js", "color-picker.js"] ) merged = widget1 + widget2 + widget3 self.assertEqual( merged._js, ["text-editor.js", "text-editor-extras.js", "color-picker.js"] ) def test_merge_js_three_way2(self): # The merge prefers to place 'c' before 'b' and 'g' before 'h' to # preserve the original order. The preference 'c'->'b' is overridden by # widget3's media, but 'g'->'h' survives in the final ordering. widget1 = Media(js=["a", "c", "f", "g", "k"]) widget2 = Media(js=["a", "b", "f", "h", "k"]) widget3 = Media(js=["b", "c", "f", "k"]) merged = widget1 + widget2 + widget3 self.assertEqual(merged._js, ["a", "b", "c", "f", "g", "h", "k"]) def test_merge_css_three_way(self): widget1 = Media(css={"screen": ["c.css"], "all": ["d.css", "e.css"]}) widget2 = Media(css={"screen": ["a.css"]}) widget3 = Media(css={"screen": ["a.css", "b.css", "c.css"], "all": ["e.css"]}) widget4 = Media(css={"all": ["d.css", "e.css"], "screen": ["c.css"]}) merged = widget1 + widget2 # c.css comes before a.css because widget1 + widget2 establishes this # order. self.assertEqual( merged._css, {"screen": ["c.css", "a.css"], "all": ["d.css", "e.css"]} ) merged += widget3 # widget3 contains an explicit ordering of c.css and a.css. self.assertEqual( merged._css, {"screen": ["a.css", "b.css", "c.css"], "all": ["d.css", "e.css"]}, ) # Media ordering does not matter. merged = widget1 + widget4 self.assertEqual(merged._css, {"screen": ["c.css"], "all": ["d.css", "e.css"]}) def test_add_js_deduplication(self): widget1 = Media(js=["a", "b", "c"]) widget2 = Media(js=["a", "b"]) widget3 = Media(js=["a", "c", "b"]) merged = widget1 + widget1 self.assertEqual(merged._js_lists, [["a", "b", "c"]]) self.assertEqual(merged._js, ["a", "b", "c"]) merged = widget1 + widget2 self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "b"]]) self.assertEqual(merged._js, ["a", "b", "c"]) # Lists with items in a different order are preserved when added. merged = widget1 + widget3 self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "c", "b"]]) msg = ( "Detected duplicate Media files in an opposite order: " "['a', 'b', 'c'], ['a', 'c', 'b']" ) with self.assertWarnsMessage(RuntimeWarning, msg): merged._js def test_add_css_deduplication(self): widget1 = Media(css={"screen": ["a.css"], "all": ["b.css"]}) widget2 = Media(css={"screen": ["c.css"]}) widget3 = Media(css={"screen": ["a.css"], "all": ["b.css", "c.css"]}) widget4 = Media(css={"screen": ["a.css"], "all": ["c.css", "b.css"]}) merged = widget1 + widget1 self.assertEqual(merged._css_lists, [{"screen": ["a.css"], "all": ["b.css"]}]) self.assertEqual(merged._css, {"screen": ["a.css"], "all": ["b.css"]}) merged = widget1 + widget2 self.assertEqual( merged._css_lists, [ {"screen": ["a.css"], "all": ["b.css"]}, {"screen": ["c.css"]}, ], ) self.assertEqual(merged._css, {"screen": ["a.css", "c.css"], "all": ["b.css"]}) merged = widget3 + widget4 # Ordering within lists is preserved. self.assertEqual( merged._css_lists, [ {"screen": ["a.css"], "all": ["b.css", "c.css"]}, {"screen": ["a.css"], "all": ["c.css", "b.css"]}, ], ) msg = ( "Detected duplicate Media files in an opposite order: " "['b.css', 'c.css'], ['c.css', 'b.css']" ) with self.assertWarnsMessage(RuntimeWarning, msg): merged._css def test_add_empty(self): media = Media(css={"screen": ["a.css"]}, js=["a"]) empty_media = Media() merged = media + empty_media self.assertEqual(merged._css_lists, [{"screen": ["a.css"]}]) self.assertEqual(merged._js_lists, [["a"]]) @html_safe class Asset: def __init__(self, path): self.path = path def __eq__(self, other): return (self.__class__ == other.__class__ and self.path == other.path) or ( other.__class__ == str and self.path == other ) def __hash__(self): return hash(self.path) def __str__(self): return self.absolute_path(self.path) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __repr__(self): return f"{self.path!r}" class CSS(Asset): def __init__(self, path, medium): super().__init__(path) self.medium = medium def __str__(self): path = super().__str__() return format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), self.medium, ) class JS(Asset): def __init__(self, path, integrity=None): super().__init__(path) self.integrity = integrity or "" def __str__(self, integrity=None): path = super().__str__() template = '<script src="{}"%s></script>' % ( ' integrity="{}"' if self.integrity else "{}" ) return format_html(template, self.absolute_path(path), self.integrity) @override_settings( STATIC_URL="http://media.example.com/static/", ) class FormsMediaObjectTestCase(SimpleTestCase): """Media handling when media are objects instead of raw strings.""" def test_construction(self): m = Media( css={"all": (CSS("path/to/css1", "all"), CSS("/path/to/css2", "all"))}, js=( JS("/path/to/js1"), JS("http://media.other.com/path/to/js2"), JS( "https://secure.other.com/path/to/js3", integrity="9d947b87fdeb25030d56d01f7aa75800", ), ), ) self.assertEqual( str(m), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3" ' 'integrity="9d947b87fdeb25030d56d01f7aa75800"></script>', ) self.assertEqual( repr(m), "Media(css={'all': ['path/to/css1', '/path/to/css2']}, " "js=['/path/to/js1', 'http://media.other.com/path/to/js2', " "'https://secure.other.com/path/to/js3'])", ) def test_simplest_class(self): @html_safe class SimpleJS: """The simplest possible asset class.""" def __str__(self): return '<script src="https://example.org/asset.js" rel="stylesheet">' m = Media(js=(SimpleJS(),)) self.assertEqual( str(m), '<script src="https://example.org/asset.js" rel="stylesheet">', ) def test_combine_media(self): class MyWidget1(TextInput): class Media: css = {"all": (CSS("path/to/css1", "all"), "/path/to/css2")} js = ( "/path/to/js1", "http://media.other.com/path/to/js2", "https://secure.other.com/path/to/js3", JS("/path/to/js4", integrity="9d947b87fdeb25030d56d01f7aa75800"), ) class MyWidget2(TextInput): class Media: css = {"all": (CSS("/path/to/css2", "all"), "/path/to/css3")} js = (JS("/path/to/js1"), "/path/to/js4") w1 = MyWidget1() w2 = MyWidget2() self.assertEqual( str(w1.media + w2.media), '<link href="http://media.example.com/static/path/to/css1" media="all" ' 'rel="stylesheet">\n' '<link href="/path/to/css2" media="all" rel="stylesheet">\n' '<link href="/path/to/css3" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>\n' '<script src="http://media.other.com/path/to/js2"></script>\n' '<script src="https://secure.other.com/path/to/js3"></script>\n' '<script src="/path/to/js4" integrity="9d947b87fdeb25030d56d01f7aa75800">' "</script>", ) def test_media_deduplication(self): # The deduplication doesn't only happen at the point of merging two or # more media objects. media = Media( css={ "all": ( CSS("/path/to/css1", "all"), CSS("/path/to/css1", "all"), "/path/to/css1", ) }, js=(JS("/path/to/js1"), JS("/path/to/js1"), "/path/to/js1"), ) self.assertEqual( str(media), '<link href="/path/to/css1" media="all" rel="stylesheet">\n' '<script src="/path/to/js1"></script>', )
8849629372b059e9c812f0df513cdd1b1b654e4daed5209910ed2b11d04f8a05
import copy import datetime import json import uuid from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import MaxValueValidator, RegexValidator from django.forms import ( BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, FileField, FileInput, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, MultiWidget, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, forms, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.datastructures import MultiValueDict from django.utils.safestring import mark_safe from . import jinja2_tests class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")], widget=RadioSelect) class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class PersonNew(Form): first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"})) last_name = CharField() birthday = DateField() class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) class MultiValueDictLike(dict): def getlist(self, key): return [self[key]] class FormsTestCase(SimpleTestCase): # A Form is a collection of Fields. It knows how to validate a set of data and it # knows how to render itself in a couple of default ways (e.g., an HTML table). # You can pass it data in __init__(), as a dictionary. def test_form(self): # Pass a dictionary to a Form's __init__(). p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertIsInstance(p.errors, dict) self.assertTrue(p.is_valid()) self.assertHTMLEqual(p.errors.as_ul(), "") self.assertEqual(p.errors.as_text(), "") self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>", ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>", ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) msg = ( "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, " "first_name, last_name." ) with self.assertRaisesMessage(KeyError, msg): p["nonexistentfield"] form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertHTMLEqual( "\n".join(form_output), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>" '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>" '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual( form_output, [ ["First name", "John"], ["Last name", "Lennon"], ["Birthday", "1940-10-9"], ], ) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) def test_empty_dict(self): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) def test_empty_querydict_args(self): data = QueryDict() files = QueryDict() p = Person(data, files) self.assertIs(p.data, data) self.assertIs(p.files, files) def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, # the Form will be considered unbound and won't do any validation. Form.errors # will be an empty dictionary *but* Form.is_valid() will return False. p = Person() self.assertFalse(p.is_bound) self.assertEqual(p.errors, {}) self.assertFalse(p.is_valid()) with self.assertRaises(AttributeError): p.cleaned_data self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) def test_unicode_values(self): # Unicode values are handled properly. p = Person( { "first_name": "John", "last_name": "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111", "birthday": "1940-10-9", } ) self.assertHTMLEqual( p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td>' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></td></tr>\n" '<tr><th><label for="id_last_name">Last name:</label>' '</th><td><input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"' 'id="id_last_name" required></td></tr>\n' '<tr><th><label for="id_birthday">Birthday:</label></th><td>' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></td></tr>", ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></li>\n" '<li><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></li>\n' '<li><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></li>", ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></p>\n" '<p><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></p>\n' '<p><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></p>", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<input type="text" name="first_name" value="John" id="id_first_name" ' 'required></div><div><label for="id_last_name">Last name:</label>' '<input type="text" name="last_name"' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" value="1940-10-9" ' 'id="id_birthday" required></div>', ) p = Person({"last_name": "Lennon"}) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual( p.errors, { "birthday": ["This field is required."], "first_name": ["This field is required."], }, ) self.assertEqual(p.cleaned_data, {"last_name": "Lennon"}) self.assertEqual(p["first_name"].errors, ["This field is required."]) self.assertHTMLEqual( p["first_name"].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>', ) self.assertEqual(p["first_name"].errors.as_text(), "* This field is required.") p = Person() self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" id="id_first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" id="id_last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" id="id_birthday" required>', ) def test_cleaned_data_only_fields(self): # cleaned_data will always *only* contain a key for fields defined in the # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. data = { "first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9", "extra1": "hello", "extra2": "hello", } p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) def test_optional_data(self): # cleaned_data will include a key and value for *all* fields defined in # the Form, even if the Form's data didn't include a value for fields # that are not required. In this example, the data dictionary doesn't # include a value for the "nick_name" field, but cleaned_data includes # it. For CharFields, it's set to the empty string. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() nick_name = CharField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["nick_name"], "") self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") # For DateFields, it's set to None. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() birth_date = DateField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertIsNone(f.cleaned_data["birth_date"]) self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form # element. If it's a string that contains '%s', Django will use that as # a format string into which the field's name will be inserted. It will # also put a <label> around the human-readable labels for a field. p = Person(auto_id="%s_id") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td> <input type="text" name="first_name" id="first_name_id" required></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td> <input type="text" name="last_name" id="last_name_id" required></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td> <input type="text" name="birthday" id="birthday_id" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="first_name_id">First name:</label><input type="text" ' 'name="first_name" id="first_name_id" required></div><div><label ' 'for="last_name_id">Last name:</label><input type="text" ' 'name="last_name" id="last_name_id" required></div><div><label ' 'for="birthday_id">Birthday:</label><input type="text" name="birthday" ' 'id="birthday_id" required></div>', ) def test_auto_id_true(self): # If auto_id is any True value whose str() does not contain '%s', the "id" # attribute will be the name of the field. p = Person(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_auto_id_false(self): # If auto_id is any False value, an "id" attribute won't be output unless it # was manually entered. p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_id_on_field(self): # In this example, auto_id is False, but the "id" attribute for the "first_name" # field is given. Also note that field gets a <label>, while the others don't. p = PersonNew(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_auto_id_on_form_and_field(self): # If the "id" attribute is specified in the Form and auto_id is True, the "id" # attribute in the Form gets precedence. p = PersonNew(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" required>' ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm({"email": "[email protected]", "get_spam": True}, auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" value="[email protected]" required>', ) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # 'True' or 'true' should be rendered without a value attribute f = SignupForm({"email": "[email protected]", "get_spam": "True"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({"email": "[email protected]", "get_spam": "true"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # A value of 'False' or 'false' should be rendered unchecked f = SignupForm( {"email": "[email protected]", "get_spam": "False"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm( {"email": "[email protected]", "get_spam": "false"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({"email": "[email protected]", "get_spam": "0"}) self.assertTrue(f.is_valid()) self.assertTrue(f.cleaned_data.get("get_spam")) def test_widget_output(self): # Any Field can have a Widget class passed to its constructor: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["subject"]), '<input type="text" name="subject" required>' ) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="10" cols="40" required></textarea>', ) # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea name="subject" rows="10" cols="40" required></textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message">' ) # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea(attrs={"rows": 80, "cols": 20})) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="80" cols="20" required></textarea>', ) # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) f = ContactForm({"subject": "Hello", "message": "I love you."}, auto_id=False) self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" value="I love you." required>', ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message" value="I love you.">', ) def test_forms_with_choices(self): # For a form with a <select>, use ChoiceField: class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # A subtlety: If one of the choices' value is the empty string and the form is # unbound, then the <option> for the empty-string choice will get selected. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("", "------"), ("P", "Python"), ("J", "Java")] ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language" required> <option value="" selected>------</option> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) # You can specify widget attributes in the Widget constructor. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select(attrs={"class": "foo"}), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # When passing a custom widget instance to ChoiceField, note that setting # 'choices' on the widget is meaningless. The widget will use the choices # defined on the Field, not the ones defined on the Widget. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select( choices=[("R", "Ruby"), ("P", "Perl")], attrs={"class": "foo"} ), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # You can set a ChoiceField's choices after the fact. class FrameworkForm(Form): name = CharField() language = ChoiceField() f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> </select>""", ) f.fields["language"].choices = [("P", "Python"), ("J", "Java")] self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) def test_forms_with_radio(self): # Add widget=RadioSelect to use that widget with a ChoiceField. f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div>""", ) self.assertHTMLEqual( f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required></td></tr> <tr><th>Language:</th><td><div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" required></li> <li>Language: <div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></li>""", ) # Need an auto_id to generate legend. self.assertHTMLEqual( f.render(f.template_name_div), '<div> Name: <input type="text" name="name" required></div><div><fieldset>' 'Language:<div><div><label><input type="radio" name="language" value="P" ' 'required> Python</label></div><div><label><input type="radio" ' 'name="language" value="J" required> Java</label></div></div></fieldset>' "</div>", ) # Regarding auto_id and <label>, RadioSelect is a special case. Each # radio button gets a distinct ID, formed by appending an underscore # plus the button's zero-based index. f = FrameworkForm(auto_id="id_%s") self.assertHTMLEqual( str(f["language"]), """ <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div>""", ) # When RadioSelect is used with auto_id, and the whole form is printed # using either as_table() or as_ul(), the label for the RadioSelect # will **not** point to the ID of the *first* radio button to improve # accessibility for screen reader users. self.assertHTMLEqual( f.as_table(), """ <tr><th><label for="id_name">Name:</label></th><td> <input type="text" name="name" id="id_name" required></td></tr> <tr><th><label>Language:</label></th><td><div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """ <li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></li> """, ) self.assertHTMLEqual( f.as_p(), """ <p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></p> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Language:</legend>' '<div id="id_language"><div><label for="id_language_0"><input ' 'type="radio" name="language" value="P" required id="id_language_0">' 'Python</label></div><div><label for="id_language_1"><input type="radio" ' 'name="language" value="J" required id="id_language_1">Java</label></div>' "</div></fieldset></div>", ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), '<label><input type="radio" name="name" value="john" required> John</label>' '<label><input type="radio" name="name" value="paul" required> Paul</label>' '<label><input type="radio" name="name" value="george" required> George' "</label>" '<label><input type="radio" name="name" value="ringo" required> Ringo' "</label>", ) self.assertHTMLEqual( "\n".join("<div>%s</div>" % bf for bf in f["name"]), """ <div><label> <input type="radio" name="name" value="john" required> John</label></div> <div><label> <input type="radio" name="name" value="paul" required> Paul</label></div> <div><label> <input type="radio" name="name" value="george" required> George </label></div> <div><label> <input type="radio" name="name" value="ringo" required> Ringo</label></div> """, ) def test_form_with_iterable_boundfield_id(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) fields = list(BeatleForm()["name"]) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, "id_name_0") self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual( fields[0].tag(), '<input type="radio" name="name" value="john" id="id_name_0" required>', ) self.assertHTMLEqual( str(fields[0]), '<label for="id_name_0"><input type="radio" name="name" ' 'value="john" id="id_name_0" required> John</label>', ) self.assertEqual(fields[1].id_for_label, "id_name_1") self.assertEqual(fields[1].choice_label, "Paul") self.assertHTMLEqual( fields[1].tag(), '<input type="radio" name="name" value="paul" id="id_name_1" required>', ) self.assertHTMLEqual( str(fields[1]), '<label for="id_name_1"><input type="radio" name="name" ' 'value="paul" id="id_name_1" required> Paul</label>', ) def test_iterable_boundfield_select(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ] ) fields = list(BeatleForm(auto_id=False)["name"]) self.assertEqual(len(fields), 4) self.assertIsNone(fields[0].id_for_label) self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. class BeatleForm(Form): name = CharField() f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), '<input type="text" name="name" required>', ) def test_boundfield_slice(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm() bf = f["name"] self.assertEqual( [str(item) for item in bf[1:]], [str(bf[1]), str(bf[2]), str(bf[3])], ) def test_boundfield_invalid_index(self): class TestForm(Form): name = ChoiceField(choices=[]) field = TestForm()["name"] msg = "BoundField indices must be integers or slices, not str." with self.assertRaisesMessage(TypeError, msg): field["foo"] def test_boundfield_bool(self): """BoundField without any choices (subwidgets) evaluates to True.""" class TestForm(Form): name = ChoiceField(choices=[]) self.assertIs(bool(TestForm()["name"]), True) def test_forms_with_multiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: class SongForm(Form): name = CharField() composers = MultipleChoiceField() f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> </select>""", ) class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""", ) f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( str(f["name"]), '<input type="text" name="name" value="Yesterday" required>' ) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P" selected>Paul McCartney</option> </select>""", ) f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th>' '<td><input type="text" name="name" required id="id_name"></td>' '</tr><tr><th><label for="id_composers">Composers:</label></th>' '<td><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><label for="id_composers">Composers:' '</label><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option><option value="P">Paul McCartney' "</option></select></div>", ) def test_multiple_checkbox_render(self): f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th><td>' '<input type="text" name="name" required id="id_name"></td></tr>' '<tr><th><label>Composers:</label></th><td><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Composers:</legend>' '<div id="id_composers"><div><label for="id_composers_0"><input ' 'type="checkbox" name="composers" value="J" id="id_composers_0">' 'John Lennon</label></div><div><label for="id_composers_1"><input ' 'type="checkbox" name="composers" value="P" id="id_composers_1">' "Paul McCartney</label></div></div></fieldset></div>", ) def test_form_with_disabled_fields(self): class PersonForm(Form): name = CharField() birthday = DateField(disabled=True) class PersonFormFieldInitial(Form): name = CharField() birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16)) # Disabled fields are generally not transmitted by user agents. # The value from the form's initial data is used. f1 = PersonForm( {"name": "John Doe"}, initial={"birthday": datetime.date(1974, 8, 16)} ) f2 = PersonFormFieldInitial({"name": "John Doe"}) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Values provided in the form's data are ignored. data = {"name": "John Doe", "birthday": "1984-11-10"} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Initial data remains present on invalid forms. data = {} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertFalse(form.is_valid()) self.assertEqual(form["birthday"].value(), datetime.date(1974, 8, 16)) def test_hidden_data(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) # MultipleChoiceField rendered as_hidden() is a special case. Because it can # have multiple values, its as_hidden() renders multiple <input type="hidden"> # tags. f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), '<input type="hidden" name="composers" value="P">', ) f = SongForm({"name": "From Me To You", "composers": ["P", "J"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), """<input type="hidden" name="composers" value="P"> <input type="hidden" name="composers" value="J">""", ) # DateTimeField rendered as_hidden() is special too class MessageForm(Form): when = SplitDateTimeField() f = MessageForm({"when_0": "1992-01-01", "when_1": "01:01"}) self.assertTrue(f.is_valid()) self.assertHTMLEqual( str(f["when"]), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" ' "required>" '<input type="text" name="when_1" value="01:01" id="id_when_1" required>', ) self.assertHTMLEqual( f["when"].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">' '<input type="hidden" name="when_1" value="01:01" id="id_when_1">', ) def test_multiple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J", "P"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) def test_checkbox_auto_id(self): # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox # gets a distinct ID, formed by appending an underscore plus the checkbox's # zero-based index. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) f = SongForm(auto_id="%s_id") self.assertHTMLEqual( str(f["composers"]), """ <div id="composers_id"> <div><label for="composers_id_0"> <input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></div> <div><label for="composers_id_1"> <input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></div> </div> """, ) def test_multiple_choice_list_data(self): # Data for a MultipleChoiceField should be a list. QueryDict and # MultiValueDict conveniently work with this. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) data = {"name": "Yesterday", "composers": ["J", "P"]} f = SongForm(data) self.assertEqual(f.errors, {}) data = QueryDict("name=Yesterday&composers=J&composers=P") f = SongForm(data) self.assertEqual(f.errors, {}) data = MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}) f = SongForm(data) self.assertEqual(f.errors, {}) # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist() # is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_multiple_hidden(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) # The MultipleHiddenInput widget renders multiple values as hidden fields. class SongFormHidden(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=MultipleHiddenInput, ) f = SongFormHidden( MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}), auto_id=False, ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" required> <input type="hidden" name="composers" value="J"> <input type="hidden" name="composers" value="P"></li>""", ) # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({"name": "Yesterday"}, auto_id=False) self.assertEqual(f.errors["composers"], ["This field is required."]) f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") f = SongForm({"name": "Yesterday", "composers": ["J", "P"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J", "P"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") # MultipleHiddenInput uses ducktyping so that # MultiValueDictLike.getlist() is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. class EscapingForm(Form): special_name = CharField(label="<em>Special</em> Field") special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) def clean_special_name(self): raise ValidationError( "Something's wrong with '%s'" % self.cleaned_data["special_name"] ) def clean_special_safe_name(self): raise ValidationError( mark_safe( "'<b>%s</b>' is a safe string" % self.cleaned_data["special_safe_name"] ) ) f = EscapingForm( { "special_name": "Nothing to escape", "special_safe_name": "Nothing to escape", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), """ <tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"> <li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul> <input type="text" name="special_name" value="Nothing to escape" required> </td></tr> <tr><th><em>Special</em> Field:</th><td> <ul class="errorlist"> <li>'<b>Nothing to escape</b>' is a safe string</li></ul> <input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr> """, ) f = EscapingForm( { "special_name": "Should escape < & > and <script>alert('xss')</script>", "special_safe_name": "<i>Do not escape</i>", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>" '<ul class="errorlist"><li>' "Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and " "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>" '<input type="text" name="special_name" value="Should escape &lt; &amp; ' '&gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required>' "</td></tr>" "<tr><th><em>Special</em> Field:</th><td>" '<ul class="errorlist">' "<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>" '<input type="text" name="special_safe_name" ' 'value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>', ) def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you # want the validation message to be associated with a particular field, # implement the clean_XXX() method on the Form, where XXX is the field # name. As in Field.clean(), the clean_XXX() method should return the # cleaned value. In the clean_XXX() method, you have access to # self.cleaned_data, which is a dictionary of all the data that has # been cleaned *so far*, in order by the fields, including the current # field (e.g., the field XXX if you're in clean_XXX()). class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean_password2(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data["password2"] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertEqual(f.errors["username"], ["This field is required."]) self.assertEqual(f.errors["password1"], ["This field is required."]) self.assertEqual(f.errors["password2"], ["This field is required."]) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertEqual( f.errors["password2"], ["Please make sure your passwords match."] ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") # Another way of doing multiple-field validation is by implementing the # Form's clean() method. Usually ValidationError raised by that method # will not be associated with a particular field and will have a # special-case association with the field named '__all__'. It's # possible to associate the errors to particular field with the # Form.add_error() method or by passing a dictionary that maps each # field to one or more errors. # # Note that in Form.clean(), you have access to self.cleaned_data, a # dictionary of all the fields/values that have *not* raised a # ValidationError. Also note Form.clean() is required to return a # dictionary of all clean data. class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): # Test raising a ValidationError as NON_FIELD_ERRORS. if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") # Test raising ValidationError that targets multiple fields. errors = {} if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE": errors["password1"] = "Forbidden value." if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE": errors["password2"] = ["Forbidden value."] if errors: raise ValidationError(errors) # Test Form.add_error() if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2": self.add_error(None, "Non-field error 1.") self.add_error("password1", "Forbidden value 2.") if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2": self.add_error("password2", "Forbidden value 2.") raise ValidationError("Non-field error 2.") return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>Username:</th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password2" required></td></tr>""", ) self.assertEqual(f.errors["username"], ["This field is required."]) self.assertEqual(f.errors["password1"], ["This field is required."]) self.assertEqual(f.errors["password2"], ["This field is required."]) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertEqual( f.errors["__all__"], ["Please make sure your passwords match."] ) self.assertHTMLEqual( f.as_table(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td> <input type="text" name="username" value="adrian" maxlength="10" required> </td></tr> <tr><th>Password1:</th><td> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td> <input type="password" name="password2" required></td></tr> """, ) self.assertHTMLEqual( f.as_ul(), """ <li><ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required> </li> <li>Password1: <input type="password" name="password1" required></li> <li>Password2: <input type="password" name="password2" required></li> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Please make sure your passwords match.' '</li></ul><div>Username: <input type="text" name="username" ' 'value="adrian" maxlength="10" required></div><div>Password1: <input ' 'type="password" name="password1" required></div><div>Password2: <input ' 'type="password" name="password2" required></div>', ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") f = UserRegistration( { "username": "adrian", "password1": "FORBIDDEN_VALUE", "password2": "FORBIDDEN_VALUE", }, auto_id=False, ) self.assertEqual(f.errors["password1"], ["Forbidden value."]) self.assertEqual(f.errors["password2"], ["Forbidden value."]) f = UserRegistration( { "username": "adrian", "password1": "FORBIDDEN_VALUE2", "password2": "FORBIDDEN_VALUE2", }, auto_id=False, ) self.assertEqual( f.errors["__all__"], ["Non-field error 1.", "Non-field error 2."] ) self.assertEqual(f.errors["password1"], ["Forbidden value 2."]) self.assertEqual(f.errors["password2"], ["Forbidden value 2."]) with self.assertRaisesMessage(ValueError, "has no field named"): f.add_error("missing_field", "Some error.") def test_update_error_dict(self): class CodeForm(Form): code = CharField(max_length=10) def clean(self): try: raise ValidationError({"code": [ValidationError("Code error 1.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": [ValidationError("Code error 2.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": forms.ErrorList(["Code error 3."])}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError("Non-field error 1.") except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError([ValidationError("Non-field error 2.")]) except ValidationError as e: self._errors = e.update_error_dict(self._errors) # The newly added list of errors is an instance of ErrorList. for field, error_list in self._errors.items(): if not isinstance(error_list, self.error_class): self._errors[field] = self.error_class(error_list) form = CodeForm({"code": "hello"}) # Trigger validation. self.assertFalse(form.is_valid()) # update_error_dict didn't lose track of the ErrorDict type. self.assertIsInstance(form._errors, forms.ErrorDict) self.assertEqual( dict(form.errors), { "code": ["Code error 1.", "Code error 2.", "Code error 3."], NON_FIELD_ERRORS: ["Non-field error 1.", "Non-field error 2."], }, ) def test_has_error(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput, min_length=5) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError( "Please make sure your passwords match.", code="password_mismatch", ) f = UserRegistration(data={}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "required")) self.assertFalse(f.has_error("password1", "anything")) f = UserRegistration(data={"password1": "Hi", "password2": "Hi"}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "min_length")) self.assertFalse(f.has_error("password1", "anything")) self.assertFalse(f.has_error("password2")) self.assertFalse(f.has_error("password2", "anything")) f = UserRegistration(data={"password1": "Bonjour", "password2": "Hello"}) self.assertFalse(f.has_error("password1")) self.assertFalse(f.has_error("password1", "required")) self.assertTrue(f.has_error(NON_FIELD_ERRORS)) self.assertTrue(f.has_error(NON_FIELD_ERRORS, "password_mismatch")) self.assertFalse(f.has_error(NON_FIELD_ERRORS, "anything")) def test_html_output_with_hidden_input_field_errors(self): class TestForm(Form): hidden_input = CharField(widget=HiddenInput) def clean(self): self.add_error(None, "Form error") f = TestForm(data={}) error_dict = { "hidden_input": ["This field is required."], "__all__": ["Form error"], } self.assertEqual(f.errors, error_dict) f.as_table() self.assertEqual(f.errors, error_dict) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></td></tr>', ) self.assertHTMLEqual( f.as_ul(), '<li><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></li>', ) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<p><input type="hidden" name="hidden_input" id="id_hidden_input"></p>', ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<div><input type="hidden" name="hidden_input" id="id_hidden_input"></div>', ) def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the # subclass' __init__(). class Person(Form): first_name = CharField() last_name = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["birthday"] = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td> <input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" required></td></tr> """, ) # Instances of a dynamic Form do not persist fields from one Form instance to # the next. class MyForm(Form): def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) class MyForm(Form): default_field_1 = CharField() default_field_2 = CharField() def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) # Similarly, changes to field attributes do not persist from one Form instance # to the next. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): super().__init__(*args, **kwargs) if names_required: self.fields["first_name"].required = True self.fields["first_name"].widget.attrs["class"] = "required" self.fields["last_name"].required = True self.fields["last_name"].widget.attrs["class"] = "required" f = Person(names_required=False) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (False, False), ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({}, {}), ) f = Person(names_required=True) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (True, True) ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({"class": "reuired"}, {"class": "required"}), ) f = Person(names_required=False) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (False, False), ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({}, {}), ) class Person(Form): first_name = CharField(max_length=30) last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): super().__init__(*args, **kwargs) if name_max_length: self.fields["first_name"].max_length = name_max_length self.fields["last_name"].max_length = name_max_length f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) f = Person(name_max_length=20) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20) ) f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) # Similarly, choices do not persist from one Form instance to the next. # Refs #15127. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) gender = ChoiceField(choices=(("f", "Female"), ("m", "Male"))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields["gender"].choices += (("u", "Unspecified"),) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) f = Person(allow_unspec_gender=True) self.assertEqual( f["gender"].field.choices, [("f", "Female"), ("m", "Male"), ("u", "Unspecified")], ) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) def test_validators_independence(self): """ The list of form field validators can be modified without polluting other forms. """ class MyForm(Form): myfield = CharField(max_length=25) f1 = MyForm() f2 = MyForm() f1.fields["myfield"].validators[0] = MaxValueValidator(12) self.assertNotEqual( f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0] ) def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a # separate row is not displayed. They're displayed in the last row of the # form, directly after that row's form element. class Person(Form): first_name = CharField() last_name = CharField() hidden_text = CharField(widget=HiddenInput) birthday = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td><input type="text" name="first_name" required> </td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required> </td></tr> <tr><th>Birthday:</th> <td><input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <p>First name: <input type="text" name="first_name" required></p> <p>Last name: <input type="text" name="last_name" required></p> <p>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<div>First name: <input type="text" name="first_name" required></div>' '<div>Last name: <input type="text" name="last_name" required></div><div>' 'Birthday: <input type="text" name="birthday" required><input ' 'type="hidden" name="hidden_text"></div>', ) # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. p = Person(auto_id="id_%s") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">Birthday:' '</label><input type="text" name="birthday" id="id_birthday" required>' '<input type="hidden" name="hidden_text" id="id_hidden_text"></div>', ) # If a field with a HiddenInput has errors, the as_table() and as_ul() output # will include the error message(s) with the text "(Hidden field [fieldname]) " # prepended. This message is displayed at the top of the output, regardless of # its field's order in the form. p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}, auto_id=False, ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></td></tr> <tr><th>First name:</th><td> <input type="text" name="first_name" value="John" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" value="Lennon" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li><ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" required> </li> <li>Last name: <input type="text" name="last_name" value="Lennon" required> </li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" required> </p> <p>Last name: <input type="text" name="last_name" value="Lennon" required> </p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field ' 'is required.</li></ul><div>First name: <input type="text" ' 'name="first_name" value="John" required></div><div>Last name: <input ' 'type="text" name="last_name" value="Lennon" required></div><div>' 'Birthday: <input type="text" name="birthday" value="1940-10-9" required>' '<input type="hidden" name="hidden_text"></div>', ) # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): foo = CharField(widget=HiddenInput) bar = CharField(widget=HiddenInput) p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_ul(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">' ) def test_field_order(self): # A Form's fields are displayed in the same order in which they were defined. class TestForm(Form): field1 = CharField() field2 = CharField() field3 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field7 = CharField() field8 = CharField() field9 = CharField() field10 = CharField() field11 = CharField() field12 = CharField() field13 = CharField() field14 = CharField() p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), "".join( f"<tr><th>Field{i}:</th><td>" f'<input type="text" name="field{i}" required></td></tr>' for i in range(1, 15) ), ) def test_explicit_field_order(self): class TestFormParent(Form): field1 = CharField() field2 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field_order = ["field6", "field5", "field4", "field2", "field1"] class TestForm(TestFormParent): field3 = CharField() field_order = ["field2", "field4", "field3", "field5", "field6"] class TestFormRemove(TestForm): field1 = None class TestFormMissing(TestForm): field_order = ["field2", "field4", "field3", "field5", "field6", "field1"] field1 = None class TestFormInit(TestFormParent): field3 = CharField() field_order = None def __init__(self, **kwargs): super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() self.assertEqual(list(p.fields), TestFormParent.field_order) p = TestFormRemove() self.assertEqual(list(p.fields), TestForm.field_order) p = TestFormMissing() self.assertEqual(list(p.fields), TestForm.field_order) p = TestForm() self.assertEqual(list(p.fields), TestFormMissing.field_order) p = TestFormInit() order = [*TestForm.field_order, "field1"] self.assertEqual(list(p.fields), order) TestForm.field_order = ["unknown"] p = TestForm() self.assertEqual( list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"] ) def test_form_html_attributes(self): # Some Field classes have an effect on the HTML attributes of their associated # Widget. If you set max_length in a CharField and its associated widget is # either a TextInput or PasswordInput, then the widget's rendered HTML will # include the "maxlength" attribute. class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) realname = CharField( max_length=10, widget=TextInput ) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" maxlength="10" required> </li> <li>Password: <input type="password" name="password" maxlength="10" required></li> <li>Realname: <input type="text" name="realname" maxlength="10" required> </li> <li>Address: <input type="text" name="address" required></li> """, ) # If you specify a custom "attrs" that includes the "maxlength" # attribute, the Field's max_length attribute will override whatever # "maxlength" you specify in "attrs". class UserRegistration(Form): username = CharField( max_length=10, widget=TextInput(attrs={"maxlength": 20}) ) password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' "</li>" '<li>Password: <input type="password" name="password" maxlength="10" ' "required></li>", ) def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field # class. If you don't specify 'label', Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. class UserRegistration(Form): username = CharField(max_length=10, label="Your username") password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)") p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Your username: <input type="text" name="username" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Contraseña (de nuevo): <input type="password" name="password2" required></li> """, ) # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. class Questions(Form): q1 = CharField(label="The first question") q2 = CharField(label="What is your name?") q3 = CharField(label="The answer to life is:") q4 = CharField(label="Answer this question!") q5 = CharField(label="The last question. Period.") self.assertHTMLEqual( Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" required></p> <p>What is your name? <input type="text" name="q2" required></p> <p>The answer to life is: <input type="text" name="q3" required></p> <p>Answer this question! <input type="text" name="q4" required></p> <p>The last question. Period. <input type="text" name="q5" required></p>""", ) self.assertHTMLEqual( Questions().as_p(), """ <p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p> """, ) # If a label is set to the empty string for a field, that field won't # get a label. class UserRegistration(Form): username = CharField(max_length=10, label="") password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""", ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """ <li> <input id="id_username" type="text" name="username" maxlength="10" required> </li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li> """, ) # If label is None, Django will auto-create the label from the field name. This # is default behavior. class UserRegistration(Form): username = CharField(max_length=10, label=None) password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' "</li>" '<li>Password: <input type="password" name="password" required></li>', ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li>""", ) def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify # the punctuation symbol used at the end of a label. By default, the # colon (:) is used, and is only appended to the label if the label # doesn't already end with a punctuation symbol: ., !, ? or :. If you # specify a different suffix, it will be appended regardless of the # last character of the label. class FavoriteForm(Form): color = CharField(label="Favorite color?") animal = CharField(label="Favorite animal") answer = CharField(label="Secret answer", label_suffix=" =") f = FavoriteForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal: <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="?") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal? <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="\u2192") self.assertHTMLEqual( f.as_ul(), '<li>Favorite color? <input type="text" name="color" required></li>\n' "<li>Favorite animal\u2192 " '<input type="text" name="animal" required></li>\n' '<li>Secret answer = <input type="text" name="answer" required></li>', ) def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a # Field class. This initial data is displayed when a Form is rendered with *no* # data. It is not displayed when a Form is rendered with any data (including an # empty dictionary). Also, the initial value is *not* used if data for a # particular required field isn't provided. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": ""}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # An 'initial' value is *not* used as a fallback if data is not # provided. In this example, we don't provide a value for 'username', # and the form raises a validation error rather than using the initial # value for 'username'. p = UserRegistration({"password": "secret"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): # The previous technique dealt with "hard-coded" initial data, but it's also # possible to specify initial data after you've already created the Form class # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This # should be a dictionary containing initial values for one or more fields in the # form, keyed by field name. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) p = UserRegistration(initial={"username": "stephane"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": "foo"}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # A dynamic 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the # form raises a validation error rather than using the initial value # for 'username'. p = UserRegistration({"password": "secret"}, initial={"username": "django"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) p = UserRegistration(initial={"username": "babik"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also # possible to specify callable data. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")] ) # We need to define functions that get called later.) def initial_django(): return "django" def initial_stephane(): return "stephane" def initial_options(): return ["f", "b"] def initial_other_options(): return ["b", "w"] # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration( initial={"username": initial_django, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration( {}, initial={"username": initial_django, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": initial_django}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": "foo", "options": ["f", "b"]}, initial={"username": initial_django}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # A callable 'initial' value is *not* used as a fallback if data is not # provided. In this example, we don't provide a value for 'username', # and the form raises a validation error rather than using the initial # value for 'username'. p = UserRegistration( {"password": "secret"}, initial={"username": initial_django, "options": initial_options}, ) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial=initial_django) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")], initial=initial_other_options, ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b" selected>bar</option> <option value="w" selected>whiz</option> </select></li> """, ) p = UserRegistration( initial={"username": initial_stephane, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) def test_get_initial_for_field(self): now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456) class PersonForm(Form): first_name = CharField(initial="John") last_name = CharField(initial="Doe") age = IntegerField() occupation = CharField(initial=lambda: "Unknown") dt_fixed = DateTimeField(initial=now) dt_callable = DateTimeField(initial=lambda: now) form = PersonForm(initial={"first_name": "Jane"}) cases = [ ("age", None), ("last_name", "Doe"), # Form.initial overrides Field.initial. ("first_name", "Jane"), # Callables are evaluated. ("occupation", "Unknown"), # Microseconds are removed from datetimes. ("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)), ("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)), ] for field_name, expected in cases: with self.subTest(field_name=field_name): field = form.fields[field_name] actual = form.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def test_changed_data(self): class Person(Form): first_name = CharField(initial="Hans") last_name = CharField(initial="Greatel") birthday = DateField(initial=datetime.date(1974, 8, 16)) p = Person( data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"} ) self.assertTrue(p.is_valid()) self.assertNotIn("first_name", p.changed_data) self.assertIn("last_name", p.changed_data) self.assertNotIn("birthday", p.changed_data) # A field raising ValidationError is always in changed_data class PedanticField(forms.Field): def to_python(self, value): raise ValidationError("Whatever") class Person2(Person): pedantic = PedanticField(initial="whatever", show_hidden_initial=True) p = Person2( data={ "first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16", "initial-pedantic": "whatever", } ) self.assertFalse(p.is_valid()) self.assertIn("pedantic", p.changed_data) def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. class UserRegistration(Form): username = CharField(max_length=10, initial="djangonaut") password = CharField(widget=PasswordInput) unbound = UserRegistration() bound = UserRegistration({"password": "foo"}) self.assertIsNone(bound["username"].value()) self.assertEqual(unbound["username"].value(), "djangonaut") self.assertEqual(bound["password"].value(), "foo") self.assertIsNone(unbound["password"].value()) def test_boundfield_initial_called_once(self): """ Multiple calls to BoundField().value() in an unbound form should return the same result each time (#24391). """ class MyForm(Form): name = CharField(max_length=10, initial=uuid.uuid4) form = MyForm() name = form["name"] self.assertEqual(name.value(), name.value()) # BoundField is also cached self.assertIs(form["name"], name) def test_boundfield_value_disabled_callable_initial(self): class PersonForm(Form): name = CharField(initial=lambda: "John Doe", disabled=True) # Without form data. form = PersonForm() self.assertEqual(form["name"].value(), "John Doe") # With form data. As the field is disabled, the value should not be # affected by the form data. form = PersonForm({}) self.assertEqual(form["name"].value(), "John Doe") def test_custom_boundfield(self): class CustomField(CharField): def get_bound_field(self, form, name): return (form, name) class SampleForm(Form): name = CustomField() f = SampleForm() self.assertEqual(f["name"], (f, "name")) def test_initial_datetime_values(self): now = datetime.datetime.now() # Nix microseconds (since they should be ignored). #22502 now_no_ms = now.replace(microsecond=0) if now == now_no_ms: now = now.replace(microsecond=1) def delayed_now(): return now def delayed_now_time(): return now.time() class HiddenInputWithoutMicrosec(HiddenInput): supports_microseconds = False class TextInputWithoutMicrosec(TextInput): supports_microseconds = False class DateTimeForm(Form): # Test a non-callable. fixed = DateTimeField(initial=now) auto_timestamp = DateTimeField(initial=delayed_now) auto_time_only = TimeField(initial=delayed_now_time) supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput) hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput) hi_without_microsec = DateTimeField( initial=delayed_now, widget=HiddenInputWithoutMicrosec ) ti_without_microsec = DateTimeField( initial=delayed_now, widget=TextInputWithoutMicrosec ) unbound = DateTimeForm() cases = [ ("fixed", now_no_ms), ("auto_timestamp", now_no_ms), ("auto_time_only", now_no_ms.time()), ("supports_microseconds", now), ("hi_default_microsec", now), ("hi_without_microsec", now_no_ms), ("ti_without_microsec", now_no_ms), ] for field_name, expected in cases: with self.subTest(field_name=field_name): actual = unbound[field_name].value() self.assertEqual(actual, expected) # Also check get_initial_for_field(). field = unbound.fields[field_name] actual = unbound.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def get_datetime_form_with_callable_initial(self, disabled, microseconds=0): class FakeTime: def __init__(self): self.elapsed_seconds = 0 def now(self): self.elapsed_seconds += 1 return datetime.datetime( 2006, 10, 25, 14, 30, 45 + self.elapsed_seconds, microseconds, ) class DateTimeForm(forms.Form): dt = DateTimeField(initial=FakeTime().now, disabled=disabled) return DateTimeForm({}) def test_datetime_clean_disabled_callable_initial_microseconds(self): """ Cleaning a form with a disabled DateTimeField and callable initial removes microseconds. """ form = self.get_datetime_form_with_callable_initial( disabled=True, microseconds=123456, ) self.assertEqual(form.errors, {}) self.assertEqual( form.cleaned_data, { "dt": datetime.datetime(2006, 10, 25, 14, 30, 46), }, ) def test_datetime_clean_disabled_callable_initial_bound_field(self): """ The cleaned value for a form with a disabled DateTimeField and callable initial matches the bound field's cached initial value. """ form = self.get_datetime_form_with_callable_initial(disabled=True) self.assertEqual(form.errors, {}) cleaned = form.cleaned_data["dt"] self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46)) bf = form["dt"] self.assertEqual(cleaned, bf.initial) def test_datetime_changed_data_callable_with_microseconds(self): class DateTimeForm(forms.Form): dt = DateTimeField( initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True, ) form = DateTimeForm({"dt": "2006-10-25 14:30:45"}) self.assertEqual(form.changed_data, []) def test_help_text(self): # You can specify descriptive text for a field by using the 'help_text' # argument. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Wählen Sie mit Bedacht." ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""", ) self.assertHTMLEqual( p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><th>Username:</th><td> <input type="text" name="username" maxlength="10" required><br> <span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" required> <br> <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div>Username: <div class="helptext">e.g., [email protected]</div>' '<input type="text" name="username" maxlength="10" required></div>' '<div>Password: <div class="helptext">Wählen Sie mit Bedacht.</div>' '<input type="password" name="password" required></div>', ) # The help text is displayed whether or not data is provided for the form. p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" value="foo" ' 'maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li><ul class="errorlist"><li>This field is required.</li></ul>' 'Password: <input type="password" name="password" required>' '<span class="helptext">Wählen Sie mit Bedacht.</span></li>', ) # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField(widget=PasswordInput) next = CharField( widget=HiddenInput, initial="/", help_text="Redirect destination" ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <input type="hidden" name="next" value="/"></li>""", ) def test_help_text_html_safe(self): """help_text should not be escaped.""" class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Help text is <strong>escaped</strong>.", ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></li>', ) self.assertHTMLEqual( p.as_p(), '<p>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></p>' '<p>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></p>', ) self.assertHTMLEqual( p.as_table(), "<tr><th>Username:</th><td>" '<input type="text" name="username" maxlength="10" required><br>' '<span class="helptext">e.g., [email protected]</span></td></tr>' "<tr><th>Password:</th><td>" '<input type="password" name="password" required><br>' '<span class="helptext">Help text is <strong>escaped</strong>.</span>' "</td></tr>", ) def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have # all of the fields of the parent Form, plus whichever fields you define in the # subclass. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Musician(Person): instrument = CharField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) m = Musician(auto_id=False) self.assertHTMLEqual( m.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Instrument: <input type="text" name="instrument" required></li>""", ) # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Instrument(Form): instrument = CharField() class Beatle(Person, Instrument): haircut_type = CharField() b = Beatle(auto_id=False) self.assertHTMLEqual( b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required></li> <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Haircut type: <input type="text" name="haircut_type" required></li>""", ) def test_forms_with_prefixes(self): # Sometimes it's necessary to have multiple forms display on the same # HTML page, or multiple copies of the same form. We can accomplish # this with form prefixes. Pass the keyword argument 'prefix' to the # Form constructor to use this feature. This value will be prepended to # each HTML form field name. One way to think about this is "namespaces # for HTML forms". Notice that in the data argument, each field's key # has the prefix, in this case 'person1', prepended to the actual field # name. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", } p = Person(data, prefix="person1") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li> <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li> """, ) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="person1-first_name" value="John" ' 'id="id_person1-first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="person1-last_name" value="Lennon" ' 'id="id_person1-last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="person1-birthday" value="1940-10-9" ' 'id="id_person1-birthday" required>', ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { "person1-first_name": "", "person1-last_name": "", "person1-birthday": "", } p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertEqual(p["first_name"].errors, ["This field is required."]) # Accessing a nonexistent field. with self.assertRaises(KeyError): p["person1-first_name"].errors # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", "person2-first_name": "Jim", "person2-last_name": "Morrison", "person2-birthday": "1943-12-8", } p1 = Person(data, prefix="person1") self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data["first_name"], "John") self.assertEqual(p1.cleaned_data["last_name"], "Lennon") self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9)) p2 = Person(data, prefix="person2") self.assertTrue(p2.is_valid()) self.assertEqual(p2.cleaned_data["first_name"], "Jim") self.assertEqual(p2.cleaned_data["last_name"], "Morrison") self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a # form can alter that behavior by implementing the add_prefix() method. This # method takes a field name and returns the prefixed field, according to # self.prefix. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() def add_prefix(self, field_name): return ( "%s-prefix-%s" % (self.prefix, field_name) if self.prefix else field_name ) p = Person(prefix="foo") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li> <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li> """, ) data = { "foo-prefix-first_name": "John", "foo-prefix-last_name": "Lennon", "foo-prefix-birthday": "1940-10-9", } p = Person(data, prefix="foo") self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) def test_class_prefix(self): # Prefix can be also specified at the class level. class Person(Form): first_name = CharField() prefix = "foo" p = Person() self.assertEqual(p.prefix, "foo") p = Person(prefix="bar") self.assertEqual(p.prefix, "bar") def test_forms_with_null_boolean(self): # NullBooleanField is a bit of a special case because its presentation (widget) # is different than its data. This is handled transparently, though. class Person(Form): name = CharField() is_cool = NullBooleanField() p = Person({"name": "Joe"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "1"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "2"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "3"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": True}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": False}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "unknown"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "true"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "false"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) def test_forms_with_file_fields(self): # FileFields are a special case because they take their data from the # request.FILES, not request.POST. class FileForm(Form): file1 = FileField() f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"")}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>The submitted file is empty.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": "something that is not a file"}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>No file was submitted. Check the ' "encoding type on the form.</li></ul>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"some content")}, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) self.assertTrue(f.is_valid()) file1 = SimpleUploadedFile( "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() ) f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data should not contain the # required HTML attribute. The file input is left blank by the user to # keep the existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_filefield_initial_callable(self): class FileForm(forms.Form): file1 = forms.FileField(initial=lambda: "resume.txt") f = FileForm({}) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["file1"], "resume.txt") def test_filefield_with_fileinput_required(self): class FileForm(Form): file1 = forms.FileField(widget=FileInput) f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data doesn't contain the required # HTML attribute. The file input is left blank by the user to keep the # existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation # if it is completely empty. We can accomplish this by using the empty_permitted # argument to a form constructor. class SongForm(Form): artist = CharField() name = CharField() # First let's show what happens id empty_permitted=False (the default): data = {"artist": "", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": ["This field is required."], "artist": ["This field is required."], }, ) self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) # But if we fill in data for one of the fields, the form is no longer empty and # the whole thing must pass validation. data = {"artist": "The Doors", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["This field is required."]}) self.assertEqual(form.cleaned_data, {"artist": "The Doors"}) # If a field is not given in the data then None is returned for its data. Lets # make sure that when checking for empty_permitted that None is treated # accordingly. data = {"artist": None, "song": ""} form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in # initial that returns False on a boolean call needs to be treated literally. class PriceForm(Form): amount = FloatField() qty = IntegerField() data = {"amount": "0.0", "qty": ""} form = PriceForm( data, initial={"amount": 0.0}, empty_permitted=True, use_required_attribute=False, ) self.assertTrue(form.is_valid()) def test_empty_permitted_and_use_required_attribute(self): msg = ( "The empty_permitted and use_required_attribute arguments may not " "both be True." ) with self.assertRaisesMessage(ValueError, msg): Person(empty_permitted=True, use_required_attribute=True) def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput) artist = CharField() name = CharField() form = SongForm() self.assertEqual([f.name for f in form.hidden_fields()], ["token"]) self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"]) def test_hidden_initial_gets_id(self): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) self.assertHTMLEqual( MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td>' '<input id="id_field1" type="text" name="field1" maxlength="50" required>' '<input type="hidden" name="initial-field1" id="initial-id_field1">' "</td></tr>", ) def test_error_html_required_html_classes(self): class Person(Form): name = CharField() is_cool = NullBooleanField() email = EmailField(required=False) age = IntegerField() p = Person({}) p.error_css_class = "error" p.required_css_class = "required" self.assertHTMLEqual( p.as_ul(), """ <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li> <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr class="required error"> <th><label class="required" for="id_name">Name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="name" id="id_name" required></td></tr> <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th> <td><select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td> <input type="email" name="email" id="id_email"></td></tr> <tr class="required error"><th><label class="required" for="id_age">Age:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="number" name="age" id="id_age" required></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div class="required error"><label for="id_name" class="required">Name:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="name" required id="id_name" /></div>' '<div class="required"><label for="id_is_cool" class="required">Is cool:' '</label><select name="is_cool" id="id_is_cool">' '<option value="unknown" selected>Unknown</option>' '<option value="true">Yes</option><option value="false">No</option>' '</select></div><div><label for="id_email">Email:</label>' '<input type="email" name="email" id="id_email" /></div>' '<div class="required error"><label for="id_age" class="required">Age:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="number" name="age" required id="id_age" /></div>', ) def test_label_has_required_css_class(self): """ required_css_class is added to label_tag() and legend_tag() of required fields. """ class SomeForm(Form): required_css_class = "required" field = CharField(max_length=10) field2 = IntegerField(required=False) f = SomeForm({"field": "test"}) self.assertHTMLEqual( f["field"].label_tag(), '<label for="id_field" class="required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(), '<legend for="id_field" class="required">Field:</legend>', ) self.assertHTMLEqual( f["field"].label_tag(attrs={"class": "foo"}), '<label for="id_field" class="foo required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(attrs={"class": "foo"}), '<legend for="id_field" class="foo required">Field:</legend>', ) self.assertHTMLEqual( f["field2"].label_tag(), '<label for="id_field2">Field2:</label>' ) self.assertHTMLEqual( f["field2"].legend_tag(), '<legend for="id_field2">Field2:</legend>', ) def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() self.assertHTMLEqual( form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0">' '<input type="hidden" name="happened_at_1" id="id_happened_at_1">', ) def test_multivalue_field_validation(self): def bad_names(value): if value == "bad value": raise ValidationError("bad value not allowed") class NameField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( CharField(label="First name", max_length=10), CharField(label="Last name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return " ".join(data_list) class NameForm(Form): name = NameField(validators=[bad_names]) form = NameForm(data={"name": ["bad", "value"]}) form.full_clean() self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["bad value not allowed"]}) form = NameForm(data={"name": ["should be overly", "long for the field names"]}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": [ "Ensure this value has at most 10 characters (it has 16).", "Ensure this value has at most 10 characters (it has 24).", ], }, ) form = NameForm(data={"name": ["fname", "lname"]}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"name": "fname lname"}) def test_multivalue_deep_copy(self): """ #19298 -- MultiValueField needs to override the default as it needs to deep-copy subfields: """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( ChoiceField(label="Rank", choices=((1, 1), (2, 2))), CharField(label="Name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) self.assertIsInstance(field2, ChoicesField) self.assertIsNot(field2.fields, field.fields) self.assertIsNot(field2.fields[0].choices, field.fields[0].choices) def test_multivalue_initial_data(self): """ #23674 -- invalid initial data should not break form.changed_data() """ class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() data = {"date_age": ["1998-12-06", 16]} form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]}) self.assertTrue(form.has_changed()) def test_multivalue_optional_subfields(self): class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = ( CharField( label="Country Code", validators=[ RegexValidator( r"^\+[0-9]{1,2}$", message="Enter a valid country code." ) ], ), CharField(label="Phone Number"), CharField( label="Extension", error_messages={"incomplete": "Enter an extension."}, ), CharField( label="Label", required=False, help_text="E.g. home, work." ), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return "%s.%s ext. %s (label: %s)" % tuple(data_list) return None # An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61"]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61", "287654321", "123"]) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` f = PhoneField(required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) self.assertEqual("+61. ext. (label: )", f.clean(["+61"])) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. f = PhoneField(required=False, require_all_fields=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) def test_multivalue_optional_subfields_rendering(self): class PhoneWidget(MultiWidget): def __init__(self, attrs=None): widgets = [TextInput(), TextInput()] super().__init__(widgets, attrs) def decompress(self, value): return [None, None] class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = [CharField(), CharField(required=False)] super().__init__(fields, *args, **kwargs) class PhoneForm(Form): phone1 = PhoneField(widget=PhoneWidget) phone2 = PhoneField(widget=PhoneWidget, required=False) phone3 = PhoneField(widget=PhoneWidget, require_all_fields=False) phone4 = PhoneField( widget=PhoneWidget, required=False, require_all_fields=False, ) form = PhoneForm(auto_id=False) self.assertHTMLEqual( form.as_p(), """ <p>Phone1:<input type="text" name="phone1_0" required> <input type="text" name="phone1_1" required></p> <p>Phone2:<input type="text" name="phone2_0"> <input type="text" name="phone2_1"></p> <p>Phone3:<input type="text" name="phone3_0" required> <input type="text" name="phone3_1"></p> <p>Phone4:<input type="text" name="phone4_0"> <input type="text" name="phone4_1"></p> """, ) def test_custom_empty_values(self): """ Form fields can customize what is considered as an empty value for themselves (#19997). """ class CustomJSONField(CharField): empty_values = [None, ""] def to_python(self, value): # Fake json.loads if value == "{}": return {} return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() form = JSONForm(data={"json": "{}"}) form.full_clean() self.assertEqual(form.cleaned_data, {"json": {}}) def test_boundfield_label_tag(self): class SomeForm(Form): field = CharField() boundfield = SomeForm()["field"] testcases = [ # (args, kwargs, expected) # without anything: just print the <label> ((), {}, '<%(tag)s for="id_field">Field:</%(tag)s>'), # passing just one argument: overrides the field's label (("custom",), {}, '<%(tag)s for="id_field">custom:</%(tag)s>'), # the overridden label is escaped (("custom&",), {}, '<%(tag)s for="id_field">custom&amp;:</%(tag)s>'), ((mark_safe("custom&"),), {}, '<%(tag)s for="id_field">custom&:</%(tag)s>'), # Passing attrs to add extra attributes on the <label> ( (), {"attrs": {"class": "pretty"}}, '<%(tag)s for="id_field" class="pretty">Field:</%(tag)s>', ), ] for args, kwargs, expected in testcases: with self.subTest(args=args, kwargs=kwargs): self.assertHTMLEqual( boundfield.label_tag(*args, **kwargs), expected % {"tag": "label"}, ) self.assertHTMLEqual( boundfield.legend_tag(*args, **kwargs), expected % {"tag": "legend"}, ) def test_boundfield_label_tag_no_id(self): """ If a widget has no id, label_tag() and legend_tag() return the text with no surrounding <label>. """ class SomeForm(Form): field = CharField() boundfield = SomeForm(auto_id="")["field"] self.assertHTMLEqual(boundfield.label_tag(), "Field:") self.assertHTMLEqual(boundfield.legend_tag(), "Field:") self.assertHTMLEqual(boundfield.label_tag("Custom&"), "Custom&amp;:") self.assertHTMLEqual(boundfield.legend_tag("Custom&"), "Custom&amp;:") def test_boundfield_label_tag_custom_widget_id_for_label(self): class CustomIdForLabelTextInput(TextInput): def id_for_label(self, id): return "custom_" + id class EmptyIdForLabelTextInput(TextInput): def id_for_label(self, id): return None class SomeForm(Form): custom = CharField(widget=CustomIdForLabelTextInput) empty = CharField(widget=EmptyIdForLabelTextInput) form = SomeForm() self.assertHTMLEqual( form["custom"].label_tag(), '<label for="custom_id_custom">Custom:</label>' ) self.assertHTMLEqual( form["custom"].legend_tag(), '<legend for="custom_id_custom">Custom:</legend>', ) self.assertHTMLEqual(form["empty"].label_tag(), "<label>Empty:</label>") self.assertHTMLEqual(form["empty"].legend_tag(), "<legend>Empty:</legend>") def test_boundfield_empty_label(self): class SomeForm(Form): field = CharField(label="") boundfield = SomeForm()["field"] self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>') self.assertHTMLEqual( boundfield.legend_tag(), '<legend for="id_field"></legend>', ) def test_boundfield_id_for_label(self): class SomeForm(Form): field = CharField(label="") self.assertEqual(SomeForm()["field"].id_for_label, "id_field") def test_boundfield_id_for_label_override_by_attrs(self): """ If an id is provided in `Widget.attrs`, it overrides the generated ID, unless it is `None`. """ class SomeForm(Form): field = CharField(widget=TextInput(attrs={"id": "myCustomID"})) field_none = CharField(widget=TextInput(attrs={"id": None})) form = SomeForm() self.assertEqual(form["field"].id_for_label, "myCustomID") self.assertEqual(form["field_none"].id_for_label, "id_field_none") def test_boundfield_subwidget_id_for_label(self): """ If auto_id is provided when initializing the form, the generated ID in subwidgets must reflect that prefix. """ class SomeForm(Form): field = MultipleChoiceField( choices=[("a", "A"), ("b", "B")], widget=CheckboxSelectMultiple, ) form = SomeForm(auto_id="prefix_%s") subwidgets = form["field"].subwidgets self.assertEqual(subwidgets[0].id_for_label, "prefix_field_0") self.assertEqual(subwidgets[1].id_for_label, "prefix_field_1") def test_boundfield_widget_type(self): class SomeForm(Form): first_name = CharField() birthday = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) f = SomeForm() self.assertEqual(f["first_name"].widget_type, "text") self.assertEqual(f["birthday"].widget_type, "splithiddendatetime") def test_boundfield_css_classes(self): form = Person() field = form["first_name"] self.assertEqual(field.css_classes(), "") self.assertEqual(field.css_classes(extra_classes=""), "") self.assertEqual(field.css_classes(extra_classes="test"), "test") self.assertEqual(field.css_classes(extra_classes="test test"), "test") def test_label_suffix_override(self): """ BoundField label_suffix (if provided) overrides Form label_suffix """ class SomeForm(Form): field = CharField() boundfield = SomeForm(label_suffix="!")["field"] self.assertHTMLEqual( boundfield.label_tag(label_suffix="$"), '<label for="id_field">Field$</label>', ) self.assertHTMLEqual( boundfield.legend_tag(label_suffix="$"), '<legend for="id_field">Field$</legend>', ) def test_error_dict(self): class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "Non-field error.", code="secret", params={"a": 1, "b": 2} ) form = MyForm({}) self.assertIs(form.is_valid(), False) errors = form.errors.as_text() control = [ "* foo\n * This field is required.", "* bar\n * This field is required.", "* __all__\n * Non-field error.", ] for error in control: self.assertIn(error, errors) errors = form.errors.as_ul() control = [ '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>' "</li>", ] for error in control: self.assertInHTML(error, errors) errors = form.errors.get_json_data() control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "Non-field error."}], } self.assertEqual(errors, control) self.assertEqual(json.dumps(errors), form.errors.as_json()) def test_error_dict_as_json_escape_html(self): """#21962 - adding html escape flag to ErrorDict""" class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "<p>Non-field error.</p>", code="secret", params={"a": 1, "b": 2}, ) control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "<p>Non-field error.</p>"}], } form = MyForm({}) self.assertFalse(form.is_valid()) errors = json.loads(form.errors.as_json()) self.assertEqual(errors, control) escaped_error = "&lt;p&gt;Non-field error.&lt;/p&gt;" self.assertEqual( form.errors.get_json_data(escape_html=True)["__all__"][0]["message"], escaped_error, ) errors = json.loads(form.errors.as_json(escape_html=True)) control["__all__"][0]["message"] = escaped_error self.assertEqual(errors, control) def test_error_list(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertIsInstance(e, list) self.assertIn("Foo", e) self.assertIn("Foo", ValidationError(e)) self.assertEqual(e.as_text(), "* Foo\n* Foobar") self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) errors = e.get_json_data() self.assertEqual( errors, [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}], ) self.assertEqual(json.dumps(errors), e.as_json()) def test_error_list_class_not_specified(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_class_has_one_class_specified(self): e = ErrorList(error_class="foobar-error-class") e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>', ) def test_error_list_with_hidden_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField(widget=HiddenInput) p = Person({"first_name": "John"}) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></li><li> <label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field last_name) This field ' 'is required.</li></ul><div><label for="id_first_name">First name:</label>' '<input id="id_first_name" name="first_name" type="text" value="John" ' 'required><input id="id_last_name" name="last_name" type="hidden"></div>', ) def test_error_list_with_non_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField() def clean(self): raise ValidationError("Generic validation error") p = Person({"first_name": "John", "last_name": "Lennon"}) self.assertHTMLEqual( str(p.non_field_errors()), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>', ) self.assertHTMLEqual( p.as_ul(), """<li> <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li> <li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></li> <li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""", ) self.assertHTMLEqual( p.non_field_errors().as_text(), "* Generic validation error" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>Generic validation error</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></p> <p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"><ul class="errorlist nonfield"> <li>Generic validation error</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> </td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input id="id_last_name" name="last_name" type="text" value="Lennon" required> </td></tr> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>' '<div><label for="id_first_name">First name:</label><input ' 'id="id_first_name" name="first_name" type="text" value="John" required>' '</div><div><label for="id_last_name">Last name:</label><input ' 'id="id_last_name" name="last_name" type="text" value="Lennon" required>' "</div>", ) def test_error_escaping(self): class TestForm(Form): hidden = CharField(widget=HiddenInput(), required=False) visible = CharField() def clean_hidden(self): raise ValidationError('Foo & "bar"!') clean_visible = clean_hidden form = TestForm({"hidden": "a", "visible": "b"}) form.is_valid() self.assertHTMLEqual( form.as_ul(), '<li><ul class="errorlist nonfield">' "<li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>" '<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>' '<label for="id_visible">Visible:</label> ' '<input type="text" name="visible" value="b" id="id_visible" required>' '<input type="hidden" name="hidden" value="a" id="id_hidden"></li>', ) def test_baseform_repr(self): """ BaseForm.__repr__() should contain some basic information about the form. """ p = Person() self.assertEqual( repr(p), "<Person bound=False, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertEqual( repr(p), "<Person bound=True, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>", ) def test_baseform_repr_dont_trigger_validation(self): """ BaseForm.__repr__() shouldn't trigger the form validation. """ p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) repr(p) with self.assertRaises(AttributeError): p.cleaned_data self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {"first_name": "John", "last_name": "Lennon"}) def test_accessing_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data if not self.errors: data["username"] = data["username"].lower() return data f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_nothing_returned(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): self.cleaned_data["username"] = self.cleaned_data["username"].lower() # don't return anything f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_in_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data # Return a different dict. We have not changed self.cleaned_data. return { "username": data["username"].lower(), "password": "this_is_not_a_secret", } f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_multipart_encoded_form(self): class FormWithoutFile(Form): username = CharField() class FormWithFile(Form): username = CharField() file = FileField() class FormWithImage(Form): image = ImageField() self.assertFalse(FormWithoutFile().is_multipart()) self.assertTrue(FormWithFile().is_multipart()) self.assertTrue(FormWithImage().is_multipart()) def test_html_safe(self): class SimpleForm(Form): username = CharField() form = SimpleForm() self.assertTrue(hasattr(SimpleForm, "__html__")) self.assertEqual(str(form), form.__html__()) self.assertTrue(hasattr(form["username"], "__html__")) self.assertEqual(str(form["username"]), form["username"].__html__()) def test_use_required_attribute_true(self): class MyForm(Form): use_required_attribute = True f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text" required></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></p>" '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> ' '<input id="id_f1" maxlength="30" name="f1" type="text" required></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></li>" '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text" required>' "</td></tr>" '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th>' '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label><input id="id_f1" maxlength="30" ' 'name="f1" type="text" required></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div><label ' 'for="id_f3">F3:</label><textarea cols="40" id="id_f3" name="f3" ' 'rows="10" required></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_use_required_attribute_false(self): class MyForm(Form): use_required_attribute = False f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th><td>' '<textarea cols="40" id="id_f3" name="f3" rows="10">' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" ' 'name="f1" type="text"></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div>' '<label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" ' 'rows="10"></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_only_hidden_fields(self): # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>\n<p> " '<input type="hidden" name="data" id="id_data"></p>', ) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>" '<input type="hidden" name="data" id="id_data"></td></tr>', ) def test_field_named_data(self): class DataForm(Form): data = CharField(max_length=10) f = DataForm({"data": "xyzzy"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {"data": "xyzzy"}) def test_empty_data_files_multi_value_dict(self): p = Person() self.assertIsInstance(p.data, MultiValueDict) self.assertIsInstance(p.files, MultiValueDict) def test_field_deep_copy_error_messages(self): class CustomCharField(CharField): def __init__(self, **kwargs): kwargs["error_messages"] = {"invalid": "Form custom error message."} super().__init__(**kwargs) field = CustomCharField() field_copy = copy.deepcopy(field) self.assertIsInstance(field_copy, CustomCharField) self.assertIsNot(field_copy.error_messages, field.error_messages) def test_label_does_not_include_new_line(self): form = Person() field = form["first_name"] self.assertEqual( field.label_tag(), '<label for="id_first_name">First name:</label>' ) self.assertEqual( field.legend_tag(), '<legend for="id_first_name">First name:</legend>', ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_label_attrs_not_localized(self): form = Person() field = form["first_name"] self.assertHTMLEqual( field.label_tag(attrs={"number": 9999}), '<label number="9999" for="id_first_name">First name:</label>', ) self.assertHTMLEqual( field.legend_tag(attrs={"number": 9999}), '<legend number="9999" for="id_first_name">First name:</legend>', ) def test_remove_cached_field(self): class TestForm(Form): name = CharField(max_length=10) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate fields cache. [field for field in self] # Removed cached field. del self.fields["name"] f = TestForm({"name": "abcde"}) with self.assertRaises(KeyError): f["name"] @jinja2_tests class Jinja2FormsTestCase(FormsTestCase): pass class CustomRenderer(DjangoTemplates): form_template_name = "forms_tests/form_snippet.html" class RendererTests(SimpleTestCase): def test_default(self): form = Form() self.assertEqual(form.renderer, get_default_renderer()) def test_kwarg_instance(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_kwarg_class(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_attribute_instance(self): class CustomForm(Form): default_renderer = DjangoTemplates() form = CustomForm() self.assertEqual(form.renderer, CustomForm.default_renderer) def test_attribute_class(self): class CustomForm(Form): default_renderer = CustomRenderer form = CustomForm() self.assertIsInstance(form.renderer, CustomForm.default_renderer) def test_attribute_override(self): class CustomForm(Form): default_renderer = DjangoTemplates() custom = CustomRenderer() form = CustomForm(renderer=custom) self.assertEqual(form.renderer, custom) class TemplateTests(SimpleTestCase): def test_iterate_radios(self): f = FrameworkForm(auto_id="id_%s") t = Template( "{% for radio in form.language %}" '<div class="myradio">{{ radio }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="myradio"><label for="id_language_0">' '<input id="id_language_0" name="language" type="radio" value="P" ' "required> Python</label></div>" '<div class="myradio"><label for="id_language_1">' '<input id="id_language_1" name="language" type="radio" value="J" ' "required> Java</label></div>", ) def test_iterate_checkboxes(self): f = SongForm({"composers": ["J", "P"]}, auto_id=False) t = Template( "{% for checkbox in form.composers %}" '<div class="mycheckbox">{{ checkbox }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="J"> ' "John Lennon</label></div>" '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="P"> ' "Paul McCartney</label></div>", ) def test_templates_with_forms(self): class UserRegistration(Form): username = CharField( max_length=10, help_text=("Good luck picking a username that doesn't already exist."), ) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data # There is full flexibility in displaying form fields in a template. # Just pass a Form instance to the template, and use "dot" access to # refer to individual fields. However, this flexibility comes with the # responsibility of displaying all the errors, including any that might # not be associated with a particular field. t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration({"username": "django"}, auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" '<ul class="errorlist"><li>This field is required.</li></ul><p>' "<label>Password: " '<input type="password" name="password1" required></label></p>' '<ul class="errorlist"><li>This field is required.</li></ul>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label to output a field's label. 'label' for a field # can by specified by using the 'label' argument to a Field class. If # 'label' is not specified, Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. t = Template( "<form>" "<p><label>{{ form.username.label }}: {{ form.username }}</label></p>" "<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>" "<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password1: " '<input type="password" name="password1" required></label></p>' "<p><label>Password2: " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label_tag to output a field's label with a <label> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><label for="id_username">Username:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>" '<p><label for="id_password1">Password1:</label>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><label for="id_password2">Password2:</label>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].legend_tag to output a field's label with a <legend> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.legend_tag }} {{ form.username }}</p>" "<p>{{ form.password1.legend_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.legend_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><legend for="id_username">Username:</legend>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>" '<p><legend for="id_password1">Password1:</legend>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><legend for="id_password2">Password2:</legend>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].help_text to output a field's help text. If the # given field does not have help text, nothing will be output. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}<br>" "{{ form.username.help_text }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required><br>' "Good luck picking a username that doesn&#x27;t already exist.</p>" '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) self.assertEqual( Template("{{ form.password1.help_text }}").render(Context({"form": f})), "", ) # To display the errors that aren't associated with a particular field # e.g. the errors caused by Form.clean() -- use # {{ form.non_field_errors }} in the template. If used on its own, it # is displayed as a <ul> (or an empty string, if the list of errors is # empty). t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration( {"username": "django", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) t = Template( "<form>" "{{ form.non_field_errors }}" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) def test_basic_processing_in_view(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data def my_function(method, post_data): if method == "POST": form = UserRegistration(post_data, auto_id=False) else: form = UserRegistration(auto_id=False) if form.is_valid(): return "VALID: %r" % sorted(form.cleaned_data.items()) t = Template( '<form method="post">' "{{ form }}" '<input type="submit" required>' "</form>" ) return t.render(Context({"form": form})) # GET with an empty form and no errors. self.assertHTMLEqual( my_function("GET", {}), '<form method="post">' "<div>Username:" '<input type="text" name="username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with erroneous data, a redisplayed form, with errors. self.assertHTMLEqual( my_function( "POST", { "username": "this-is-a-long-username", "password1": "foo", "password2": "bar", }, ), '<form method="post">' '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" '<div>Username:<ul class="errorlist">' "<li>Ensure this value has at most 10 characters (it has 23).</li></ul>" '<input type="text" name="username" ' 'value="this-is-a-long-username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with valid data (the success message). self.assertEqual( my_function( "POST", { "username": "adrian", "password1": "secret", "password2": "secret", }, ), "VALID: [('password1', 'secret'), ('password2', 'secret'), " "('username', 'adrian')]", ) class OverrideTests(SimpleTestCase): @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_template_name(self): class Person(Form): first_name = CharField() get_default_renderer.cache_clear() t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) get_default_renderer.cache_clear() def test_per_form_template_name(self): class Person(Form): first_name = CharField() template_name = "forms_tests/form_snippet.html" t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) def test_errorlist_override(self): class CustomErrorList(ErrorList): template_name = "forms_tests/error.html" class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {"email": "invalid"} f = CommentForm(data, auto_id=False, error_class=CustomErrorList) self.assertHTMLEqual( f.as_p(), '<p>Name: <input type="text" name="name" maxlength="50"></p>' '<div class="errorlist">' '<div class="error">Enter a valid email address.</div></div>' '<p>Email: <input type="email" name="email" value="invalid" required></p>' '<div class="errorlist">' '<div class="error">This field is required.</div></div>' '<p>Comment: <input type="text" name="comment" required></p>', ) def test_cyclic_context_boundfield_render(self): class FirstNameForm(Form): first_name = CharField() template_name_label = "forms_tests/cyclic_context_boundfield_render.html" f = FirstNameForm() try: f.render() except RecursionError: self.fail("Cyclic reference in BoundField.render().") def test_legend_tag(self): class CustomFrameworkForm(FrameworkForm): template_name = "forms_tests/legend_test.html" required_css_class = "required" f = CustomFrameworkForm() self.assertHTMLEqual( str(f), '<label for="id_name" class="required">Name:</label>' '<legend class="required">Language:</legend>', )
826ac68bf16fca217ab31602c9f54a838022ba13d331ea589eb946c5883b9390
import gettext import json from os import path from django.conf import settings from django.test import ( RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.test.selenium import SeleniumTestCase from django.urls import reverse from django.utils.translation import get_language, override from django.views.i18n import JavaScriptCatalog, get_formats from ..urls import locale_dir @override_settings(ROOT_URLCONF="view_tests.urls") class SetLanguageTests(TestCase): """Test the django.views.i18n.set_language view.""" def _get_inactive_language_code(self): """Return language code for a language which is not activated.""" current_language = get_language() return [code for code, name in settings.LANGUAGES if code != current_language][ 0 ] def test_setlang(self): """ The set_language view can be used to change the session language. The user is redirected to the 'next' argument if provided. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "/"} response = self.client.post( "/i18n/setlang/", post_data, headers={"referer": "/i_should_not_be_used/"} ) self.assertRedirects(response, "/") # The language is set in a cookie. language_cookie = self.client.cookies[settings.LANGUAGE_COOKIE_NAME] self.assertEqual(language_cookie.value, lang_code) self.assertEqual(language_cookie["domain"], "") self.assertEqual(language_cookie["path"], "/") self.assertEqual(language_cookie["max-age"], "") self.assertEqual(language_cookie["httponly"], "") self.assertEqual(language_cookie["samesite"], "") self.assertEqual(language_cookie["secure"], "") def test_setlang_unsafe_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe". """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "//unsafe/redirection/"} response = self.client.post("/i18n/setlang/", data=post_data) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_http_next(self): """ The set_language view only redirects to the 'next' argument if it is "safe" and its scheme is HTTPS if the request was sent over HTTPS. """ lang_code = self._get_inactive_language_code() non_https_next_url = "http://testserver/redirection/" post_data = {"language": lang_code, "next": non_https_next_url} # Insecure URL in POST data. response = self.client.post("/i18n/setlang/", data=post_data, secure=True) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) # Insecure URL in HTTP referer. response = self.client.post( "/i18n/setlang/", secure=True, headers={"referer": non_https_next_url} ) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_redirect_to_referer(self): """ The set_language view redirects to the URL in the referer header when there isn't a "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} response = self.client.post( "/i18n/setlang/", post_data, headers={"referer": "/i18n/"} ) self.assertRedirects(response, "/i18n/", fetch_redirect_response=False) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_default_redirect(self): """ The set_language view redirects to '/' when there isn't a referer or "next" parameter. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} response = self.client.post("/i18n/setlang/", post_data) self.assertRedirects(response, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_performs_redirect_for_ajax_if_explicitly_requested(self): """ The set_language view redirects to the "next" parameter for requests not accepting HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "/"} response = self.client.post( "/i18n/setlang/", post_data, headers={"accept": "application/json"} ) self.assertRedirects(response, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_doesnt_perform_a_redirect_to_referer_for_ajax(self): """ The set_language view doesn't redirect to the HTTP referer header if the request doesn't accept HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} headers = {"HTTP_REFERER": "/", "HTTP_ACCEPT": "application/json"} response = self.client.post("/i18n/setlang/", post_data, **headers) self.assertEqual(response.status_code, 204) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_doesnt_perform_a_default_redirect_for_ajax(self): """ The set_language view returns 204 by default for requests not accepting HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code} response = self.client.post( "/i18n/setlang/", post_data, headers={"accept": "application/json"} ) self.assertEqual(response.status_code, 204) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_unsafe_next_for_ajax(self): """ The fallback to root URL for the set_language view works for requests not accepting HTML response content. """ lang_code = self._get_inactive_language_code() post_data = {"language": lang_code, "next": "//unsafe/redirection/"} response = self.client.post( "/i18n/setlang/", post_data, headers={"accept": "application/json"} ) self.assertEqual(response.url, "/") self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) def test_setlang_reversal(self): self.assertEqual(reverse("set_language"), "/i18n/setlang/") def test_setlang_cookie(self): # we force saving language to a cookie rather than a session # by excluding session middleware and those which do require it test_settings = { "MIDDLEWARE": ["django.middleware.common.CommonMiddleware"], "LANGUAGE_COOKIE_NAME": "mylanguage", "LANGUAGE_COOKIE_AGE": 3600 * 7 * 2, "LANGUAGE_COOKIE_DOMAIN": ".example.com", "LANGUAGE_COOKIE_PATH": "/test/", "LANGUAGE_COOKIE_HTTPONLY": True, "LANGUAGE_COOKIE_SAMESITE": "Strict", "LANGUAGE_COOKIE_SECURE": True, } with self.settings(**test_settings): post_data = {"language": "pl", "next": "/views/"} response = self.client.post("/i18n/setlang/", data=post_data) language_cookie = response.cookies.get("mylanguage") self.assertEqual(language_cookie.value, "pl") self.assertEqual(language_cookie["domain"], ".example.com") self.assertEqual(language_cookie["path"], "/test/") self.assertEqual(language_cookie["max-age"], 3600 * 7 * 2) self.assertIs(language_cookie["httponly"], True) self.assertEqual(language_cookie["samesite"], "Strict") self.assertIs(language_cookie["secure"], True) def test_setlang_decodes_http_referer_url(self): """ The set_language view decodes the HTTP_REFERER URL and preserves an encoded query string. """ # The URL & view must exist for this to work as a regression test. self.assertEqual( reverse("with_parameter", kwargs={"parameter": "x"}), "/test-setlang/x/" ) lang_code = self._get_inactive_language_code() # %C3%A4 decodes to ä, %26 to &. encoded_url = "/test-setlang/%C3%A4/?foo=bar&baz=alpha%26omega" response = self.client.post( "/i18n/setlang/", {"language": lang_code}, headers={"referer": encoded_url} ) self.assertRedirects(response, encoded_url, fetch_redirect_response=False) self.assertEqual( self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, lang_code ) @modify_settings( MIDDLEWARE={ "append": "django.middleware.locale.LocaleMiddleware", } ) def test_lang_from_translated_i18n_pattern(self): response = self.client.post( "/i18n/setlang/", data={"language": "nl"}, follow=True, headers={"referer": "/en/translated/"}, ) self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "nl") self.assertRedirects(response, "/nl/vertaald/") # And reverse response = self.client.post( "/i18n/setlang/", data={"language": "en"}, follow=True, headers={"referer": "/nl/vertaald/"}, ) self.assertRedirects(response, "/en/translated/") @override_settings(ROOT_URLCONF="view_tests.urls") class I18NViewTests(SimpleTestCase): """Test django.views.i18n views other than set_language.""" @override_settings(LANGUAGE_CODE="de") def test_get_formats(self): formats = get_formats() # Test 3 possible types in get_formats: integer, string, and list. self.assertEqual(formats["FIRST_DAY_OF_WEEK"], 1) self.assertEqual(formats["DECIMAL_SEPARATOR"], ",") self.assertEqual( formats["TIME_INPUT_FORMATS"], ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"] ) def test_jsi18n(self): """The javascript_catalog can be deployed with language settings""" for lang_code in ["es", "fr", "ru"]: with override(lang_code): catalog = gettext.translation("djangojs", locale_dir, [lang_code]) trans_txt = catalog.gettext("this is to be translated") response = self.client.get("/jsi18n/") self.assertEqual( response.headers["Content-Type"], 'text/javascript; charset="utf-8"' ) # response content must include a line like: # "this is to be translated": <value of trans_txt Python variable> # json.dumps() is used to be able to check Unicode strings. self.assertContains(response, json.dumps(trans_txt), 1) if lang_code == "fr": # Message with context (msgctxt) self.assertContains(response, '"month name\\u0004May": "mai"', 1) @override_settings(USE_I18N=False) def test_jsi18n_USE_I18N_False(self): response = self.client.get("/jsi18n/") # default plural function self.assertContains( response, "django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };", ) self.assertNotContains(response, "var newcatalog =") def test_jsoni18n(self): """ The json_catalog returns the language catalog and settings as JSON. """ with override("de"): response = self.client.get("/jsoni18n/") data = json.loads(response.content.decode()) self.assertIn("catalog", data) self.assertIn("formats", data) self.assertEqual( data["formats"]["TIME_INPUT_FORMATS"], ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"], ) self.assertEqual(data["formats"]["FIRST_DAY_OF_WEEK"], 1) self.assertIn("plural", data) self.assertEqual(data["catalog"]["month name\x04May"], "Mai") self.assertIn("DATETIME_FORMAT", data["formats"]) self.assertEqual(data["plural"], "(n != 1)") def test_jsi18n_with_missing_en_files(self): """ The javascript_catalog shouldn't load the fallback language in the case that the current selected language is actually the one translated from, and hence missing translation files completely. This happens easily when you're translating from English to other languages and you've set settings.LANGUAGE_CODE to some other language than English. """ with self.settings(LANGUAGE_CODE="es"), override("en-us"): response = self.client.get("/jsi18n/") self.assertNotContains(response, "esto tiene que ser traducido") def test_jsoni18n_with_missing_en_files(self): """ Same as above for the json_catalog view. Here we also check for the expected JSON format. """ with self.settings(LANGUAGE_CODE="es"), override("en-us"): response = self.client.get("/jsoni18n/") data = json.loads(response.content.decode()) self.assertIn("catalog", data) self.assertIn("formats", data) self.assertIn("plural", data) self.assertEqual(data["catalog"], {}) self.assertIn("DATETIME_FORMAT", data["formats"]) self.assertIsNone(data["plural"]) def test_jsi18n_fallback_language(self): """ Let's make sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), override("fi"): response = self.client.get("/jsi18n/") self.assertContains(response, "il faut le traduire") self.assertNotContains(response, "Untranslated string") def test_jsi18n_fallback_language_with_custom_locale_dir(self): """ The fallback language works when there are several levels of fallback translation catalogs. """ locale_paths = [ path.join( path.dirname(path.dirname(path.abspath(__file__))), "custom_locale_path", ), ] with self.settings(LOCALE_PATHS=locale_paths), override("es_MX"): response = self.client.get("/jsi18n/") self.assertContains( response, "custom_locale_path: esto tiene que ser traducido" ) response = self.client.get("/jsi18n_no_packages/") self.assertContains( response, "custom_locale_path: esto tiene que ser traducido" ) def test_i18n_fallback_language_plural(self): """ The fallback to a language with less plural forms maintains the real language's number of plural forms and correct translations. """ with self.settings(LANGUAGE_CODE="pt"), override("ru"): response = self.client.get("/jsi18n/") self.assertEqual( response.context["catalog"]["{count} plural3"], ["{count} plural3 p3", "{count} plural3 p3s", "{count} plural3 p3t"], ) self.assertEqual( response.context["catalog"]["{count} plural2"], ["{count} plural2", "{count} plural2s", ""], ) with self.settings(LANGUAGE_CODE="ru"), override("pt"): response = self.client.get("/jsi18n/") self.assertEqual( response.context["catalog"]["{count} plural3"], ["{count} plural3", "{count} plural3s"], ) self.assertEqual( response.context["catalog"]["{count} plural2"], ["{count} plural2", "{count} plural2s"], ) def test_i18n_english_variant(self): with override("en-gb"): response = self.client.get("/jsi18n/") self.assertIn( '"this color is to be translated": "this colour is to be translated"', response.context["catalog_str"], ) def test_i18n_language_non_english_default(self): """ Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English, the selected language is English and there is not 'en' translation available. See #13388, #3594 and #13726 for more details. """ with self.settings(LANGUAGE_CODE="fr"), override("en-us"): response = self.client.get("/jsi18n/") self.assertNotContains(response, "Choisir une heure") @modify_settings(INSTALLED_APPS={"append": "view_tests.app0"}) def test_non_english_default_english_userpref(self): """ Same as above with the difference that there IS an 'en' translation available. The JavaScript i18n view must return a NON empty language catalog with the proper English translations. See #13726 for more details. """ with self.settings(LANGUAGE_CODE="fr"), override("en-us"): response = self.client.get("/jsi18n_english_translation/") self.assertContains(response, "this app0 string is to be translated") def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), override("none"): response = self.client.get("/jsi18n/") self.assertContains(response, "Choisir une heure") def test_escaping(self): # Force a language via GET otherwise the gettext functions are a noop! response = self.client.get("/jsi18n_admin/?language=de") self.assertContains(response, "\\x04") @modify_settings(INSTALLED_APPS={"append": ["view_tests.app5"]}) def test_non_BMP_char(self): """ Non-BMP characters should not break the javascript_catalog (#21725). """ with self.settings(LANGUAGE_CODE="en-us"), override("fr"): response = self.client.get("/jsi18n/app5/") self.assertContains(response, "emoji") self.assertContains(response, "\\ud83d\\udca9") @modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]}) def test_i18n_language_english_default(self): """ Check if the JavaScript i18n view returns a complete language catalog if the default language is en-us, the selected language has a translation available and a catalog composed by djangojs domain translations of multiple Python packages is requested. See #13388, #3594 and #13514 for more details. """ base_trans_string = ( "il faut traduire cette cha\\u00eene de caract\\u00e8res de " ) app1_trans_string = base_trans_string + "app1" app2_trans_string = base_trans_string + "app2" with self.settings(LANGUAGE_CODE="en-us"), override("fr"): response = self.client.get("/jsi18n_multi_packages1/") self.assertContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) response = self.client.get("/jsi18n/app1/") self.assertContains(response, app1_trans_string) self.assertNotContains(response, app2_trans_string) response = self.client.get("/jsi18n/app2/") self.assertNotContains(response, app1_trans_string) self.assertContains(response, app2_trans_string) @modify_settings(INSTALLED_APPS={"append": ["view_tests.app3", "view_tests.app4"]}) def test_i18n_different_non_english_languages(self): """ Similar to above but with neither default or requested language being English. """ with self.settings(LANGUAGE_CODE="fr"), override("es-ar"): response = self.client.get("/jsi18n_multi_packages2/") self.assertContains(response, "este texto de app3 debe ser traducido") def test_i18n_with_locale_paths(self): extended_locale_paths = settings.LOCALE_PATHS + [ path.join( path.dirname(path.dirname(path.abspath(__file__))), "app3", "locale", ), ] with self.settings(LANGUAGE_CODE="es-ar", LOCALE_PATHS=extended_locale_paths): with override("es-ar"): response = self.client.get("/jsi18n/") self.assertContains(response, "este texto de app3 debe ser traducido") def test_i18n_unknown_package_error(self): view = JavaScriptCatalog.as_view() request = RequestFactory().get("/") msg = "Invalid package(s) provided to JavaScriptCatalog: unknown_package" with self.assertRaisesMessage(ValueError, msg): view(request, packages="unknown_package") msg += ",unknown_package2" with self.assertRaisesMessage(ValueError, msg): view(request, packages="unknown_package+unknown_package2") @override_settings(ROOT_URLCONF="view_tests.urls") class I18nSeleniumTests(SeleniumTestCase): # The test cases use fixtures & translations from these apps. available_apps = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "view_tests", ] @override_settings(LANGUAGE_CODE="de") def test_javascript_gettext(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + "/jsi18n_template/") elem = self.selenium.find_element(By.ID, "gettext") self.assertEqual(elem.text, "Entfernen") elem = self.selenium.find_element(By.ID, "ngettext_sing") self.assertEqual(elem.text, "1 Element") elem = self.selenium.find_element(By.ID, "ngettext_plur") self.assertEqual(elem.text, "455 Elemente") elem = self.selenium.find_element(By.ID, "ngettext_onnonplural") self.assertEqual(elem.text, "Bild") elem = self.selenium.find_element(By.ID, "pgettext") self.assertEqual(elem.text, "Kann") elem = self.selenium.find_element(By.ID, "npgettext_sing") self.assertEqual(elem.text, "1 Resultat") elem = self.selenium.find_element(By.ID, "npgettext_plur") self.assertEqual(elem.text, "455 Resultate") elem = self.selenium.find_element(By.ID, "formats") self.assertEqual( elem.text, "DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; " "FIRST_DAY_OF_WEEK is a number;", ) @modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]}) @override_settings(LANGUAGE_CODE="fr") def test_multiple_catalogs(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + "/jsi18n_multi_catalogs/") elem = self.selenium.find_element(By.ID, "app1string") self.assertEqual( elem.text, "il faut traduire cette chaîne de caractères de app1" ) elem = self.selenium.find_element(By.ID, "app2string") self.assertEqual( elem.text, "il faut traduire cette chaîne de caractères de app2" )
a5aa692f6b83ed2e4a8fdd73d624fca1018f9267204603d640f8181bf3c4f8e1
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("migrations2", "0001_initial")] operations = [ migrations.CreateModel( "Bookstore", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ], ), ]
28a66eba8e1d53baefa07b4bdd9f405e48a99ca4c02ce9aef45b88dcecab2185
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("migrations", "__first__"), ] operations = [ migrations.CreateModel( "OtherAuthor", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), ]
a945d78282b179a8660119a460e8db0a78ff2f12260b2ea457c9373fdd97ecc9
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( "OtherAuthor", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), ]
1191ceb9a233b1b33b1c1a2404cd777effe6f49823b689e7b9edf98f83117d07
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("migrations", "0002_second")] operations = [ migrations.CreateModel( "OtherAuthor", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), ]
79e63ea4a1c24aad20e155982b391c43fda98287b1000391bc696dfd636fb2c7
from datetime import datetime, timedelta from django.template.defaultfilters import timeuntil_filter from django.test import SimpleTestCase from django.test.utils import requires_tz_support from ..utils import setup from .timezone_utils import TimezoneTestCase class TimeuntilTests(TimezoneTestCase): # Default compare with datetime.now() @setup({"timeuntil01": "{{ a|timeuntil }}"}) def test_timeuntil01(self): output = self.engine.render_to_string( "timeuntil01", {"a": datetime.now() + timedelta(minutes=2, seconds=10)} ) self.assertEqual(output, "2\xa0minutes") @setup({"timeuntil02": "{{ a|timeuntil }}"}) def test_timeuntil02(self): output = self.engine.render_to_string( "timeuntil02", {"a": (datetime.now() + timedelta(days=1, seconds=10))} ) self.assertEqual(output, "1\xa0day") @setup({"timeuntil03": "{{ a|timeuntil }}"}) def test_timeuntil03(self): output = self.engine.render_to_string( "timeuntil03", {"a": (datetime.now() + timedelta(hours=8, minutes=10, seconds=10))}, ) self.assertEqual(output, "8\xa0hours, 10\xa0minutes") # Compare to a given parameter @setup({"timeuntil04": "{{ a|timeuntil:b }}"}) def test_timeuntil04(self): output = self.engine.render_to_string( "timeuntil04", {"a": self.now - timedelta(days=1), "b": self.now - timedelta(days=2)}, ) self.assertEqual(output, "1\xa0day") @setup({"timeuntil05": "{{ a|timeuntil:b }}"}) def test_timeuntil05(self): output = self.engine.render_to_string( "timeuntil05", { "a": self.now - timedelta(days=2), "b": self.now - timedelta(days=2, minutes=1), }, ) self.assertEqual(output, "1\xa0minute") # Regression for #7443 @setup({"timeuntil06": "{{ earlier|timeuntil }}"}) def test_timeuntil06(self): output = self.engine.render_to_string( "timeuntil06", {"earlier": self.now - timedelta(days=7)} ) self.assertEqual(output, "0\xa0minutes") @setup({"timeuntil07": "{{ earlier|timeuntil:now }}"}) def test_timeuntil07(self): output = self.engine.render_to_string( "timeuntil07", {"now": self.now, "earlier": self.now - timedelta(days=7)} ) self.assertEqual(output, "0\xa0minutes") @setup({"timeuntil08": "{{ later|timeuntil }}"}) def test_timeuntil08(self): output = self.engine.render_to_string( "timeuntil08", {"later": self.now + timedelta(days=7, hours=1)} ) self.assertEqual(output, "1\xa0week") @setup({"timeuntil09": "{{ later|timeuntil:now }}"}) def test_timeuntil09(self): output = self.engine.render_to_string( "timeuntil09", {"now": self.now, "later": self.now + timedelta(days=7)} ) self.assertEqual(output, "1\xa0week") # Differing timezones are calculated correctly. @requires_tz_support @setup({"timeuntil10": "{{ a|timeuntil }}"}) def test_timeuntil10(self): output = self.engine.render_to_string("timeuntil10", {"a": self.now_tz}) self.assertEqual(output, "0\xa0minutes") @requires_tz_support @setup({"timeuntil11": "{{ a|timeuntil }}"}) def test_timeuntil11(self): output = self.engine.render_to_string("timeuntil11", {"a": self.now_tz_i}) self.assertEqual(output, "0\xa0minutes") @setup({"timeuntil12": "{{ a|timeuntil:b }}"}) def test_timeuntil12(self): output = self.engine.render_to_string( "timeuntil12", {"a": self.now_tz_i, "b": self.now_tz} ) self.assertEqual(output, "0\xa0minutes") # Regression for #9065 (two date objects). @setup({"timeuntil13": "{{ a|timeuntil:b }}"}) def test_timeuntil13(self): output = self.engine.render_to_string( "timeuntil13", {"a": self.today, "b": self.today} ) self.assertEqual(output, "0\xa0minutes") @setup({"timeuntil14": "{{ a|timeuntil:b }}"}) def test_timeuntil14(self): output = self.engine.render_to_string( "timeuntil14", {"a": self.today, "b": self.today - timedelta(hours=24)} ) self.assertEqual(output, "1\xa0day") @setup({"timeuntil15": "{{ a|timeuntil:b }}"}) def test_naive_aware_type_error(self): output = self.engine.render_to_string( "timeuntil15", {"a": self.now, "b": self.now_tz_i} ) self.assertEqual(output, "") @setup({"timeuntil16": "{{ a|timeuntil:b }}"}) def test_aware_naive_type_error(self): output = self.engine.render_to_string( "timeuntil16", {"a": self.now_tz_i, "b": self.now} ) self.assertEqual(output, "") class FunctionTests(SimpleTestCase): def test_until_now(self): self.assertEqual(timeuntil_filter(datetime.now() + timedelta(1, 1)), "1\xa0day") def test_no_args(self): self.assertEqual(timeuntil_filter(None), "") def test_explicit_date(self): self.assertEqual( timeuntil_filter(datetime(2005, 12, 30), datetime(2005, 12, 29)), "1\xa0day" )
89dca916fea89860b9aac69bad4624e33cb77df382a10cf9f1841a55d6e38b4a
from decimal import Decimal, localcontext from django.template.defaultfilters import floatformat from django.test import SimpleTestCase from django.utils import translation from django.utils.safestring import mark_safe from ..utils import setup class FloatformatTests(SimpleTestCase): @setup( { "floatformat01": ( "{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}" "{% endautoescape %}" ) } ) def test_floatformat01(self): output = self.engine.render_to_string( "floatformat01", {"a": "1.42", "b": mark_safe("1.42")} ) self.assertEqual(output, "1.4 1.4") @setup({"floatformat02": "{{ a|floatformat }} {{ b|floatformat }}"}) def test_floatformat02(self): output = self.engine.render_to_string( "floatformat02", {"a": "1.42", "b": mark_safe("1.42")} ) self.assertEqual(output, "1.4 1.4") class FunctionTests(SimpleTestCase): def test_inputs(self): self.assertEqual(floatformat(7.7), "7.7") self.assertEqual(floatformat(7.0), "7") self.assertEqual(floatformat(0.7), "0.7") self.assertEqual(floatformat(-0.7), "-0.7") self.assertEqual(floatformat(0.07), "0.1") self.assertEqual(floatformat(-0.07), "-0.1") self.assertEqual(floatformat(0.007), "0.0") self.assertEqual(floatformat(0.0), "0") self.assertEqual(floatformat(7.7, 0), "8") self.assertEqual(floatformat(7.7, 3), "7.700") self.assertEqual(floatformat(6.000000, 3), "6.000") self.assertEqual(floatformat(6.200000, 3), "6.200") self.assertEqual(floatformat(6.200000, -3), "6.200") self.assertEqual(floatformat(13.1031, -3), "13.103") self.assertEqual(floatformat(11.1197, -2), "11.12") self.assertEqual(floatformat(11.0000, -2), "11") self.assertEqual(floatformat(11.000001, -2), "11.00") self.assertEqual(floatformat(8.2798, 3), "8.280") self.assertEqual(floatformat(5555.555, 2), "5555.56") self.assertEqual(floatformat(001.3000, 2), "1.30") self.assertEqual(floatformat(0.12345, 2), "0.12") self.assertEqual(floatformat(Decimal("555.555"), 2), "555.56") self.assertEqual(floatformat(Decimal("09.000")), "9") self.assertEqual( floatformat(Decimal("123456.123456789012345678901"), 21), "123456.123456789012345678901", ) self.assertEqual(floatformat("foo"), "") self.assertEqual(floatformat(13.1031, "bar"), "13.1031") self.assertEqual(floatformat(18.125, 2), "18.13") self.assertEqual(floatformat("foo", "bar"), "") self.assertEqual(floatformat("¿Cómo esta usted?"), "") self.assertEqual(floatformat(None), "") self.assertEqual( floatformat(-1.323297138040798e35, 2), "-132329713804079800000000000000000000.00", ) self.assertEqual( floatformat(-1.323297138040798e35, -2), "-132329713804079800000000000000000000", ) self.assertEqual(floatformat(1.5e-15, 20), "0.00000000000000150000") self.assertEqual(floatformat(1.5e-15, -20), "0.00000000000000150000") self.assertEqual(floatformat(1.00000000000000015, 16), "1.0000000000000002") def test_force_grouping(self): with translation.override("en"): self.assertEqual(floatformat(10000, "g"), "10,000") self.assertEqual(floatformat(66666.666, "1g"), "66,666.7") # Invalid suffix. self.assertEqual(floatformat(10000, "g2"), "10000") with translation.override("de", deactivate=True): self.assertEqual(floatformat(10000, "g"), "10.000") self.assertEqual(floatformat(66666.666, "1g"), "66.666,7") # Invalid suffix. self.assertEqual(floatformat(10000, "g2"), "10000") def test_unlocalize(self): with translation.override("de", deactivate=True): self.assertEqual(floatformat(66666.666, "2"), "66666,67") self.assertEqual(floatformat(66666.666, "2u"), "66666.67") with self.settings( USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=3, THOUSAND_SEPARATOR="!", ): self.assertEqual(floatformat(66666.666, "2gu"), "66!666.67") self.assertEqual(floatformat(66666.666, "2ug"), "66!666.67") # Invalid suffix. self.assertEqual(floatformat(66666.666, "u2"), "66666.666") def test_zero_values(self): self.assertEqual(floatformat(0, 6), "0.000000") self.assertEqual(floatformat(0, 7), "0.0000000") self.assertEqual(floatformat(0, 10), "0.0000000000") self.assertEqual( floatformat(0.000000000000000000015, 20), "0.00000000000000000002" ) self.assertEqual(floatformat("0.00", 0), "0") self.assertEqual(floatformat(Decimal("0.00"), 0), "0") def test_negative_zero_values(self): tests = [ (-0.01, -1, "0.0"), (-0.001, 2, "0.00"), (-0.499, 0, "0"), ] for num, decimal_places, expected in tests: with self.subTest(num=num, decimal_places=decimal_places): self.assertEqual(floatformat(num, decimal_places), expected) def test_infinity(self): pos_inf = float(1e30000) neg_inf = float(-1e30000) self.assertEqual(floatformat(pos_inf), "inf") self.assertEqual(floatformat(neg_inf), "-inf") self.assertEqual(floatformat(pos_inf / pos_inf), "nan") def test_float_dunder_method(self): class FloatWrapper: def __init__(self, value): self.value = value def __float__(self): return self.value self.assertEqual(floatformat(FloatWrapper(11.000001), -2), "11.00") def test_low_decimal_precision(self): """ #15789 """ with localcontext() as ctx: ctx.prec = 2 self.assertEqual(floatformat(1.2345, 2), "1.23") self.assertEqual(floatformat(15.2042, -3), "15.204") self.assertEqual(floatformat(1.2345, "2"), "1.23") self.assertEqual(floatformat(15.2042, "-3"), "15.204") self.assertEqual(floatformat(Decimal("1.2345"), 2), "1.23") self.assertEqual(floatformat(Decimal("15.2042"), -3), "15.204")
6d401c77b68130603091b25b7f70741ef3fe9d62ce93bc697b675b0964a7d816
from django.template import Context, Template from django.test import SimpleTestCase from django.utils import translation from ...utils import setup from .base import MultipleLocaleActivationTestCase class MultipleLocaleActivationTests(MultipleLocaleActivationTestCase): def test_single_locale_activation(self): """ Simple baseline behavior with one locale for all the supported i18n constructs. """ with translation.override("fr"): self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), "Oui") # Literal marked up with _() in a filter expression def test_multiple_locale_filter(self): with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_deactivate(self): with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "nee") def test_multiple_locale_filter_direct_switch(self): with translation.override("de"): t = Template("{% load i18n %}{{ 0|yesno:_('yes,no,maybe') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "nee") # Literal marked up with _() def test_multiple_locale(self): with translation.override("de"): t = Template("{{ _('No') }}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_deactivate(self): with translation.override("de", deactivate=True): t = Template("{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_direct_switch(self): with translation.override("de"): t = Template("{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") # Literal marked up with _(), loading the i18n template tag library def test_multiple_locale_loadi18n(self): with translation.override("de"): t = Template("{% load i18n %}{{ _('No') }}") with translation.override(self._old_language), translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_loadi18n_deactivate(self): with translation.override("de", deactivate=True): t = Template("{% load i18n %}{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") def test_multiple_locale_loadi18n_direct_switch(self): with translation.override("de"): t = Template("{% load i18n %}{{ _('No') }}") with translation.override("nl"): self.assertEqual(t.render(Context({})), "Nee") class I18nStringLiteralTests(SimpleTestCase): """translation of constant strings""" libraries = {"i18n": "django.templatetags.i18n"} @setup({"i18n13": '{{ _("Password") }}'}) def test_i18n13(self): with translation.override("de"): output = self.engine.render_to_string("i18n13") self.assertEqual(output, "Passwort") @setup( { "i18n14": ( '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} ' "{% cycle c %}" ) } ) def test_i18n14(self): with translation.override("de"): output = self.engine.render_to_string("i18n14") self.assertEqual(output, "foo Passwort Passwort") @setup({"i18n15": '{{ absent|default:_("Password") }}'}) def test_i18n15(self): with translation.override("de"): output = self.engine.render_to_string("i18n15", {"absent": ""}) self.assertEqual(output, "Passwort") @setup({"i18n16": '{{ _("<") }}'}) def test_i18n16(self): with translation.override("de"): output = self.engine.render_to_string("i18n16") self.assertEqual(output, "<")
c14e6117d6545358b08b60bd5453ff14ced6ed281b766a807ec6b47bff91ceae
from datetime import date, datetime from django.conf.urls.i18n import i18n_patterns from django.contrib.sitemaps import GenericSitemap, Sitemap, views from django.http import HttpResponse from django.urls import path from django.utils import timezone from django.views.decorators.cache import cache_page from ..models import I18nTestModel, TestModel class SimpleSitemap(Sitemap): changefreq = "never" priority = 0.5 location = "/location/" lastmod = date.today() def items(self): return [object()] class SimplePagedSitemap(Sitemap): lastmod = date.today() def items(self): return [object() for x in range(Sitemap.limit + 1)] class SimpleI18nSitemap(Sitemap): changefreq = "never" priority = 0.5 i18n = True def items(self): return I18nTestModel.objects.order_by("pk").all() class AlternatesI18nSitemap(SimpleI18nSitemap): alternates = True class LimitedI18nSitemap(AlternatesI18nSitemap): languages = ["en", "es"] class XDefaultI18nSitemap(AlternatesI18nSitemap): x_default = True class ItemByLangSitemap(SimpleI18nSitemap): def get_languages_for_item(self, item): if item.name == "Only for PT": return ["pt"] return super().get_languages_for_item(item) class ItemByLangAlternatesSitemap(AlternatesI18nSitemap): x_default = True def get_languages_for_item(self, item): if item.name == "Only for PT": return ["pt"] return super().get_languages_for_item(item) class EmptySitemap(Sitemap): changefreq = "never" priority = 0.5 location = "/location/" class FixedLastmodSitemap(SimpleSitemap): lastmod = datetime(2013, 3, 13, 10, 0, 0) class FixedLastmodMixedSitemap(Sitemap): changefreq = "never" priority = 0.5 location = "/location/" loop = 0 def items(self): o1 = TestModel() o1.lastmod = datetime(2013, 3, 13, 10, 0, 0) o2 = TestModel() return [o1, o2] class FixedNewerLastmodSitemap(SimpleSitemap): lastmod = datetime(2013, 4, 20, 5, 0, 0) class DateSiteMap(SimpleSitemap): lastmod = date(2013, 3, 13) class TimezoneSiteMap(SimpleSitemap): lastmod = datetime(2013, 3, 13, 10, 0, 0, tzinfo=timezone.get_fixed_timezone(-300)) class CallableLastmodPartialSitemap(Sitemap): """Not all items have `lastmod`.""" location = "/location/" def items(self): o1 = TestModel() o1.lastmod = datetime(2013, 3, 13, 10, 0, 0) o2 = TestModel() return [o1, o2] def lastmod(self, obj): return obj.lastmod class CallableLastmodFullSitemap(Sitemap): """All items have `lastmod`.""" location = "/location/" def items(self): o1 = TestModel() o1.lastmod = datetime(2013, 3, 13, 10, 0, 0) o2 = TestModel() o2.lastmod = datetime(2014, 3, 13, 10, 0, 0) return [o1, o2] def lastmod(self, obj): return obj.lastmod class CallableLastmodNoItemsSitemap(Sitemap): location = "/location/" def items(self): return [] def lastmod(self, obj): return obj.lastmod class GetLatestLastmodNoneSiteMap(Sitemap): changefreq = "never" priority = 0.5 location = "/location/" def items(self): return [object()] def lastmod(self, obj): return datetime(2013, 3, 13, 10, 0, 0) def get_latest_lastmod(self): return None class GetLatestLastmodSiteMap(SimpleSitemap): def get_latest_lastmod(self): return datetime(2013, 3, 13, 10, 0, 0) def testmodelview(request, id): return HttpResponse() simple_sitemaps = { "simple": SimpleSitemap, } simple_i18n_sitemaps = { "i18n": SimpleI18nSitemap, } alternates_i18n_sitemaps = { "i18n-alternates": AlternatesI18nSitemap, } limited_i18n_sitemaps = { "i18n-limited": LimitedI18nSitemap, } xdefault_i18n_sitemaps = { "i18n-xdefault": XDefaultI18nSitemap, } item_by_lang_i18n_sitemaps = { "i18n-item-by-lang": ItemByLangSitemap, } item_by_lang_alternates_i18n_sitemaps = { "i18n-item-by-lang-alternates": ItemByLangAlternatesSitemap, } simple_sitemaps_not_callable = { "simple": SimpleSitemap(), } simple_sitemaps_paged = { "simple": SimplePagedSitemap, } empty_sitemaps = { "empty": EmptySitemap, } fixed_lastmod_sitemaps = { "fixed-lastmod": FixedLastmodSitemap, } fixed_lastmod_mixed_sitemaps = { "fixed-lastmod-mixed": FixedLastmodMixedSitemap, } sitemaps_lastmod_mixed_ascending = { "no-lastmod": EmptySitemap, "lastmod": FixedLastmodSitemap, } sitemaps_lastmod_mixed_descending = { "lastmod": FixedLastmodSitemap, "no-lastmod": EmptySitemap, } sitemaps_lastmod_ascending = { "date": DateSiteMap, "datetime": FixedLastmodSitemap, "datetime-newer": FixedNewerLastmodSitemap, } sitemaps_lastmod_descending = { "datetime-newer": FixedNewerLastmodSitemap, "datetime": FixedLastmodSitemap, "date": DateSiteMap, } generic_sitemaps = { "generic": GenericSitemap({"queryset": TestModel.objects.order_by("pk").all()}), } get_latest_lastmod_none_sitemaps = { "get-latest-lastmod-none": GetLatestLastmodNoneSiteMap, } get_latest_lastmod_sitemaps = { "get-latest-lastmod": GetLatestLastmodSiteMap, } latest_lastmod_timezone_sitemaps = { "latest-lastmod-timezone": TimezoneSiteMap, } generic_sitemaps_lastmod = { "generic": GenericSitemap( { "queryset": TestModel.objects.order_by("pk").all(), "date_field": "lastmod", } ), } callable_lastmod_partial_sitemap = { "callable-lastmod": CallableLastmodPartialSitemap, } callable_lastmod_full_sitemap = { "callable-lastmod": CallableLastmodFullSitemap, } callable_lastmod_no_items_sitemap = { "callable-lastmod": CallableLastmodNoItemsSitemap, } urlpatterns = [ path("simple/index.xml", views.index, {"sitemaps": simple_sitemaps}), path("simple-paged/index.xml", views.index, {"sitemaps": simple_sitemaps_paged}), path( "simple-not-callable/index.xml", views.index, {"sitemaps": simple_sitemaps_not_callable}, ), path( "simple/custom-lastmod-index.xml", views.index, { "sitemaps": simple_sitemaps, "template_name": "custom_sitemap_lastmod_index.xml", }, ), path( "simple/sitemap-<section>.xml", views.sitemap, {"sitemaps": simple_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "simple/sitemap.xml", views.sitemap, {"sitemaps": simple_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "simple/i18n.xml", views.sitemap, {"sitemaps": simple_i18n_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "alternates/i18n.xml", views.sitemap, {"sitemaps": alternates_i18n_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "limited/i18n.xml", views.sitemap, {"sitemaps": limited_i18n_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "x-default/i18n.xml", views.sitemap, {"sitemaps": xdefault_i18n_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "simple/custom-sitemap.xml", views.sitemap, {"sitemaps": simple_sitemaps, "template_name": "custom_sitemap.xml"}, name="django.contrib.sitemaps.views.sitemap", ), path( "empty/sitemap.xml", views.sitemap, {"sitemaps": empty_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod/sitemap.xml", views.sitemap, {"sitemaps": fixed_lastmod_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod-mixed/sitemap.xml", views.sitemap, {"sitemaps": fixed_lastmod_mixed_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod/date-sitemap.xml", views.sitemap, {"sitemaps": {"date-sitemap": DateSiteMap}}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod/tz-sitemap.xml", views.sitemap, {"sitemaps": {"tz-sitemap": TimezoneSiteMap}}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod-sitemaps/mixed-ascending.xml", views.sitemap, {"sitemaps": sitemaps_lastmod_mixed_ascending}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod-sitemaps/mixed-descending.xml", views.sitemap, {"sitemaps": sitemaps_lastmod_mixed_descending}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod-sitemaps/ascending.xml", views.sitemap, {"sitemaps": sitemaps_lastmod_ascending}, name="django.contrib.sitemaps.views.sitemap", ), path( "item-by-lang/i18n.xml", views.sitemap, {"sitemaps": item_by_lang_i18n_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "item-by-lang-alternates/i18n.xml", views.sitemap, {"sitemaps": item_by_lang_alternates_i18n_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod-sitemaps/descending.xml", views.sitemap, {"sitemaps": sitemaps_lastmod_descending}, name="django.contrib.sitemaps.views.sitemap", ), path( "lastmod/get-latest-lastmod-none-sitemap.xml", views.index, {"sitemaps": get_latest_lastmod_none_sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "lastmod/get-latest-lastmod-sitemap.xml", views.index, {"sitemaps": get_latest_lastmod_sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "lastmod/latest-lastmod-timezone-sitemap.xml", views.index, {"sitemaps": latest_lastmod_timezone_sitemaps}, name="django.contrib.sitemaps.views.index", ), path( "generic/sitemap.xml", views.sitemap, {"sitemaps": generic_sitemaps}, name="django.contrib.sitemaps.views.sitemap", ), path( "generic-lastmod/sitemap.xml", views.sitemap, {"sitemaps": generic_sitemaps_lastmod}, name="django.contrib.sitemaps.views.sitemap", ), path( "cached/index.xml", cache_page(1)(views.index), {"sitemaps": simple_sitemaps, "sitemap_url_name": "cached_sitemap"}, ), path( "cached/sitemap-<section>.xml", cache_page(1)(views.sitemap), {"sitemaps": simple_sitemaps}, name="cached_sitemap", ), path( "sitemap-without-entries/sitemap.xml", views.sitemap, {"sitemaps": {}}, name="django.contrib.sitemaps.views.sitemap", ), path( "callable-lastmod-partial/index.xml", views.index, {"sitemaps": callable_lastmod_partial_sitemap}, ), path( "callable-lastmod-partial/sitemap.xml", views.sitemap, {"sitemaps": callable_lastmod_partial_sitemap}, ), path( "callable-lastmod-full/index.xml", views.index, {"sitemaps": callable_lastmod_full_sitemap}, ), path( "callable-lastmod-full/sitemap.xml", views.sitemap, {"sitemaps": callable_lastmod_full_sitemap}, ), path( "callable-lastmod-no-items/index.xml", views.index, {"sitemaps": callable_lastmod_no_items_sitemap}, ), path( "generic-lastmod/index.xml", views.index, {"sitemaps": generic_sitemaps_lastmod}, name="django.contrib.sitemaps.views.index", ), ] urlpatterns += i18n_patterns( path("i18n/testmodel/<int:id>/", testmodelview, name="i18n_testmodel"), )
7043dab6e1d2078bc5ed36b18a1e9a4ca82fcc7108a157d1ce86bca0fd1ebcf3
import os import re import tempfile import threading import unittest from pathlib import Path from unittest import mock from django.db import NotSupportedError, connection, transaction from django.db.models import Aggregate, Avg, CharField, StdDev, Sum, Variance from django.db.utils import ConnectionHandler from django.test import ( TestCase, TransactionTestCase, override_settings, skipIfDBFeature, ) from django.test.utils import isolate_apps from ..models import Author, Item, Object, Square @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class Tests(TestCase): longMessage = True def test_aggregation(self): """Raise NotSupportedError when aggregating on date/time fields.""" for aggregate in (Sum, Avg, Variance, StdDev): with self.assertRaises(NotSupportedError): Item.objects.aggregate(aggregate("time")) with self.assertRaises(NotSupportedError): Item.objects.aggregate(aggregate("date")) with self.assertRaises(NotSupportedError): Item.objects.aggregate(aggregate("last_modified")) with self.assertRaises(NotSupportedError): Item.objects.aggregate( **{ "complex": aggregate("last_modified") + aggregate("last_modified") } ) def test_distinct_aggregation(self): class DistinctAggregate(Aggregate): allow_distinct = True aggregate = DistinctAggregate("first", "second", distinct=True) msg = ( "SQLite doesn't support DISTINCT on aggregate functions accepting " "multiple arguments." ) with self.assertRaisesMessage(NotSupportedError, msg): connection.ops.check_expression_support(aggregate) def test_distinct_aggregation_multiple_args_no_distinct(self): # Aggregate functions accept multiple arguments when DISTINCT isn't # used, e.g. GROUP_CONCAT(). class DistinctAggregate(Aggregate): allow_distinct = True aggregate = DistinctAggregate("first", "second", distinct=False) connection.ops.check_expression_support(aggregate) def test_memory_db_test_name(self): """A named in-memory db should be allowed where supported.""" from django.db.backends.sqlite3.base import DatabaseWrapper settings_dict = { "TEST": { "NAME": "file:memorydb_test?mode=memory&cache=shared", } } creation = DatabaseWrapper(settings_dict).creation self.assertEqual( creation._get_test_db_name(), creation.connection.settings_dict["TEST"]["NAME"], ) def test_regexp_function(self): tests = ( ("test", r"[0-9]+", False), ("test", r"[a-z]+", True), ("test", None, None), (None, r"[a-z]+", None), (None, None, None), ) for string, pattern, expected in tests: with self.subTest((string, pattern)): with connection.cursor() as cursor: cursor.execute("SELECT %s REGEXP %s", [string, pattern]) value = cursor.fetchone()[0] value = bool(value) if value in {0, 1} else value self.assertIs(value, expected) def test_pathlib_name(self): with tempfile.TemporaryDirectory() as tmp: settings_dict = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": Path(tmp) / "test.db", }, } connections = ConnectionHandler(settings_dict) connections["default"].ensure_connection() connections["default"].close() self.assertTrue(os.path.isfile(os.path.join(tmp, "test.db"))) @mock.patch.object(connection, "get_database_version", return_value=(3, 20)) def test_check_database_version_supported(self, mocked_get_database_version): msg = "SQLite 3.21 or later is required (found 3.20)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called) @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") @isolate_apps("backends") class SchemaTests(TransactionTestCase): available_apps = ["backends"] def test_autoincrement(self): """ auto_increment fields are created with the AUTOINCREMENT keyword in order to be monotonically increasing (#10164). """ with connection.schema_editor(collect_sql=True) as editor: editor.create_model(Square) statements = editor.collected_sql match = re.search('"id" ([^,]+),', statements[0]) self.assertIsNotNone(match) self.assertEqual( "integer NOT NULL PRIMARY KEY AUTOINCREMENT", match[1], "Wrong SQL used to create an auto-increment column on SQLite", ) def test_disable_constraint_checking_failure_disallowed(self): """ SQLite schema editor is not usable within an outer transaction if foreign key constraint checks are not disabled beforehand. """ msg = ( "SQLite schema editor cannot be used while foreign key " "constraint checks are enabled. Make sure to disable them " "before entering a transaction.atomic() context because " "SQLite does not support disabling them in the middle of " "a multi-statement transaction." ) with self.assertRaisesMessage(NotSupportedError, msg): with transaction.atomic(), connection.schema_editor(atomic=True): pass def test_constraint_checks_disabled_atomic_allowed(self): """ SQLite schema editor is usable within an outer transaction as long as foreign key constraints checks are disabled beforehand. """ def constraint_checks_enabled(): with connection.cursor() as cursor: return bool(cursor.execute("PRAGMA foreign_keys").fetchone()[0]) with connection.constraint_checks_disabled(), transaction.atomic(): with connection.schema_editor(atomic=True): self.assertFalse(constraint_checks_enabled()) self.assertFalse(constraint_checks_enabled()) self.assertTrue(constraint_checks_enabled()) @skipIfDBFeature("supports_atomic_references_rename") def test_field_rename_inside_atomic_block(self): """ NotImplementedError is raised when a model field rename is attempted inside an atomic block. """ new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") msg = ( "Renaming the 'backends_author'.'name' column while in a " "transaction is not supported on SQLite < 3.26 because it would " "break referential integrity. Try adding `atomic = False` to the " "Migration class." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) @skipIfDBFeature("supports_atomic_references_rename") def test_table_rename_inside_atomic_block(self): """ NotImplementedError is raised when a table rename is attempted inside an atomic block. """ msg = ( "Renaming the 'backends_author' table while in a transaction is " "not supported on SQLite < 3.26 because it would break referential " "integrity. Try adding `atomic = False` to the Migration class." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Author, "backends_author", "renamed_table") @unittest.skipUnless(connection.vendor == "sqlite", "Test only for SQLite") @override_settings(DEBUG=True) class LastExecutedQueryTest(TestCase): def test_no_interpolation(self): # This shouldn't raise an exception (#17158) query = "SELECT strftime('%Y', 'now');" with connection.cursor() as cursor: cursor.execute(query) self.assertEqual(connection.queries[-1]["sql"], query) def test_parameter_quoting(self): # The implementation of last_executed_queries isn't optimal. It's # worth testing that parameters are quoted (#14091). query = "SELECT %s" params = ["\"'\\"] with connection.cursor() as cursor: cursor.execute(query, params) # Note that the single quote is repeated substituted = "SELECT '\"''\\'" self.assertEqual(connection.queries[-1]["sql"], substituted) def test_large_number_of_parameters(self): # If SQLITE_MAX_VARIABLE_NUMBER (default = 999) has been changed to be # greater than SQLITE_MAX_COLUMN (default = 2000), last_executed_query # can hit the SQLITE_MAX_COLUMN limit (#26063). with connection.cursor() as cursor: sql = "SELECT MAX(%s)" % ", ".join(["%s"] * 2001) params = list(range(2001)) # This should not raise an exception. cursor.db.ops.last_executed_query(cursor.cursor, sql, params) @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class EscapingChecks(TestCase): """ All tests in this test case are also run with settings.DEBUG=True in EscapingChecksDebug test case, to also test CursorDebugWrapper. """ def test_parameter_escaping(self): # '%s' escaping support for sqlite3 (#13648). with connection.cursor() as cursor: cursor.execute("select strftime('%s', date('now'))") response = cursor.fetchall()[0][0] # response should be an non-zero integer self.assertTrue(int(response)) @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") @override_settings(DEBUG=True) class EscapingChecksDebug(EscapingChecks): pass @unittest.skipUnless(connection.vendor == "sqlite", "SQLite tests") class ThreadSharing(TransactionTestCase): available_apps = ["backends"] def test_database_sharing_in_threads(self): def create_object(): Object.objects.create() create_object() thread = threading.Thread(target=create_object) thread.start() thread.join() self.assertEqual(Object.objects.count(), 2)
04d665520a2f542aa2fd3de465529503d40cf54e451af6448ed87151c2e4bc3a
import unittest from contextlib import contextmanager from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import NotSupportedError, connection from django.test import TestCase, override_settings @contextmanager def get_connection(): new_connection = connection.copy() yield new_connection new_connection.close() @override_settings(DEBUG=True) @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests") class IsolationLevelTests(TestCase): read_committed = "read committed" repeatable_read = "repeatable read" isolation_values = { level: level.upper() for level in (read_committed, repeatable_read) } @classmethod def setUpClass(cls): super().setUpClass() configured_isolation_level = ( connection.isolation_level or cls.isolation_values[cls.repeatable_read] ) cls.configured_isolation_level = configured_isolation_level.upper() cls.other_isolation_level = ( cls.read_committed if configured_isolation_level != cls.isolation_values[cls.read_committed] else cls.repeatable_read ) @staticmethod def get_isolation_level(connection): with connection.cursor() as cursor: cursor.execute( "SHOW VARIABLES " "WHERE variable_name IN ('transaction_isolation', 'tx_isolation')" ) return cursor.fetchone()[1].replace("-", " ") def test_auto_is_null_auto_config(self): query = "set sql_auto_is_null = 0" connection.init_connection_state() last_query = connection.queries[-1]["sql"].lower() if connection.features.is_sql_auto_is_null_enabled: self.assertIn(query, last_query) else: self.assertNotIn(query, last_query) def test_connect_isolation_level(self): self.assertEqual( self.get_isolation_level(connection), self.configured_isolation_level ) def test_setting_isolation_level(self): with get_connection() as new_connection: new_connection.settings_dict["OPTIONS"][ "isolation_level" ] = self.other_isolation_level self.assertEqual( self.get_isolation_level(new_connection), self.isolation_values[self.other_isolation_level], ) def test_uppercase_isolation_level(self): # Upper case values are also accepted in 'isolation_level'. with get_connection() as new_connection: new_connection.settings_dict["OPTIONS"][ "isolation_level" ] = self.other_isolation_level.upper() self.assertEqual( self.get_isolation_level(new_connection), self.isolation_values[self.other_isolation_level], ) def test_default_isolation_level(self): # If not specified in settings, the default is read committed. with get_connection() as new_connection: new_connection.settings_dict["OPTIONS"].pop("isolation_level", None) self.assertEqual( self.get_isolation_level(new_connection), self.isolation_values[self.read_committed], ) def test_isolation_level_validation(self): new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["isolation_level"] = "xxx" msg = ( "Invalid transaction isolation level 'xxx' specified.\n" "Use one of 'read committed', 'read uncommitted', " "'repeatable read', 'serializable', or None." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): new_connection.cursor() @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests") class Tests(TestCase): @mock.patch.object(connection, "get_database_version") def test_check_database_version_supported(self, mocked_get_database_version): if connection.mysql_is_mariadb: mocked_get_database_version.return_value = (10, 3) msg = "MariaDB 10.4 or later is required (found 10.3)." else: mocked_get_database_version.return_value = (5, 7) msg = "MySQL 8 or later is required (found 5.7)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called)
88d6f2c902d35598e3775f41864b2b357eab2e15522e6e4bfa7dfa25310a5f27
import copy import unittest from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, NotSupportedError, connection, connections, ) from django.db.backends.base.base import BaseDatabaseWrapper from django.test import TestCase, override_settings try: from django.db.backends.postgresql.psycopg_any import errors, is_psycopg3 except ImportError: is_psycopg3 = False @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class Tests(TestCase): databases = {"default", "other"} def test_nodb_cursor(self): """ The _nodb_cursor() fallbacks to the default connection database when access to the 'postgres' database is not granted. """ orig_connect = BaseDatabaseWrapper.connect def mocked_connect(self): if self.settings_dict["NAME"] is None: raise DatabaseError() return orig_connect(self) with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIsNone(cursor.db.settings_dict["NAME"]) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) # Now assume the 'postgres' db isn't available msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with mock.patch.object( connection, "settings_dict", {**connection.settings_dict, "NAME": "postgres"}, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) self.assertIsNotNone(cursor.db.settings_dict["NAME"]) self.assertEqual( cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"] ) # Cursor is yielded only for the first PostgreSQL database. with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) def test_nodb_cursor_raises_postgres_authentication_failure(self): """ _nodb_cursor() re-raises authentication failure to the 'postgres' db when other connection to the PostgreSQL database isn't available. """ def mocked_connect(self): raise DatabaseError() def mocked_all(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy(connection.settings_dict) test_connection.settings_dict["NAME"] = "postgres" return [test_connection] msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): mocker_connections_all = mock.patch( "django.utils.connection.BaseConnectionHandler.all", side_effect=mocked_all, autospec=True, ) mocker_connect = mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ) with mocker_connections_all, mocker_connect: with self.assertRaises(DatabaseError): with connection._nodb_cursor(): pass def test_nodb_cursor_reraise_exceptions(self): with self.assertRaisesMessage(DatabaseError, "exception"): with connection._nodb_cursor(): raise DatabaseError("exception") def test_database_name_too_long(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() max_name_length = connection.ops.max_name_length() settings["NAME"] = "a" + (max_name_length * "a") msg = ( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %s characters. Supply a shorter NAME in " "settings.DATABASES." ) % (settings["NAME"], max_name_length + 1, max_name_length) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_database_name_empty(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = "" msg = ( "settings.DATABASES is improperly configured. Please supply the " "NAME or OPTIONS['service'] value." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_service_name(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["OPTIONS"] = {"service": "my_service"} settings["NAME"] = "" params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["service"], "my_service") self.assertNotIn("database", params) def test_service_name_default_db(self): # None is used to connect to the default 'postgres' db. from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = None settings["OPTIONS"] = {"service": "django_test"} params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["dbname"], "postgres") self.assertNotIn("service", params) def test_connect_and_rollback(self): """ PostgreSQL shouldn't roll back SET TIME ZONE, even if the first transaction is rolled back (#17062). """ new_connection = connection.copy() try: # Ensure the database default time zone is different than # the time zone in new_connection.settings_dict. We can # get the default time zone by reset & show. with new_connection.cursor() as cursor: cursor.execute("RESET TIMEZONE") cursor.execute("SHOW TIMEZONE") db_default_tz = cursor.fetchone()[0] new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC" new_connection.close() # Invalidate timezone name cache, because the setting_changed # handler cannot know about new_connection. del new_connection.timezone_name # Fetch a new connection with the new_tz as default # time zone, run a query and rollback. with self.settings(TIME_ZONE=new_tz): new_connection.set_autocommit(False) new_connection.rollback() # Now let's see if the rollback rolled back the SET TIME ZONE. with new_connection.cursor() as cursor: cursor.execute("SHOW TIMEZONE") tz = cursor.fetchone()[0] self.assertEqual(new_tz, tz) finally: new_connection.close() def test_connect_non_autocommit(self): """ The connection wrapper shouldn't believe that autocommit is enabled after setting the time zone when AUTOCOMMIT is False (#21452). """ new_connection = connection.copy() new_connection.settings_dict["AUTOCOMMIT"] = False try: # Open a database connection. with new_connection.cursor(): self.assertFalse(new_connection.get_autocommit()) finally: new_connection.close() def test_connect_isolation_level(self): """ The transaction level can be configured with DATABASES ['OPTIONS']['isolation_level']. """ from django.db.backends.postgresql.psycopg_any import IsolationLevel # Since this is a django.test.TestCase, a transaction is in progress # and the isolation level isn't reported as 0. This test assumes that # PostgreSQL is configured with the default isolation level. # Check the level on the psycopg connection, not the Django wrapper. self.assertIsNone(connection.connection.isolation_level) new_connection = connection.copy() new_connection.settings_dict["OPTIONS"][ "isolation_level" ] = IsolationLevel.SERIALIZABLE try: # Start a transaction so the isolation level isn't reported as 0. new_connection.set_autocommit(False) # Check the level on the psycopg connection, not the Django wrapper. self.assertEqual( new_connection.connection.isolation_level, IsolationLevel.SERIALIZABLE, ) finally: new_connection.close() def test_connect_invalid_isolation_level(self): self.assertIsNone(connection.connection.isolation_level) new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["isolation_level"] = -1 msg = ( "Invalid transaction isolation level -1 specified. Use one of the " "psycopg.IsolationLevel values." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): new_connection.ensure_connection() def test_connect_role(self): """ The session role can be configured with DATABASES ["OPTIONS"]["assume_role"]. """ try: custom_role = "django_nonexistent_role" new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["assume_role"] = custom_role msg = f'role "{custom_role}" does not exist' with self.assertRaisesMessage(errors.InvalidParameterValue, msg): new_connection.connect() finally: new_connection.close() @unittest.skipUnless(is_psycopg3, "psycopg3 specific test") def test_connect_server_side_binding(self): """ The server-side parameters binding role can be enabled with DATABASES ["OPTIONS"]["server_side_binding"]. """ from django.db.backends.postgresql.base import ServerBindingCursor new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["server_side_binding"] = True try: new_connection.connect() self.assertEqual( new_connection.connection.cursor_factory, ServerBindingCursor, ) finally: new_connection.close() def test_connect_no_is_usable_checks(self): new_connection = connection.copy() try: with mock.patch.object(new_connection, "is_usable") as is_usable: new_connection.connect() is_usable.assert_not_called() finally: new_connection.close() def _select(self, val): with connection.cursor() as cursor: cursor.execute("SELECT %s::text[]", (val,)) return cursor.fetchone()[0] def test_select_ascii_array(self): a = ["awef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_select_unicode_array(self): a = ["ᄲawef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_lookup_cast(self): from django.db.backends.postgresql.operations import DatabaseOperations do = DatabaseOperations(connection=None) lookups = ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ) for lookup in lookups: with self.subTest(lookup=lookup): self.assertIn("::text", do.lookup_cast(lookup)) # RemovedInDjango51Warning. for lookup in lookups: for field_type in ("CICharField", "CIEmailField", "CITextField"): with self.subTest(lookup=lookup, field_type=field_type): self.assertIn( "::citext", do.lookup_cast(lookup, internal_type=field_type) ) def test_correct_extraction_psycopg_version(self): from django.db.backends.postgresql.base import Database, psycopg_version with mock.patch.object(Database, "__version__", "4.2.1 (dt dec pq3 ext lo64)"): self.assertEqual(psycopg_version(), (4, 2, 1)) with mock.patch.object( Database, "__version__", "4.2b0.dev1 (dt dec pq3 ext lo64)" ): self.assertEqual(psycopg_version(), (4, 2)) @override_settings(DEBUG=True) @unittest.skipIf(is_psycopg3, "psycopg2 specific test") def test_copy_to_expert_cursors(self): out = StringIO() copy_expert_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)" with connection.cursor() as cursor: cursor.copy_expert(copy_expert_sql, out) cursor.copy_to(out, "django_session") self.assertEqual( [q["sql"] for q in connection.queries], [copy_expert_sql, "COPY django_session TO STDOUT"], ) @override_settings(DEBUG=True) @unittest.skipUnless(is_psycopg3, "psycopg3 specific test") def test_copy_cursors(self): copy_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)" with connection.cursor() as cursor: with cursor.copy(copy_sql) as copy: for row in copy: pass self.assertEqual([q["sql"] for q in connection.queries], [copy_sql]) def test_get_database_version(self): new_connection = connection.copy() new_connection.pg_version = 110009 self.assertEqual(new_connection.get_database_version(), (11, 9)) @mock.patch.object(connection, "get_database_version", return_value=(11,)) def test_check_database_version_supported(self, mocked_get_database_version): msg = "PostgreSQL 12 or later is required (found 11)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called)
2d296087b2701fb433a6238e3e12de5fb6b0fc44c07461f497688aa6196fa45e
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Bar", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("name", models.CharField(max_length=255)), ], ), ]
5feb7d6f77e1501ae91e7cc2d61523403cd9b0fb44ece9826d6cae5ed831338f
from django.core.management import BaseCommand class Command(BaseCommand): help = "Test suppress base options command." requires_system_checks = [] suppressed_base_arguments = { "-v", "--traceback", "--settings", "--pythonpath", "--no-color", "--force-color", "--version", "file", } def add_arguments(self, parser): super().add_arguments(parser) self.add_base_argument(parser, "file", nargs="?", help="input file") def handle(self, *labels, **options): print("EXECUTE:SuppressBaseOptionsCommand options=%s" % sorted(options.items()))
ee5c4f723769b949f1b53072884794f0c1925556b31c93b50eff109df56589e1
from django.contrib.gis.db import models class AllOGRFields(models.Model): f_decimal = models.FloatField() f_float = models.FloatField() f_int = models.IntegerField() f_char = models.CharField(max_length=10) f_date = models.DateField() f_datetime = models.DateTimeField() f_time = models.TimeField() geom = models.PolygonField() point = models.PointField() class Fields3D(models.Model): point = models.PointField(dim=3) pointg = models.PointField(dim=3, geography=True) line = models.LineStringField(dim=3) poly = models.PolygonField(dim=3) class Meta: required_db_features = {"supports_3d_storage"}
4341ede46794bee7a679c6a35eb70b2b5daa2e6e867014cb6cf6b36097a3c19c
import datetime import unittest from copy import copy from decimal import Decimal from pathlib import Path from django.conf import settings from django.contrib.gis.gdal import DataSource from django.contrib.gis.utils.layermapping import ( InvalidDecimal, InvalidString, LayerMapError, LayerMapping, MissingForeignKey, ) from django.db import connection from django.test import TestCase, override_settings from .models import ( City, County, CountyFeat, DoesNotAllowNulls, HasNulls, ICity1, ICity2, Interstate, Invalid, State, city_mapping, co_mapping, cofeat_mapping, has_nulls_mapping, inter_mapping, ) shp_path = Path(__file__).resolve().parent.parent / "data" city_shp = shp_path / "cities" / "cities.shp" co_shp = shp_path / "counties" / "counties.shp" inter_shp = shp_path / "interstates" / "interstates.shp" invalid_shp = shp_path / "invalid" / "emptypoints.shp" has_nulls_geojson = shp_path / "has_nulls" / "has_nulls.geojson" # Dictionaries to hold what's expected in the county shapefile. NAMES = ["Bexar", "Galveston", "Harris", "Honolulu", "Pueblo"] NUMS = [1, 2, 1, 19, 1] # Number of polygons for each. STATES = ["Texas", "Texas", "Texas", "Hawaii", "Colorado"] class LayerMapTest(TestCase): def test_init(self): "Testing LayerMapping initialization." # Model field that does not exist. bad1 = copy(city_mapping) bad1["foobar"] = "FooField" # Shapefile field that does not exist. bad2 = copy(city_mapping) bad2["name"] = "Nombre" # Nonexistent geographic field type. bad3 = copy(city_mapping) bad3["point"] = "CURVE" # Incrementing through the bad mapping dictionaries and # ensuring that a LayerMapError is raised. for bad_map in (bad1, bad2, bad3): with self.assertRaises(LayerMapError): LayerMapping(City, city_shp, bad_map) # A LookupError should be thrown for bogus encodings. with self.assertRaises(LookupError): LayerMapping(City, city_shp, city_mapping, encoding="foobar") def test_simple_layermap(self): "Test LayerMapping import of a simple point shapefile." # Setting up for the LayerMapping. lm = LayerMapping(City, city_shp, city_mapping) lm.save() # There should be three cities in the shape file. self.assertEqual(3, City.objects.count()) # Opening up the shapefile, and verifying the values in each # of the features made it to the model. ds = DataSource(city_shp) layer = ds[0] for feat in layer: city = City.objects.get(name=feat["Name"].value) self.assertEqual(feat["Population"].value, city.population) self.assertEqual(Decimal(str(feat["Density"])), city.density) self.assertEqual(feat["Created"].value, city.dt) # Comparing the geometries. pnt1, pnt2 = feat.geom, city.point self.assertAlmostEqual(pnt1.x, pnt2.x, 5) self.assertAlmostEqual(pnt1.y, pnt2.y, 5) def test_data_source_str(self): lm = LayerMapping(City, str(city_shp), city_mapping) lm.save() self.assertEqual(City.objects.count(), 3) def test_layermap_strict(self): "Testing the `strict` keyword, and import of a LineString shapefile." # When the `strict` keyword is set an error encountered will force # the importation to stop. with self.assertRaises(InvalidDecimal): lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True, strict=True) Interstate.objects.all().delete() # This LayerMapping should work b/c `strict` is not set. lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True) # Two interstate should have imported correctly. self.assertEqual(2, Interstate.objects.count()) # Verifying the values in the layer w/the model. ds = DataSource(inter_shp) # Only the first two features of this shapefile are valid. valid_feats = ds[0][:2] for feat in valid_feats: istate = Interstate.objects.get(name=feat["Name"].value) if feat.fid == 0: self.assertEqual(Decimal(str(feat["Length"])), istate.length) elif feat.fid == 1: # Everything but the first two decimal digits were truncated, # because the Interstate model's `length` field has decimal_places=2. self.assertAlmostEqual(feat.get("Length"), float(istate.length), 2) for p1, p2 in zip(feat.geom, istate.path): self.assertAlmostEqual(p1[0], p2[0], 6) self.assertAlmostEqual(p1[1], p2[1], 6) def county_helper(self, county_feat=True): "Helper function for ensuring the integrity of the mapped County models." for name, n, st in zip(NAMES, NUMS, STATES): # Should only be one record b/c of `unique` keyword. c = County.objects.get(name=name) self.assertEqual(n, len(c.mpoly)) self.assertEqual(st, c.state.name) # Checking ForeignKey mapping. # Multiple records because `unique` was not set. if county_feat: qs = CountyFeat.objects.filter(name=name) self.assertEqual(n, qs.count()) def test_layermap_unique_multigeometry_fk(self): """ The `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings. """ # All the following should work. # Telling LayerMapping that we want no transformations performed on the data. lm = LayerMapping(County, co_shp, co_mapping, transform=False) # Specifying the source spatial reference system via the `source_srs` keyword. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269) lm = LayerMapping(County, co_shp, co_mapping, source_srs="NAD83") # Unique may take tuple or string parameters. for arg in ("name", ("name", "mpoly")): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) # Now test for failures # Testing invalid params for the `unique` keyword. for e, arg in ( (TypeError, 5.0), (ValueError, "foobar"), (ValueError, ("name", "mpolygon")), ): with self.assertRaises(e): LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) # No source reference system defined in the shapefile, should raise an error. if connection.features.supports_transform: with self.assertRaises(LayerMapError): LayerMapping(County, co_shp, co_mapping) # Passing in invalid ForeignKey mapping parameters -- must be a dictionary # mapping for the model the ForeignKey points to. bad_fk_map1 = copy(co_mapping) bad_fk_map1["state"] = "name" bad_fk_map2 = copy(co_mapping) bad_fk_map2["state"] = {"nombre": "State"} with self.assertRaises(TypeError): LayerMapping(County, co_shp, bad_fk_map1, transform=False) with self.assertRaises(LayerMapError): LayerMapping(County, co_shp, bad_fk_map2, transform=False) # There exist no State models for the ForeignKey mapping to work -- should raise # a MissingForeignKey exception (this error would be ignored if the `strict` # keyword is not set). lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") with self.assertRaises(MissingForeignKey): lm.save(silent=True, strict=True) # Now creating the state models so the ForeignKey mapping may work. State.objects.bulk_create( [State(name="Colorado"), State(name="Hawaii"), State(name="Texas")] ) # If a mapping is specified as a collection, all OGR fields that # are not collections will be converted into them. For example, # a Point column would be converted to MultiPoint. Other things being done # w/the keyword args: # `transform=False`: Specifies that no transform is to be done; this # has the effect of ignoring the spatial reference check (because the # county shapefile does not have implicit spatial reference info). # # `unique='name'`: Creates models on the condition that they have # unique county names; geometries from each feature however will be # appended to the geometry collection of the unique model. Thus, # all of the various islands in Honolulu county will be in in one # database record with a MULTIPOLYGON type. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") lm.save(silent=True, strict=True) # A reference that doesn't use the unique keyword; a new database record will # created for each polygon. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) # The county helper is called to ensure integrity of County models. self.county_helper() def test_test_fid_range_step(self): "Tests the `fid_range` keyword and the `step` keyword of .save()." # Function for clearing out all the counties before testing. def clear_counties(): County.objects.all().delete() State.objects.bulk_create( [State(name="Colorado"), State(name="Hawaii"), State(name="Texas")] ) # Initializing the LayerMapping object to use in these tests. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") # Bad feature id ranges should raise a type error. bad_ranges = (5.0, "foo", co_shp) for bad in bad_ranges: with self.assertRaises(TypeError): lm.save(fid_range=bad) # Step keyword should not be allowed w/`fid_range`. fr = (3, 5) # layer[3:5] with self.assertRaises(LayerMapError): lm.save(fid_range=fr, step=10) lm.save(fid_range=fr) # Features IDs 3 & 4 are for Galveston County, Texas -- only # one model is returned because the `unique` keyword was set. qs = County.objects.all() self.assertEqual(1, qs.count()) self.assertEqual("Galveston", qs[0].name) # Features IDs 5 and beyond for Honolulu County, Hawaii, and # FID 0 is for Pueblo County, Colorado. clear_counties() lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:] lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1] # Only Pueblo & Honolulu counties should be present because of # the `unique` keyword. Have to set `order_by` on this QuerySet # or else MySQL will return a different ordering than the other dbs. qs = County.objects.order_by("name") self.assertEqual(2, qs.count()) hi, co = tuple(qs) hi_idx, co_idx = tuple(map(NAMES.index, ("Honolulu", "Pueblo"))) self.assertEqual("Pueblo", co.name) self.assertEqual(NUMS[co_idx], len(co.mpoly)) self.assertEqual("Honolulu", hi.name) self.assertEqual(NUMS[hi_idx], len(hi.mpoly)) # Testing the `step` keyword -- should get the same counties # regardless of we use a step that divides equally, that is odd, # or that is larger than the dataset. for st in (4, 7, 1000): clear_counties() lm.save(step=st, strict=True) self.county_helper(county_feat=False) def test_model_inheritance(self): "Tests LayerMapping on inherited models. See #12093." icity_mapping = { "name": "Name", "population": "Population", "density": "Density", "point": "POINT", "dt": "Created", } # Parent model has geometry field. lm1 = LayerMapping(ICity1, city_shp, icity_mapping) lm1.save() # Grandparent has geometry field. lm2 = LayerMapping(ICity2, city_shp, icity_mapping) lm2.save() self.assertEqual(6, ICity1.objects.count()) self.assertEqual(3, ICity2.objects.count()) def test_invalid_layer(self): "Tests LayerMapping on invalid geometries. See #15378." invalid_mapping = {"point": "POINT"} lm = LayerMapping(Invalid, invalid_shp, invalid_mapping, source_srs=4326) lm.save(silent=True) def test_charfield_too_short(self): mapping = copy(city_mapping) mapping["name_short"] = "Name" lm = LayerMapping(City, city_shp, mapping) with self.assertRaises(InvalidString): lm.save(silent=True, strict=True) def test_textfield(self): "String content fits also in a TextField" mapping = copy(city_mapping) mapping["name_txt"] = "Name" lm = LayerMapping(City, city_shp, mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 3) self.assertEqual(City.objects.get(name="Houston").name_txt, "Houston") def test_encoded_name(self): """Test a layer containing utf-8-encoded name""" city_shp = shp_path / "ch-city" / "ch-city.shp" lm = LayerMapping(City, city_shp, city_mapping) lm.save(silent=True, strict=True) self.assertEqual(City.objects.count(), 1) self.assertEqual(City.objects.all()[0].name, "Zürich") def test_null_geom_with_unique(self): """LayerMapping may be created with a unique and a null geometry.""" State.objects.bulk_create( [State(name="Colorado"), State(name="Hawaii"), State(name="Texas")] ) hw = State.objects.get(name="Hawaii") hu = County.objects.create(name="Honolulu", state=hw, mpoly=None) lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique="name") lm.save(silent=True, strict=True) hu.refresh_from_db() self.assertIsNotNone(hu.mpoly) self.assertEqual(hu.mpoly.ogr.num_coords, 449) def test_null_number_imported(self): """LayerMapping import of GeoJSON with a null numeric value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.count(), 3) self.assertEqual(HasNulls.objects.filter(num=0).count(), 1) self.assertEqual(HasNulls.objects.filter(num__isnull=True).count(), 1) def test_null_string_imported(self): "Test LayerMapping import of GeoJSON with a null string value." lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(name="None").count(), 0) num_empty = 1 if connection.features.interprets_empty_strings_as_nulls else 0 self.assertEqual(HasNulls.objects.filter(name="").count(), num_empty) self.assertEqual(HasNulls.objects.filter(name__isnull=True).count(), 1) def test_nullable_boolean_imported(self): """LayerMapping import of GeoJSON with a nullable boolean value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual(HasNulls.objects.filter(boolean=True).count(), 1) self.assertEqual(HasNulls.objects.filter(boolean=False).count(), 1) self.assertEqual(HasNulls.objects.filter(boolean__isnull=True).count(), 1) def test_nullable_datetime_imported(self): """LayerMapping import of GeoJSON with a nullable date/time value.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual( HasNulls.objects.filter(datetime__lt=datetime.date(1994, 8, 15)).count(), 1 ) self.assertEqual( HasNulls.objects.filter(datetime="2018-11-29T03:02:52").count(), 1 ) self.assertEqual(HasNulls.objects.filter(datetime__isnull=True).count(), 1) def test_uuids_imported(self): """LayerMapping import of GeoJSON with UUIDs.""" lm = LayerMapping(HasNulls, has_nulls_geojson, has_nulls_mapping) lm.save() self.assertEqual( HasNulls.objects.filter( uuid="1378c26f-cbe6-44b0-929f-eb330d4991f5" ).count(), 1, ) def test_null_number_imported_not_allowed(self): """ LayerMapping import of GeoJSON with nulls to fields that don't permit them. """ lm = LayerMapping(DoesNotAllowNulls, has_nulls_geojson, has_nulls_mapping) lm.save(silent=True) # When a model fails to save due to IntegrityError (null in non-null # column), subsequent saves fail with "An error occurred in the current # transaction. You can't execute queries until the end of the 'atomic' # block." On Oracle and MySQL, the one object that did load appears in # this count. On other databases, no records appear. self.assertLessEqual(DoesNotAllowNulls.objects.count(), 1) class OtherRouter: def db_for_read(self, model, **hints): return "other" def db_for_write(self, model, **hints): return self.db_for_read(model, **hints) def allow_relation(self, obj1, obj2, **hints): # ContentType objects are created during a post-migrate signal while # performing fixture teardown using the default database alias and # don't abide by the database specified by this router. return True def allow_migrate(self, db, app_label, **hints): return True @override_settings(DATABASE_ROUTERS=[OtherRouter()]) class LayerMapRouterTest(TestCase): databases = {"default", "other"} @unittest.skipUnless(len(settings.DATABASES) > 1, "multiple databases required") def test_layermapping_default_db(self): lm = LayerMapping(City, city_shp, city_mapping) self.assertEqual(lm.using, "other")
b1cf4812b600a105ff7f07341f666c3de77666aa7d8de46c1faab1586f088b2d
import json import math import re from decimal import Decimal from django.contrib.gis.db.models import GeometryField, PolygonField, functions from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon, fromstr from django.contrib.gis.measure import Area from django.db import NotSupportedError, connection from django.db.models import IntegerField, Sum, Value from django.test import TestCase, skipUnlessDBFeature from ..utils import FuncTestMixin from .models import City, Country, CountryWebMercator, State, Track class GISFunctionsTests(FuncTestMixin, TestCase): """ Testing functions from django/contrib/gis/db/models/functions.py. Area/Distance/Length/Perimeter are tested in distapp/tests. Please keep the tests in function's alphabetic order. """ fixtures = ["initial"] def test_asgeojson(self): if not connection.features.has_AsGeoJSON_function: with self.assertRaises(NotSupportedError): list(Country.objects.annotate(json=functions.AsGeoJSON("mpoly"))) return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = json.loads( '{"type":"Point","crs":{"type":"name","properties":' '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' ) victoria_json = json.loads( '{"type":"Point",' '"bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],' '"coordinates":[-123.305196,48.462611]}' ) chicago_json = json.loads( '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},' '"bbox":[-87.65018,41.85039,-87.65018,41.85039],' '"coordinates":[-87.65018,41.85039]}' ) if "crs" in connection.features.unsupported_geojson_options: del houston_json["crs"] del chicago_json["crs"] if "bbox" in connection.features.unsupported_geojson_options: del chicago_json["bbox"] del victoria_json["bbox"] if "precision" in connection.features.unsupported_geojson_options: chicago_json["coordinates"] = [-87.650175, 41.850385] # Precision argument should only be an integer with self.assertRaises(TypeError): City.objects.annotate(geojson=functions.AsGeoJSON("point", precision="foo")) # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; self.assertJSONEqual( pueblo_json, City.objects.annotate(geojson=functions.AsGeoJSON("point")) .get(name="Pueblo") .geojson, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. self.assertJSONEqual( City.objects.annotate(json=functions.AsGeoJSON("point", crs=True)) .get(name="Houston") .json, houston_json, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. self.assertJSONEqual( City.objects.annotate(geojson=functions.AsGeoJSON("point", bbox=True)) .get(name="Victoria") .geojson, victoria_json, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. # MariaDB doesn't limit the number of decimals in bbox. if connection.ops.mariadb: chicago_json["bbox"] = [-87.650175, 41.850385, -87.650175, 41.850385] try: self.assertJSONEqual( City.objects.annotate( geojson=functions.AsGeoJSON( "point", bbox=True, crs=True, precision=5 ) ) .get(name="Chicago") .geojson, chicago_json, ) except AssertionError: # Give a second chance with different coords rounding. chicago_json["coordinates"][1] = 41.85038 self.assertJSONEqual( City.objects.annotate( geojson=functions.AsGeoJSON( "point", bbox=True, crs=True, precision=5 ) ) .get(name="Chicago") .geojson, chicago_json, ) @skipUnlessDBFeature("has_AsGML_function") def test_asgml(self): # Should throw a TypeError when trying to obtain GML from a # non-geometry field. qs = City.objects.all() with self.assertRaises(TypeError): qs.annotate(gml=functions.AsGML("name")) ptown = City.objects.annotate(gml=functions.AsGML("point", precision=9)).get( name="Pueblo" ) if connection.ops.oracle: # No precision parameter for Oracle :-/ gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326" ' r'xmlns:gml="http://www.opengis.net/gml">' r'<gml:coordinates decimal="\." cs="," ts=" ">' r"-104.60925\d+,38.25500\d+ " r"</gml:coordinates></gml:Point>" ) else: gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>' r"-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>" ) self.assertTrue(gml_regex.match(ptown.gml)) self.assertIn( '<gml:pos srsDimension="2">', City.objects.annotate(gml=functions.AsGML("point", version=3)) .get(name="Pueblo") .gml, ) @skipUnlessDBFeature("has_AsKML_function") def test_askml(self): # Should throw a TypeError when trying to obtain KML from a # non-geometry field. with self.assertRaises(TypeError): City.objects.annotate(kml=functions.AsKML("name")) # Ensuring the KML is as expected. ptown = City.objects.annotate(kml=functions.AsKML("point", precision=9)).get( name="Pueblo" ) self.assertEqual( "<Point><coordinates>-104.609252,38.255001</coordinates></Point>", ptown.kml ) @skipUnlessDBFeature("has_AsSVG_function") def test_assvg(self): with self.assertRaises(TypeError): City.objects.annotate(svg=functions.AsSVG("point", precision="foo")) # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; svg1 = 'cx="-104.609252" cy="-38.255001"' # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. svg2 = svg1.replace("c", "") self.assertEqual( svg1, City.objects.annotate(svg=functions.AsSVG("point")).get(name="Pueblo").svg, ) self.assertEqual( svg2, City.objects.annotate(svg=functions.AsSVG("point", relative=5)) .get(name="Pueblo") .svg, ) @skipUnlessDBFeature("has_AsWKB_function") def test_aswkb(self): wkb = ( City.objects.annotate( wkb=functions.AsWKB(Point(1, 2, srid=4326)), ) .first() .wkb ) # WKB is either XDR or NDR encoded. self.assertIn( bytes(wkb), ( b"\x00\x00\x00\x00\x01?\xf0\x00\x00\x00\x00\x00\x00@\x00\x00" b"\x00\x00\x00\x00\x00", b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00" b"\x00\x00\x00\x00\x00@", ), ) @skipUnlessDBFeature("has_AsWKT_function") def test_aswkt(self): wkt = ( City.objects.annotate( wkt=functions.AsWKT(Point(1, 2, srid=4326)), ) .first() .wkt ) self.assertEqual( wkt, "POINT (1.0 2.0)" if connection.ops.oracle else "POINT(1 2)" ) @skipUnlessDBFeature("has_Azimuth_function") def test_azimuth(self): # Returns the azimuth in radians. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(1, 1, srid=4326)) self.assertAlmostEqual( City.objects.annotate(azimuth=azimuth_expr).first().azimuth, math.pi / 4, places=2, ) # Returns None if the two points are coincident. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(0, 0, srid=4326)) self.assertIsNone(City.objects.annotate(azimuth=azimuth_expr).first().azimuth) @skipUnlessDBFeature("has_BoundingCircle_function") def test_bounding_circle(self): def circle_num_points(num_seg): # num_seg is the number of segments per quarter circle. return (4 * num_seg) + 1 expected_areas = (169, 136) if connection.ops.postgis else (171, 126) qs = Country.objects.annotate( circle=functions.BoundingCircle("mpoly") ).order_by("name") self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0) self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0) if connection.ops.postgis: # By default num_seg=48. self.assertEqual(qs[0].circle.num_points, circle_num_points(48)) self.assertEqual(qs[1].circle.num_points, circle_num_points(48)) tests = [12, Value(12, output_field=IntegerField())] for num_seq in tests: with self.subTest(num_seq=num_seq): qs = Country.objects.annotate( circle=functions.BoundingCircle("mpoly", num_seg=num_seq), ).order_by("name") if connection.ops.postgis: self.assertGreater(qs[0].circle.area, 168.4, 0) self.assertLess(qs[0].circle.area, 169.5, 0) self.assertAlmostEqual(qs[1].circle.area, 136, 0) self.assertEqual(qs[0].circle.num_points, circle_num_points(12)) self.assertEqual(qs[1].circle.num_points, circle_num_points(12)) else: self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0) self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0) @skipUnlessDBFeature("has_Centroid_function") def test_centroid(self): qs = State.objects.exclude(poly__isnull=True).annotate( centroid=functions.Centroid("poly") ) tol = ( 1.8 if connection.ops.mysql else (0.1 if connection.ops.oracle else 0.00001) ) for state in qs: self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol)) with self.assertRaisesMessage( TypeError, "'Centroid' takes exactly 1 argument (2 given)" ): State.objects.annotate(centroid=functions.Centroid("poly", "poly")) @skipUnlessDBFeature("has_Difference_function") def test_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(diff=functions.Difference("mpoly", geom)) # Oracle does something screwy with the Texas geometry. if connection.ops.oracle: qs = qs.exclude(name="Texas") for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.diff)) @skipUnlessDBFeature("has_Difference_function", "has_Transform_function") def test_difference_mixed_srid(self): """Testing with mixed SRID (Country has default 4326).""" geom = Point(556597.4, 2632018.6, srid=3857) # Spherical Mercator qs = Country.objects.annotate(difference=functions.Difference("mpoly", geom)) # Oracle does something screwy with the Texas geometry. if connection.ops.oracle: qs = qs.exclude(name="Texas") for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.difference)) @skipUnlessDBFeature("has_Envelope_function") def test_envelope(self): countries = Country.objects.annotate(envelope=functions.Envelope("mpoly")) for country in countries: self.assertTrue(country.envelope.equals(country.mpoly.envelope)) @skipUnlessDBFeature("has_ForcePolygonCW_function") def test_force_polygon_cw(self): rings = ( ((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)), ) rhr_rings = ( ((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)), ) State.objects.create(name="Foo", poly=Polygon(*rings)) st = State.objects.annotate( force_polygon_cw=functions.ForcePolygonCW("poly") ).get(name="Foo") self.assertEqual(rhr_rings, st.force_polygon_cw.coords) @skipUnlessDBFeature("has_FromWKB_function") def test_fromwkb(self): g = Point(56.811078, 60.608647) g2 = City.objects.values_list( functions.FromWKB(Value(g.wkb.tobytes())), flat=True, )[0] self.assertIs(g.equals_exact(g2, 0.00001), True) @skipUnlessDBFeature("has_FromWKT_function") def test_fromwkt(self): g = Point(56.811078, 60.608647) g2 = City.objects.values_list( functions.FromWKT(Value(g.wkt)), flat=True, )[0] self.assertIs(g.equals_exact(g2, 0.00001), True) @skipUnlessDBFeature("has_GeoHash_function") def test_geohash(self): # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; ref_hash = "9vk1mfq8jx0c8e0386z6" h1 = City.objects.annotate(geohash=functions.GeoHash("point")).get( name="Houston" ) h2 = City.objects.annotate(geohash=functions.GeoHash("point", precision=5)).get( name="Houston" ) self.assertEqual(ref_hash, h1.geohash[: len(ref_hash)]) self.assertEqual(ref_hash[:5], h2.geohash) @skipUnlessDBFeature("has_GeometryDistance_function") def test_geometry_distance(self): point = Point(-90, 40, srid=4326) qs = City.objects.annotate( distance=functions.GeometryDistance("point", point) ).order_by("distance") distances = ( 2.99091995527296, 5.33507274054713, 9.33852187483721, 9.91769193646233, 11.556465744884, 14.713098433352, 34.3635252198568, 276.987855073372, ) for city, expected_distance in zip(qs, distances): with self.subTest(city=city): self.assertAlmostEqual(city.distance, expected_distance) @skipUnlessDBFeature("has_Intersection_function") def test_intersection(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(inter=functions.Intersection("mpoly", geom)) for c in qs: if connection.features.empty_intersection_returns_none: self.assertIsNone(c.inter) else: self.assertIs(c.inter.empty, True) @skipUnlessDBFeature("supports_empty_geometries", "has_IsEmpty_function") def test_isempty(self): empty = City.objects.create(name="Nowhere", point=Point(srid=4326)) City.objects.create(name="Somewhere", point=Point(6.825, 47.1, srid=4326)) self.assertSequenceEqual( City.objects.annotate(isempty=functions.IsEmpty("point")).filter( isempty=True ), [empty], ) self.assertSequenceEqual(City.objects.filter(point__isempty=True), [empty]) @skipUnlessDBFeature("has_IsValid_function") def test_isvalid(self): valid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))") invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") State.objects.create(name="valid", poly=valid_geom) State.objects.create(name="invalid", poly=invalid_geom) valid = ( State.objects.filter(name="valid") .annotate(isvalid=functions.IsValid("poly")) .first() ) invalid = ( State.objects.filter(name="invalid") .annotate(isvalid=functions.IsValid("poly")) .first() ) self.assertIs(valid.isvalid, True) self.assertIs(invalid.isvalid, False) @skipUnlessDBFeature("has_Area_function") def test_area_with_regular_aggregate(self): # Create projected country objects, for this test to work on all backends. for c in Country.objects.all(): CountryWebMercator.objects.create( name=c.name, mpoly=c.mpoly.transform(3857, clone=True) ) # Test in projected coordinate system qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area("mpoly"))) # Some backends (e.g. Oracle) cannot group by multipolygon values, so # defer such fields in the aggregation query. for c in qs.defer("mpoly"): result = c.area_sum # If the result is a measure object, get value. if isinstance(result, Area): result = result.sq_m self.assertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0) @skipUnlessDBFeature("has_Area_function") def test_area_lookups(self): # Create projected countries so the test works on all backends. CountryWebMercator.objects.bulk_create( CountryWebMercator(name=c.name, mpoly=c.mpoly.transform(3857, clone=True)) for c in Country.objects.all() ) qs = CountryWebMercator.objects.annotate(area=functions.Area("mpoly")) self.assertEqual( qs.get(area__lt=Area(sq_km=500000)), CountryWebMercator.objects.get(name="New Zealand"), ) with self.assertRaisesMessage( ValueError, "AreaField only accepts Area measurement objects." ): qs.get(area__lt=500000) @skipUnlessDBFeature("has_ClosestPoint_function") def test_closest_point(self): qs = Country.objects.annotate( closest_point=functions.ClosestPoint("mpoly", functions.Centroid("mpoly")) ) for country in qs: self.assertIsInstance(country.closest_point, Point) self.assertEqual( country.mpoly.intersection(country.closest_point), country.closest_point, ) @skipUnlessDBFeature("has_LineLocatePoint_function") def test_line_locate_point(self): pos_expr = functions.LineLocatePoint( LineString((0, 0), (0, 3), srid=4326), Point(0, 1, srid=4326) ) self.assertAlmostEqual( State.objects.annotate(pos=pos_expr).first().pos, 0.3333333 ) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid(self): invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") State.objects.create(name="invalid", poly=invalid_geom) invalid = ( State.objects.filter(name="invalid") .annotate(repaired=functions.MakeValid("poly")) .first() ) self.assertIs(invalid.repaired.valid, True) self.assertTrue( invalid.repaired.equals( fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))", srid=invalid.poly.srid) ) ) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid_multipolygon(self): invalid_geom = fromstr( "POLYGON((0 0, 0 1 , 1 1 , 1 0, 0 0), (10 0, 10 1, 11 1, 11 0, 10 0))" ) State.objects.create(name="invalid", poly=invalid_geom) invalid = ( State.objects.filter(name="invalid") .annotate( repaired=functions.MakeValid("poly"), ) .get() ) self.assertIs(invalid.repaired.valid, True) self.assertTrue( invalid.repaired.equals( fromstr( "MULTIPOLYGON (((0 0, 0 1, 1 1, 1 0, 0 0)), " "((10 0, 10 1, 11 1, 11 0, 10 0)))", srid=invalid.poly.srid, ) ) ) self.assertEqual(len(invalid.repaired), 2) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid_output_field(self): # output_field is GeometryField instance because different geometry # types can be returned. output_field = functions.MakeValid( Value(Polygon(), PolygonField(srid=42)), ).output_field self.assertIs(output_field.__class__, GeometryField) self.assertEqual(output_field.srid, 42) @skipUnlessDBFeature("has_MemSize_function") def test_memsize(self): ptown = City.objects.annotate(size=functions.MemSize("point")).get( name="Pueblo" ) # Exact value depends on database and version. self.assertTrue(20 <= ptown.size <= 105) @skipUnlessDBFeature("has_NumGeom_function") def test_num_geom(self): # Both 'countries' only have two geometries. for c in Country.objects.annotate(num_geom=functions.NumGeometries("mpoly")): self.assertEqual(2, c.num_geom) qs = City.objects.filter(point__isnull=False).annotate( num_geom=functions.NumGeometries("point") ) for city in qs: # The results for the number of geometries on non-collections # depends on the database. if connection.ops.mysql or connection.ops.mariadb: self.assertIsNone(city.num_geom) else: self.assertEqual(1, city.num_geom) @skipUnlessDBFeature("has_NumPoint_function") def test_num_points(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name="Foo", line=LineString(coords)) qs = Track.objects.annotate(num_points=functions.NumPoints("line")) self.assertEqual(qs.first().num_points, 2) mpoly_qs = Country.objects.annotate(num_points=functions.NumPoints("mpoly")) if not connection.features.supports_num_points_poly: for c in mpoly_qs: self.assertIsNone(c.num_points) return for c in mpoly_qs: self.assertEqual(c.mpoly.num_points, c.num_points) for c in City.objects.annotate(num_points=functions.NumPoints("point")): self.assertEqual(c.num_points, 1) @skipUnlessDBFeature("has_PointOnSurface_function") def test_point_on_surface(self): qs = Country.objects.annotate( point_on_surface=functions.PointOnSurface("mpoly") ) for country in qs: self.assertTrue(country.mpoly.intersection(country.point_on_surface)) @skipUnlessDBFeature("has_Reverse_function") def test_reverse_geom(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name="Foo", line=LineString(coords)) track = Track.objects.annotate(reverse_geom=functions.Reverse("line")).get( name="Foo" ) coords.reverse() self.assertEqual(tuple(coords), track.reverse_geom.coords) @skipUnlessDBFeature("has_Scale_function") def test_scale(self): xfac, yfac = 2, 3 tol = 5 # The low precision tolerance is for SpatiaLite qs = Country.objects.annotate(scaled=functions.Scale("mpoly", xfac, yfac)) for country in qs: for p1, p2 in zip(country.mpoly, country.scaled): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): self.assertAlmostEqual(c1[0] * xfac, c2[0], tol) self.assertAlmostEqual(c1[1] * yfac, c2[1], tol) # Test float/Decimal values qs = Country.objects.annotate( scaled=functions.Scale("mpoly", 1.5, Decimal("2.5")) ) self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area) @skipUnlessDBFeature("has_SnapToGrid_function") def test_snap_to_grid(self): # Let's try and break snap_to_grid() with bad combinations of arguments. for bad_args in ((), range(3), range(5)): with self.assertRaises(ValueError): Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args)) for bad_args in (("1.0",), (1.0, None), tuple(map(str, range(4)))): with self.assertRaises(TypeError): Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args)) # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org # from the world borders dataset he provides. wkt = ( "MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167," "12.46250 43.98472,12.47167 43.98694,12.49278 43.98917," "12.50555 43.98861,12.51000 43.98694,12.51028 43.98277," "12.51167 43.94333,12.51056 43.93916,12.49639 43.92333," "12.49500 43.91472,12.48778 43.90583,12.47444 43.89722," "12.46472 43.89555,12.45917 43.89611,12.41639 43.90472," "12.41222 43.90610,12.40782 43.91366,12.40389 43.92667," "12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))" ) Country.objects.create(name="San Marino", mpoly=fromstr(wkt)) # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. tol = 0.000000001 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) # FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr("MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))") self.assertTrue( ref.equals_exact( Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.1)) .get(name="San Marino") .snap, tol, ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) # FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( "MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))" ) self.assertTrue( ref.equals_exact( Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.05, 0.23)) .get(name="San Marino") .snap, tol, ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) # FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87," "12.45 43.87,12.4 43.87)))" ) self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid("mpoly", 0.05, 0.23, 0.5, 0.17) ) .get(name="San Marino") .snap, tol, ) ) @skipUnlessDBFeature("has_SymDifference_function") def test_sym_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate( sym_difference=functions.SymDifference("mpoly", geom) ) # Oracle does something screwy with the Texas geometry. if connection.ops.oracle: qs = qs.exclude(name="Texas") for country in qs: self.assertTrue( country.mpoly.sym_difference(geom).equals(country.sym_difference) ) @skipUnlessDBFeature("has_Transform_function") def test_transform(self): # Pre-transformed points for Houston and Pueblo. ptown = fromstr("POINT(992363.390841912 481455.395105533)", srid=2774) # Asserting the result of the transform operation with the values in # the pre-transformed points. h = City.objects.annotate(pt=functions.Transform("point", ptown.srid)).get( name="Pueblo" ) self.assertEqual(2774, h.pt.srid) # Precision is low due to version variations in PROJ and GDAL. self.assertLess(ptown.x - h.pt.x, 1) self.assertLess(ptown.y - h.pt.y, 1) @skipUnlessDBFeature("has_Translate_function") def test_translate(self): xfac, yfac = 5, -23 qs = Country.objects.annotate( translated=functions.Translate("mpoly", xfac, yfac) ) for c in qs: for p1, p2 in zip(c.mpoly, c.translated): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): # The low precision is for SpatiaLite self.assertAlmostEqual(c1[0] + xfac, c2[0], 5) self.assertAlmostEqual(c1[1] + yfac, c2[1], 5) # Some combined function tests @skipUnlessDBFeature( "has_Difference_function", "has_Intersection_function", "has_SymDifference_function", "has_Union_function", ) def test_diff_intersection_union(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate( difference=functions.Difference("mpoly", geom), sym_difference=functions.SymDifference("mpoly", geom), union=functions.Union("mpoly", geom), intersection=functions.Intersection("mpoly", geom), ) if connection.ops.oracle: # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). return for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.difference)) if connection.features.empty_intersection_returns_none: self.assertIsNone(c.intersection) else: self.assertIs(c.intersection.empty, True) self.assertTrue(c.mpoly.sym_difference(geom).equals(c.sym_difference)) self.assertTrue(c.mpoly.union(geom).equals(c.union)) @skipUnlessDBFeature("has_Union_function") def test_union(self): """Union with all combinations of geometries/geometry fields.""" geom = Point(-95.363151, 29.763374, srid=4326) union = ( City.objects.annotate(union=functions.Union("point", geom)) .get(name="Dallas") .union ) expected = fromstr( "MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)", srid=4326 ) self.assertTrue(expected.equals(union)) union = ( City.objects.annotate(union=functions.Union(geom, "point")) .get(name="Dallas") .union ) self.assertTrue(expected.equals(union)) union = ( City.objects.annotate(union=functions.Union("point", "point")) .get(name="Dallas") .union ) expected = GEOSGeometry("POINT(-96.801611 32.782057)", srid=4326) self.assertTrue(expected.equals(union)) union = ( City.objects.annotate(union=functions.Union(geom, geom)) .get(name="Dallas") .union ) self.assertTrue(geom.equals(union)) @skipUnlessDBFeature("has_Union_function", "has_Transform_function") def test_union_mixed_srid(self): """The result SRID depends on the order of parameters.""" geom = Point(61.42915, 55.15402, srid=4326) geom_3857 = geom.transform(3857, clone=True) tol = 0.001 for city in City.objects.annotate(union=functions.Union("point", geom_3857)): expected = city.point | geom self.assertTrue(city.union.equals_exact(expected, tol)) self.assertEqual(city.union.srid, 4326) for city in City.objects.annotate(union=functions.Union(geom_3857, "point")): expected = geom_3857 | city.point.transform(3857, clone=True) self.assertTrue(expected.equals_exact(city.union, tol)) self.assertEqual(city.union.srid, 3857) def test_argument_validation(self): with self.assertRaisesMessage( ValueError, "SRID is required for all geometries." ): City.objects.annotate(geo=functions.GeoFunc(Point(1, 1))) msg = "GeoFunc function requires a GeometryField in position 1, got CharField." with self.assertRaisesMessage(TypeError, msg): City.objects.annotate(geo=functions.GeoFunc("name")) msg = "GeoFunc function requires a geometric argument in position 1." with self.assertRaisesMessage(TypeError, msg): City.objects.annotate(union=functions.GeoFunc(1, "point")).get( name="Dallas" )
720d69796c3481a5c371c65c54e175baf2eb2a8969ac3ac77304eca74a37dc16
import tempfile from io import StringIO from django.contrib.gis import gdal from django.contrib.gis.db.models import Extent, MakeLine, Union, functions from django.contrib.gis.geos import ( GeometryCollection, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromstr, ) from django.core.management import call_command from django.db import DatabaseError, NotSupportedError, connection from django.db.models import F, OuterRef, Subquery from django.test import TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..utils import skipUnlessGISLookup from .models import ( City, Country, Feature, MinusOneSRID, MultiFields, NonConcreteModel, PennsylvaniaCity, State, Track, ) class GeoModelTest(TestCase): fixtures = ["initial"] def test_fixtures(self): "Testing geographic model initialization from fixtures." # Ensuring that data was loaded from initial data fixtures. self.assertEqual(2, Country.objects.count()) self.assertEqual(8, City.objects.count()) self.assertEqual(2, State.objects.count()) def test_proxy(self): "Testing Lazy-Geometry support (using the GeometryProxy)." # Testing on a Point pnt = Point(0, 0) nullcity = City(name="NullCity", point=pnt) nullcity.save() # Making sure TypeError is thrown when trying to set with an # incompatible type. for bad in [5, 2.0, LineString((0, 0), (1, 1))]: with self.assertRaisesMessage(TypeError, "Cannot set"): nullcity.point = bad # Now setting with a compatible GEOS Geometry, saving, and ensuring # the save took, notice no SRID is explicitly set. new = Point(5, 23) nullcity.point = new # Ensuring that the SRID is automatically set to that of the # field after assignment, but before saving. self.assertEqual(4326, nullcity.point.srid) nullcity.save() # Ensuring the point was saved correctly after saving self.assertEqual(new, City.objects.get(name="NullCity").point) # Setting the X and Y of the Point nullcity.point.x = 23 nullcity.point.y = 5 # Checking assignments pre & post-save. self.assertNotEqual( Point(23, 5, srid=4326), City.objects.get(name="NullCity").point ) nullcity.save() self.assertEqual( Point(23, 5, srid=4326), City.objects.get(name="NullCity").point ) nullcity.delete() # Testing on a Polygon shell = LinearRing((0, 0), (0, 90), (100, 90), (100, 0), (0, 0)) inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40)) # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name="NullState", poly=ply) self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name="NullState") self.assertEqual(connection.ops.Adapter._fix_polygon(ply), ns.poly) # Testing the `ogr` and `srs` lazy-geometry properties. self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry) self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb) self.assertIsInstance(ns.poly.srs, gdal.SpatialReference) self.assertEqual("WGS 84", ns.poly.srs.name) # Changing the interior ring on the poly attribute. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30)) ns.poly[1] = new_inner ply[1] = new_inner self.assertEqual(4326, ns.poly.srid) ns.save() self.assertEqual( connection.ops.Adapter._fix_polygon(ply), State.objects.get(name="NullState").poly, ) ns.delete() @skipUnlessDBFeature("supports_transform") def test_lookup_insert_transform(self): "Testing automatic transform for lookups and inserts." # San Antonio in 'WGS84' (SRID 4326) sa_4326 = "POINT (-98.493183 29.424170)" wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857) other_srid_pnt = wgs_pnt.transform(3857, clone=True) # Constructing & querying with a point from a different SRID. Oracle # `SDO_OVERLAPBDYINTERSECT` operates differently from # `ST_Intersects`, so contains is used instead. if connection.ops.oracle: tx = Country.objects.get(mpoly__contains=other_srid_pnt) else: tx = Country.objects.get(mpoly__intersects=other_srid_pnt) self.assertEqual("Texas", tx.name) # Creating San Antonio. Remember the Alamo. sa = City.objects.create(name="San Antonio", point=other_srid_pnt) # Now verifying that San Antonio was transformed correctly sa = City.objects.get(name="San Antonio") self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6) self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6) # If the GeometryField SRID is -1, then we shouldn't perform any # transformation if the SRID of the input geometry is different. m1 = MinusOneSRID(geom=Point(17, 23, srid=4326)) m1.save() self.assertEqual(-1, m1.geom.srid) def test_createnull(self): "Testing creating a model instance and the geometry being None" c = City() self.assertIsNone(c.point) def test_geometryfield(self): "Testing the general GeometryField." Feature(name="Point", geom=Point(1, 1)).save() Feature(name="LineString", geom=LineString((0, 0), (1, 1), (5, 5))).save() Feature( name="Polygon", geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), ).save() Feature( name="GeometryCollection", geom=GeometryCollection( Point(2, 2), LineString((0, 0), (2, 2)), Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))), ), ).save() f_1 = Feature.objects.get(name="Point") self.assertIsInstance(f_1.geom, Point) self.assertEqual((1.0, 1.0), f_1.geom.tuple) f_2 = Feature.objects.get(name="LineString") self.assertIsInstance(f_2.geom, LineString) self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple) f_3 = Feature.objects.get(name="Polygon") self.assertIsInstance(f_3.geom, Polygon) f_4 = Feature.objects.get(name="GeometryCollection") self.assertIsInstance(f_4.geom, GeometryCollection) self.assertEqual(f_3.geom, f_4.geom[2]) @skipUnlessDBFeature("supports_transform") def test_inherited_geofields(self): "Database functions on inherited Geometry fields." # Creating a Pennsylvanian city. PennsylvaniaCity.objects.create( name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)" ) # All transformation SQL will need to be performed on the # _parent_ table. qs = PennsylvaniaCity.objects.annotate( new_point=functions.Transform("point", srid=32128) ) self.assertEqual(1, qs.count()) for pc in qs: self.assertEqual(32128, pc.new_point.srid) def test_raw_sql_query(self): "Testing raw SQL query." cities1 = City.objects.all() point_select = connection.ops.select % "point" cities2 = list( City.objects.raw( "select id, name, %s as point from geoapp_city" % point_select ) ) self.assertEqual(len(cities1), len(cities2)) with self.assertNumQueries(0): # Ensure point isn't deferred. self.assertIsInstance(cities2[0].point, Point) def test_gis_query_as_string(self): """GIS queries can be represented as strings.""" query = City.objects.filter(point__within=Polygon.from_bbox((0, 0, 2, 2))) self.assertIn( connection.ops.quote_name(City._meta.db_table), str(query.query), ) def test_dumpdata_loaddata_cycle(self): """ Test a dumpdata/loaddata cycle with geographic data. """ out = StringIO() original_data = list(City.objects.order_by("name")) call_command("dumpdata", "geoapp.City", stdout=out) result = out.getvalue() houston = City.objects.get(name="Houston") self.assertIn('"point": "%s"' % houston.point.ewkt, result) # Reload now dumped data with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as tmp: tmp.write(result) tmp.seek(0) call_command("loaddata", tmp.name, verbosity=0) self.assertEqual(original_data, list(City.objects.order_by("name"))) @skipUnlessDBFeature("supports_empty_geometries") def test_empty_geometries(self): geometry_classes = [ Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon, GeometryCollection, ] for klass in geometry_classes: g = klass(srid=4326) feature = Feature.objects.create(name="Empty %s" % klass.__name__, geom=g) feature.refresh_from_db() if klass is LinearRing: # LinearRing isn't representable in WKB, so GEOSGeomtry.wkb # uses LineString instead. g = LineString(srid=4326) self.assertEqual(feature.geom, g) self.assertEqual(feature.geom.srid, g.srid) class GeoLookupTest(TestCase): fixtures = ["initial"] def test_disjoint_lookup(self): "Testing the `disjoint` lookup type." ptown = City.objects.get(name="Pueblo") qs1 = City.objects.filter(point__disjoint=ptown.point) self.assertEqual(7, qs1.count()) qs2 = State.objects.filter(poly__disjoint=ptown.point) self.assertEqual(1, qs2.count()) self.assertEqual("Kansas", qs2[0].name) def test_contains_contained_lookups(self): "Testing the 'contained', 'contains', and 'bbcontains' lookup types." # Getting Texas, yes we were a country -- once ;) texas = Country.objects.get(name="Texas") # Seeing what cities are in Texas, should get Houston and Dallas, # and Oklahoma City because 'contained' only checks on the # _bounding box_ of the Geometries. if connection.features.supports_contained_lookup: qs = City.objects.filter(point__contained=texas.mpoly) self.assertEqual(3, qs.count()) cities = ["Houston", "Dallas", "Oklahoma City"] for c in qs: self.assertIn(c.name, cities) # Pulling out some cities. houston = City.objects.get(name="Houston") wellington = City.objects.get(name="Wellington") pueblo = City.objects.get(name="Pueblo") okcity = City.objects.get(name="Oklahoma City") lawrence = City.objects.get(name="Lawrence") # Now testing contains on the countries using the points for # Houston and Wellington. tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry nz = Country.objects.get( mpoly__contains=wellington.point.hex ) # Query w/EWKBHEX self.assertEqual("Texas", tx.name) self.assertEqual("New Zealand", nz.name) # Testing `contains` on the states using the point for Lawrence. ks = State.objects.get(poly__contains=lawrence.point) self.assertEqual("Kansas", ks.name) # Pueblo and Oklahoma City (even though OK City is within the bounding # box of Texas) are not contained in Texas or New Zealand. self.assertEqual( len(Country.objects.filter(mpoly__contains=pueblo.point)), 0 ) # Query w/GEOSGeometry object self.assertEqual( len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0 ) # Query w/WKT # OK City is contained w/in bounding box of Texas. if connection.features.supports_bbcontains_lookup: qs = Country.objects.filter(mpoly__bbcontains=okcity.point) self.assertEqual(1, len(qs)) self.assertEqual("Texas", qs[0].name) @skipUnlessDBFeature("supports_crosses_lookup") def test_crosses_lookup(self): Track.objects.create(name="Line1", line=LineString([(-95, 29), (-60, 0)])) self.assertEqual( Track.objects.filter( line__crosses=LineString([(-95, 0), (-60, 29)]) ).count(), 1, ) self.assertEqual( Track.objects.filter( line__crosses=LineString([(-95, 30), (0, 30)]) ).count(), 0, ) @skipUnlessDBFeature("supports_isvalid_lookup") def test_isvalid_lookup(self): invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") State.objects.create(name="invalid", poly=invalid_geom) qs = State.objects.all() if connection.ops.oracle: # Kansas has adjacent vertices with distance 6.99244813842e-12 # which is smaller than the default Oracle tolerance. qs = qs.exclude(name="Kansas") self.assertEqual( State.objects.filter(name="Kansas", poly__isvalid=False).count(), 1 ) self.assertEqual(qs.filter(poly__isvalid=False).count(), 1) self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1) @skipUnlessGISLookup("left", "right") def test_left_right_lookups(self): "Testing the 'left' and 'right' lookup types." # Left: A << B => true if xmax(A) < xmin(B) # Right: A >> B => true if xmin(A) > xmax(B) # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source. # Getting the borders for Colorado & Kansas co_border = State.objects.get(name="Colorado").poly ks_border = State.objects.get(name="Kansas").poly # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. # These cities should be strictly to the right of the CO border. cities = [ "Houston", "Dallas", "Oklahoma City", "Lawrence", "Chicago", "Wellington", ] qs = City.objects.filter(point__right=co_border) self.assertEqual(6, len(qs)) for c in qs: self.assertIn(c.name, cities) # These cities should be strictly to the right of the KS border. cities = ["Chicago", "Wellington"] qs = City.objects.filter(point__right=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) # Note: Wellington has an 'X' value of 174, so it will not be considered # to the left of CO. vic = City.objects.get(point__left=co_border) self.assertEqual("Victoria", vic.name) cities = ["Pueblo", "Victoria"] qs = City.objects.filter(point__left=ks_border) self.assertEqual(2, len(qs)) for c in qs: self.assertIn(c.name, cities) @skipUnlessGISLookup("strictly_above", "strictly_below") def test_strictly_above_below_lookups(self): dallas = City.objects.get(name="Dallas") self.assertQuerySetEqual( City.objects.filter(point__strictly_above=dallas.point).order_by("name"), ["Chicago", "Lawrence", "Oklahoma City", "Pueblo", "Victoria"], lambda b: b.name, ) self.assertQuerySetEqual( City.objects.filter(point__strictly_below=dallas.point).order_by("name"), ["Houston", "Wellington"], lambda b: b.name, ) def test_equals_lookups(self): "Testing the 'same_as' and 'equals' lookup types." pnt = fromstr("POINT (-95.363151 29.763374)", srid=4326) c1 = City.objects.get(point=pnt) c2 = City.objects.get(point__same_as=pnt) c3 = City.objects.get(point__equals=pnt) for c in [c1, c2, c3]: self.assertEqual("Houston", c.name) @skipUnlessDBFeature("supports_null_geometries") def test_null_geometries(self): "Testing NULL geometry support, and the `isnull` lookup type." # Creating a state with a NULL boundary. State.objects.create(name="Puerto Rico") # Querying for both NULL and Non-NULL values. nullqs = State.objects.filter(poly__isnull=True) validqs = State.objects.filter(poly__isnull=False) # Puerto Rico should be NULL (it's a commonwealth unincorporated territory) self.assertEqual(1, len(nullqs)) self.assertEqual("Puerto Rico", nullqs[0].name) # GeometryField=None is an alias for __isnull=True. self.assertCountEqual(State.objects.filter(poly=None), nullqs) self.assertCountEqual(State.objects.exclude(poly=None), validqs) # The valid states should be Colorado & Kansas self.assertEqual(2, len(validqs)) state_names = [s.name for s in validqs] self.assertIn("Colorado", state_names) self.assertIn("Kansas", state_names) # Saving another commonwealth w/a NULL geometry. nmi = State.objects.create(name="Northern Mariana Islands", poly=None) self.assertIsNone(nmi.poly) # Assigning a geometry and saving -- then UPDATE back to NULL. nmi.poly = "POLYGON((0 0,1 0,1 1,1 0,0 0))" nmi.save() State.objects.filter(name="Northern Mariana Islands").update(poly=None) self.assertIsNone(State.objects.get(name="Northern Mariana Islands").poly) @skipUnlessDBFeature( "supports_null_geometries", "supports_crosses_lookup", "supports_relate_lookup" ) def test_null_geometries_excluded_in_lookups(self): """NULL features are excluded in spatial lookup functions.""" null = State.objects.create(name="NULL", poly=None) queries = [ ("equals", Point(1, 1)), ("disjoint", Point(1, 1)), ("touches", Point(1, 1)), ("crosses", LineString((0, 0), (1, 1), (5, 5))), ("within", Point(1, 1)), ("overlaps", LineString((0, 0), (1, 1), (5, 5))), ("contains", LineString((0, 0), (1, 1), (5, 5))), ("intersects", LineString((0, 0), (1, 1), (5, 5))), ("relate", (Point(1, 1), "T*T***FF*")), ("same_as", Point(1, 1)), ("exact", Point(1, 1)), ("coveredby", Point(1, 1)), ("covers", Point(1, 1)), ] for lookup, geom in queries: with self.subTest(lookup=lookup): self.assertNotIn( null, State.objects.filter(**{"poly__%s" % lookup: geom}) ) def test_wkt_string_in_lookup(self): # Valid WKT strings don't emit error logs. with self.assertNoLogs("django.contrib.gis", "ERROR"): State.objects.filter(poly__intersects="LINESTRING(0 0, 1 1, 5 5)") @skipUnlessDBFeature("supports_relate_lookup") def test_relate_lookup(self): "Testing the 'relate' lookup type." # To make things more interesting, we will have our Texas reference point in # different SRIDs. pnt1 = fromstr("POINT (649287.0363174 4177429.4494686)", srid=2847) pnt2 = fromstr("POINT(-98.4919715741052 29.4333344025053)", srid=4326) # Not passing in a geometry as first param raises a TypeError when # initializing the QuerySet. with self.assertRaises(ValueError): Country.objects.filter(mpoly__relate=(23, "foo")) # Making sure the right exception is raised for the given # bad arguments. for bad_args, e in [ ((pnt1, 0), ValueError), ((pnt2, "T*T***FF*", 0), ValueError), ]: qs = Country.objects.filter(mpoly__relate=bad_args) with self.assertRaises(e): qs.count() contains_mask = "T*T***FF*" within_mask = "T*F**F***" intersects_mask = "T********" # Relate works differently on Oracle. if connection.ops.oracle: contains_mask = "contains" within_mask = "inside" # TODO: This is not quite the same as the PostGIS mask above intersects_mask = "overlapbdyintersect" # Testing contains relation mask. if connection.features.supports_transform: self.assertEqual( Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name, "Texas", ) self.assertEqual( "Texas", Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name ) # Testing within relation mask. ks = State.objects.get(name="Kansas") self.assertEqual( "Lawrence", City.objects.get(point__relate=(ks.poly, within_mask)).name ) # Testing intersection relation mask. if not connection.ops.oracle: if connection.features.supports_transform: self.assertEqual( Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name, "Texas", ) self.assertEqual( "Texas", Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name ) self.assertEqual( "Lawrence", City.objects.get(point__relate=(ks.poly, intersects_mask)).name, ) # With a complex geometry expression mask = "anyinteract" if connection.ops.oracle else within_mask self.assertFalse( City.objects.exclude( point__relate=(functions.Union("point", "point"), mask) ) ) def test_gis_lookups_with_complex_expressions(self): multiple_arg_lookups = { "dwithin", "relate", } # These lookups are tested elsewhere. lookups = connection.ops.gis_operators.keys() - multiple_arg_lookups self.assertTrue(lookups, "No lookups found") for lookup in lookups: with self.subTest(lookup): City.objects.filter( **{"point__" + lookup: functions.Union("point", "point")} ).exists() def test_subquery_annotation(self): multifields = MultiFields.objects.create( city=City.objects.create(point=Point(1, 1)), point=Point(2, 2), poly=Polygon.from_bbox((0, 0, 2, 2)), ) qs = MultiFields.objects.annotate( city_point=Subquery( City.objects.filter( id=OuterRef("city"), ).values("point") ), ).filter( city_point__within=F("poly"), ) self.assertEqual(qs.get(), multifields) class GeoQuerySetTest(TestCase): # TODO: GeoQuerySet is removed, organize these test better. fixtures = ["initial"] @skipUnlessDBFeature("supports_extent_aggr") def test_extent(self): """ Testing the `Extent` aggregate. """ # Reference query: # SELECT ST_extent(point) # FROM geoapp_city # WHERE (name='Houston' or name='Dallas');` # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203) expected = ( -96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820, ) qs = City.objects.filter(name__in=("Houston", "Dallas")) extent = qs.aggregate(Extent("point"))["point__extent"] for val, exp in zip(extent, expected): self.assertAlmostEqual(exp, val, 4) self.assertIsNone( City.objects.filter(name=("Smalltown")).aggregate(Extent("point"))[ "point__extent" ] ) @skipUnlessDBFeature("supports_extent_aggr") def test_extent_with_limit(self): """ Testing if extent supports limit. """ extent1 = City.objects.aggregate(Extent("point"))["point__extent"] extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"] self.assertNotEqual(extent1, extent2) def test_make_line(self): """ Testing the `MakeLine` aggregate. """ if not connection.features.supports_make_line_aggr: with self.assertRaises(NotSupportedError): City.objects.aggregate(MakeLine("point")) return # MakeLine on an inappropriate field returns simply None self.assertIsNone(State.objects.aggregate(MakeLine("poly"))["poly__makeline"]) # Reference query: # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city; line = City.objects.aggregate(MakeLine("point"))["point__makeline"] ref_points = City.objects.values_list("point", flat=True) self.assertIsInstance(line, LineString) self.assertEqual(len(line), ref_points.count()) # Compare pairs of manually sorted points, as the default ordering is # flaky. for point, ref_city in zip(sorted(line), sorted(ref_points)): point_x, point_y = point self.assertAlmostEqual(point_x, ref_city.x, 5), self.assertAlmostEqual(point_y, ref_city.y, 5), @skipUnlessDBFeature("supports_union_aggr") def test_unionagg(self): """ Testing the `Union` aggregate. """ tx = Country.objects.get(name="Texas").mpoly # Houston, Dallas -- Ordering may differ depending on backend or GEOS version. union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") qs = City.objects.filter(point__within=tx) with self.assertRaises(ValueError): qs.aggregate(Union("name")) # Using `field_name` keyword argument in one query and specifying an # order in the other (which should not be used because this is # an aggregate method on a spatial column) u1 = qs.aggregate(Union("point"))["point__union"] u2 = qs.order_by("name").aggregate(Union("point"))["point__union"] self.assertTrue(union.equals(u1)) self.assertTrue(union.equals(u2)) qs = City.objects.filter(name="NotACity") self.assertIsNone(qs.aggregate(Union("point"))["point__union"]) @skipUnlessDBFeature("supports_union_aggr") def test_geoagg_subquery(self): tx = Country.objects.get(name="Texas") union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)") # Use distinct() to force the usage of a subquery for aggregation. with CaptureQueriesContext(connection) as ctx: self.assertIs( union.equals( City.objects.filter(point__within=tx.mpoly) .distinct() .aggregate( Union("point"), )["point__union"], ), True, ) self.assertIn("subquery", ctx.captured_queries[0]["sql"]) @skipUnlessDBFeature("supports_tolerance_parameter") def test_unionagg_tolerance(self): City.objects.create( point=fromstr("POINT(-96.467222 32.751389)", srid=4326), name="Forney", ) tx = Country.objects.get(name="Texas").mpoly # Tolerance is greater than distance between Forney and Dallas, that's # why Dallas is ignored. forney_houston = GEOSGeometry( "MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)", srid=4326, ) self.assertIs( forney_houston.equals_exact( City.objects.filter(point__within=tx).aggregate( Union("point", tolerance=32000), )["point__union"], tolerance=10e-6, ), True, ) @skipUnlessDBFeature("supports_tolerance_parameter") def test_unionagg_tolerance_escaping(self): tx = Country.objects.get(name="Texas").mpoly with self.assertRaises(DatabaseError): City.objects.filter(point__within=tx).aggregate( Union("point", tolerance="0.05))), (((1"), ) def test_within_subquery(self): """ Using a queryset inside a geo lookup is working (using a subquery) (#14483). """ tex_cities = City.objects.filter( point__within=Country.objects.filter(name="Texas").values("mpoly") ).order_by("name") self.assertEqual( list(tex_cities.values_list("name", flat=True)), ["Dallas", "Houston"] ) def test_non_concrete_field(self): NonConcreteModel.objects.create(point=Point(0, 0), name="name") list(NonConcreteModel.objects.all()) def test_values_srid(self): for c, v in zip(City.objects.all(), City.objects.values()): self.assertEqual(c.point.srid, v["point"].srid)
618bb4dfcb3d93802ed28cadd1e7cda3eb6ef7b063f487980e28ad02a13eea96
import ctypes import itertools import json import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock, skipIf from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile, fromstr, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.contrib.gis.shortcuts import numpy from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = fromstr(g.wkt) if geom.hasz: self.assertEqual(g.ewkt, geom.wkt) def test_wkt_invalid(self): msg = "String input unrecognized as WKT EWKT, and HEXEWKB." with self.assertRaisesMessage(ValueError, msg): fromstr("POINT(٠٠١ ٠)") with self.assertRaisesMessage(ValueError, msg): fromstr("SRID=٧٥٨٣;POINT(100 0)") def test_hex(self): "Testing HEX output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode()) def test_hexewkb(self): "Testing (HEX)EWKB output." # For testing HEX(EWKB). ogc_hex = b"01010000000000000000000000000000000000F03F" ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040" # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));` hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F" # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));` hexewkb_3d = ( b"01010000A0E61000000000000000000000000000000000F03F0000000000000040" ) pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) # OGC-compliant HEX will not have SRID value. self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) # HEXEWKB should be appropriate for its dimension -- have to use an # a WKBWriter w/dimension set accordingly, else GEOS will insert # garbage into 3D coordinate if there is none. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True) # Same for EWKB. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) # Redundant sanity check. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid) def test_kml(self): "Testing KML output." for tg in self.geometries.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, "kml", False) if kml: self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): fromstr(err.wkt) # Bad WKB with self.assertRaises(GEOSException): GEOSGeometry(memoryview(b"0")) class NotAGeometry: pass # Some other object with self.assertRaises(TypeError): GEOSGeometry(NotAGeometry()) # None with self.assertRaises(TypeError): GEOSGeometry(None) def test_wkb(self): "Testing WKB output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(wkb.hex().upper(), g.hex) def test_create_hex(self): "Testing creation from HEX." for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_create_wkb(self): "Testing creation from WKB." for g in self.geometries.hex_wkt: wkb = memoryview(bytes.fromhex(g.hex)) geom_h = GEOSGeometry(wkb) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_ewkt(self): "Testing EWKT." srids = (-1, 32140) for srid in srids: for p in self.geometries.polygons: ewkt = "SRID=%d;%s" % (srid, p.wkt) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export def test_json(self): "Testing GeoJSON input/output (via GDAL)." for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if not hasattr(g, "not_equal"): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json)) def test_json_srid(self): geojson_data = { "type": "Point", "coordinates": [2, 49], "crs": { "type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::4322"}, }, } self.assertEqual( GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322) ) def test_fromfile(self): "Testing the fromfile() factory." ref_pnt = GEOSGeometry("POINT(5 23)") wkt_f = BytesIO() wkt_f.write(ref_pnt.wkt.encode()) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) # Other tests use `fromfile()` on string filenames so those # aren't tested here. for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt) def test_eq(self): "Testing equivalence." p = fromstr("POINT(5 23)") self.assertEqual(p, p.wkt) self.assertNotEqual(p, "foo") ls = fromstr("LINESTRING(0 0, 1 1, 5 5)") self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, "bar") self.assertEqual(p, "POINT(5.0 23.0)") # Error shouldn't be raise on equivalence testing with # an invalid type. for g in (p, ls): self.assertIsNotNone(g) self.assertNotEqual(g, {"foo": "bar"}) self.assertIsNot(g, False) def test_hash(self): point_1 = Point(5, 23) point_2 = Point(5, 23, srid=4326) point_3 = Point(5, 23, srid=32632) multipoint_1 = MultiPoint(point_1, srid=4326) multipoint_2 = MultiPoint(point_2) multipoint_3 = MultiPoint(point_3) self.assertNotEqual(hash(point_1), hash(point_2)) self.assertNotEqual(hash(point_1), hash(point_3)) self.assertNotEqual(hash(point_2), hash(point_3)) self.assertNotEqual(hash(multipoint_1), hash(multipoint_2)) self.assertEqual(hash(multipoint_2), hash(multipoint_3)) self.assertNotEqual(hash(multipoint_1), hash(point_1)) self.assertNotEqual(hash(multipoint_2), hash(point_2)) self.assertNotEqual(hash(multipoint_3), hash(point_3)) def test_eq_with_srid(self): "Testing non-equivalence with different srids." p0 = Point(5, 23) p1 = Point(5, 23, srid=4326) p2 = Point(5, 23, srid=32632) # GEOS self.assertNotEqual(p0, p1) self.assertNotEqual(p1, p2) # EWKT self.assertNotEqual(p0, p1.ewkt) self.assertNotEqual(p1, p0.ewkt) self.assertNotEqual(p1, p2.ewkt) # Equivalence with matching SRIDs self.assertEqual(p2, p2) self.assertEqual(p2, p2.ewkt) # WKT contains no SRID so will not equal self.assertNotEqual(p2, p2.wkt) # SRID of 0 self.assertEqual(p0, "SRID=0;POINT (5 23)") self.assertNotEqual(p1, "SRID=0;POINT (5 23)") def test_points(self): "Testing Point objects." prev = fromstr("POINT(0 0)") for p in self.geometries.points: # Creating the point from the WKT pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, "Point") self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(pnt.dims, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(pnt, fromstr(p.wkt)) self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__. # Making sure that the point's X, Y components are what we expect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, "z"): self.assertIs(pnt.hasz, True) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertIs(pnt.hasz, False) self.assertIsNone(pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) # Centroid operation on point should be point itself self.assertEqual(p.centroid, pnt.centroid.tuple) # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(pnt, pnt2) self.assertEqual(pnt, pnt3) # Now testing setting the x and y pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) # Setting via the tuple/coords property pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt # setting the previous geometry def test_point_reverse(self): point = GEOSGeometry("POINT(144.963 -37.8143)", 4326) self.assertEqual(point.srid, 4326) point.reverse() self.assertEqual(point.ewkt, "SRID=4326;POINT (-37.8143 144.963)") def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, "MultiPoint") self.assertEqual(mpnt.geom_typeid, 4) self.assertEqual(mpnt.dims, 0) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) with self.assertRaises(IndexError): mpnt.__getitem__(len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) for p in mpnt: self.assertEqual(p.geom_type, "Point") self.assertEqual(p.geom_typeid, 0) self.assertIs(p.empty, False) self.assertIs(p.valid, True) def test_linestring(self): "Testing LineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.linestrings: ls = fromstr(line.wkt) self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.dims, 1) self.assertIs(ls.empty, False) self.assertIs(ls.ring, False) if hasattr(line, "centroid"): self.assertEqual(line.centroid, ls.centroid.tuple) if hasattr(line, "tup"): self.assertEqual(line.tup, ls.tuple) self.assertEqual(ls, fromstr(line.wkt)) self.assertIs(ls == prev, False) # Use assertIs() to test __eq__. with self.assertRaises(IndexError): ls.__getitem__(len(ls)) prev = ls # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list # Point individual arguments self.assertEqual( ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt ) if numpy: self.assertEqual( ls, LineString(numpy.array(ls.tuple)) ) # as numpy array with self.assertRaisesMessage( TypeError, "Each coordinate should be a sequence (list or tuple)" ): LineString((0, 0)) with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString(numpy.array([(0, 0)])) with mock.patch("django.contrib.gis.geos.linestring.numpy", False): with self.assertRaisesMessage( TypeError, "Invalid initialization input for LineStrings." ): LineString("wrong input") # Test __iter__(). self.assertEqual( list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)] ) def test_linestring_reverse(self): line = GEOSGeometry("LINESTRING(144.963 -37.8143,151.2607 -33.887)", 4326) self.assertEqual(line.srid, 4326) line.reverse() self.assertEqual( line.ewkt, "SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)" ) def _test_is_counterclockwise(self): lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0)) self.assertIs(lr.is_counterclockwise, True) lr.reverse() self.assertIs(lr.is_counterclockwise, False) msg = "Orientation of an empty LinearRing cannot be determined." with self.assertRaisesMessage(ValueError, msg): LinearRing().is_counterclockwise @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise(self): self._test_is_counterclockwise() @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise_geos_error(self): with mock.patch("django.contrib.gis.geos.prototypes.cs_is_ccw") as mocked: mocked.return_value = 0 mocked.func_name = "GEOSCoordSeq_isCCW" msg = 'Error encountered in GEOS C function "GEOSCoordSeq_isCCW".' with self.assertRaisesMessage(GEOSException, msg): LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.6.9") def test_is_counterclockwise_fallback(self): self._test_is_counterclockwise() def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.multilinestrings: ml = fromstr(line.wkt) self.assertEqual(ml.geom_type, "MultiLineString") self.assertEqual(ml.geom_typeid, 5) self.assertEqual(ml.dims, 1) self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9) self.assertEqual(ml, fromstr(line.wkt)) self.assertIs(ml == prev, False) # Use assertIs() to test __eq__. prev = ml for ls in ml: self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertIs(ls.empty, False) with self.assertRaises(IndexError): ml.__getitem__(len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual( ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)) ) def test_linearring(self): "Testing LinearRing objects." for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, "LinearRing") self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.dims, 1) self.assertEqual(rr.n_p, len(lr)) self.assertIs(lr.valid, True) self.assertIs(lr.empty, False) # Creating a LinearRing from a tuple, list, and numpy array self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple))) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 3." ): LinearRing((0, 0), (1, 1), (0, 0)) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing(numpy.array([(0, 0)])) def test_linearring_json(self): self.assertJSONEqual( LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json, '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}', ) def test_polygons_from_bbox(self): "Testing `from_bbox` class method." bbox = (-180, -90, 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) # Testing numerical precision x = 3.14159265358979323 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[-1] self.assertEqual(format(x, ".13f"), format(y, ".13f")) def test_polygons(self): "Testing Polygon objects." prev = fromstr("POINT(0 0)") for p in self.geometries.polygons: # Creating the Polygon, testing its properties. poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, "Polygon") self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.dims, 2) self.assertIs(poly.empty, False) self.assertIs(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) # Testing the geometry equivalence self.assertEqual(poly, fromstr(p.wkt)) # Should not be equal to previous geometry self.assertIs(poly == prev, False) # Use assertIs() to test __eq__. self.assertIs(poly != prev, True) # Use assertIs() to test __ne__. # Testing the exterior ring ring = poly.exterior_ring self.assertEqual(ring.geom_type, "LinearRing") self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices with self.assertRaises(IndexError): poly.__getitem__(len(poly)) with self.assertRaises(IndexError): poly.__setitem__(len(poly), False) with self.assertRaises(IndexError): poly.__getitem__(-1 * len(poly) - 1) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, "LinearRing") self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. with self.assertRaises(TypeError): Polygon(0, [1, 2, 3]) with self.assertRaises(TypeError): Polygon("foo") # Polygon(shell, (hole1, ... holeN)) ext_ring, *int_rings = poly self.assertEqual(poly, Polygon(ext_ring, int_rings)) # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN) ring_tuples = tuple(r.tuple for r in poly) self.assertEqual(poly, Polygon(*ring_tuples)) # Constructing with tuples of LinearRings. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt) self.assertEqual( poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt ) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content) def test_polygon_comparison(self): p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0))) self.assertGreater(p1, p2) self.assertLess(p2, p1) p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0))) p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0))) self.assertGreater(p4, p3) self.assertLess(p3, p4) def test_multipolygons(self): "Testing MultiPolygon objects." fromstr("POINT (0 0)") for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, "MultiPolygon") self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mpoly.dims, 2) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) with self.assertRaises(IndexError): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, "Polygon") self.assertEqual(p.geom_typeid, 3) self.assertIs(p.valid, True) self.assertEqual( mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt ) def test_memory_hijinks(self): "Testing Geometry __del__() on rings and polygons." # #### Memory issues with rings and poly # These tests are needed to ensure sanity with writable geometries. # Getting a polygon with interior rings, and pulling out the interior rings poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] # These deletes should be 'harmless' since they are done on child geometries del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] # Deleting the polygon del poly # Access to these rings is OK since they are clones. str(ring1) str(ring2) def test_coord_seq(self): "Testing Coordinate Sequence objects." for p in self.geometries.polygons: if p.ext_ring_cs: # Constructing the polygon and getting the coordinate sequence poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq self.assertEqual( p.ext_ring_cs, cs.tuple ) # done in the Polygon test too. self.assertEqual( len(p.ext_ring_cs), len(cs) ) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in range(len(p.ext_ring_cs)): c1 = p.ext_ring_cs[i] # Expected value c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with if len(c1) == 2: tset = (5, 23) else: tset = (5, 23, 8) cs[i] = tset # Making sure every set point matches what we expect for j in range(len(tset)): cs[i] = tset self.assertEqual(tset[j], cs[i][j]) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr("POINT (0 0)") with self.assertRaises(GEOSException): g.relate_pattern(0, "invalid pattern, yo") for rg in self.geometries.relate_geoms: a = fromstr(rg.wkt_a) b = fromstr(rg.wkt_b) self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern)) self.assertEqual(rg.pattern, a.relate(b)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) i1 = fromstr(self.geometries.intersect_geoms[i].wkt) self.assertIs(a.intersects(b), True) i2 = a.intersection(b) self.assertTrue(i1.equals(i2)) self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator a &= b # testing __iand__ self.assertTrue(i1.equals(a)) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertTrue(u1.equals(u2)) self.assertTrue(u1.equals(a | b)) # __or__ is union operator a |= b # testing __ior__ self.assertTrue(u1.equals(a)) def test_unary_union(self): "Testing unary_union." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = GeometryCollection(a, b).unary_union self.assertTrue(u1.equals(u2)) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator a -= b # testing __isub__ self.assertTrue(d1.equals(a)) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue( d1.equals(a ^ b) ) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertTrue(d1.equals(a)) def test_buffer(self): bg = self.geometries.buffer_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer(bg.width, quadsegs=1.1) self._test_buffer(self.geometries.buffer_geoms, "buffer") def test_buffer_with_style(self): bg = self.geometries.buffer_with_style_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, quadsegs=1.1) # Can't use a floating-point for the end cap style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, end_cap_style=1.2) # Can't use a end cap style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, end_cap_style=55) # Can't use a floating-point for the join style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, join_style=1.3) # Can't use a join style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, join_style=66) self._test_buffer( itertools.chain( self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms ), "buffer_with_style", ) def _test_buffer(self, geometries, buffer_method_name): for bg in geometries: g = fromstr(bg.wkt) # The buffer we expect exp_buf = fromstr(bg.buffer_wkt) # Constructing our buffer buf_kwargs = { kwarg_name: getattr(bg, kwarg_name) for kwarg_name in ( "width", "quadsegs", "end_cap_style", "join_style", "mitre_limit", ) if hasattr(bg, kwarg_name) } buf = getattr(g, buffer_method_name)(**buf_kwargs) self.assertEqual(exp_buf.num_coords, buf.num_coords) self.assertEqual(len(exp_buf), len(buf)) # Now assuring that each point in the buffer is almost equal for j in range(len(exp_buf)): exp_ring = exp_buf[j] buf_ring = buf[j] self.assertEqual(len(exp_ring), len(buf_ring)) for k in range(len(exp_ring)): # Asserting the X, Y of each point are almost equal (due to # floating point imprecision). self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9) self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9) def test_covers(self): poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0))) self.assertTrue(poly.covers(Point(5, 5))) self.assertFalse(poly.covers(Point(100, 100))) def test_closed(self): ls_closed = LineString((0, 0), (1, 1), (0, 0)) ls_not_closed = LineString((0, 0), (1, 1)) self.assertFalse(ls_not_closed.closed) self.assertTrue(ls_closed.closed) def test_srid(self): "Testing the SRID property and keyword." # Testing SRID keyword on Point pnt = Point(5, 23, srid=4326) self.assertEqual(4326, pnt.srid) pnt.srid = 3084 self.assertEqual(3084, pnt.srid) with self.assertRaises(ctypes.ArgumentError): pnt.srid = "4326" # Testing SRID keyword on fromstr(), and on Polygon rings. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269) self.assertEqual(4269, poly.srid) for ring in poly: self.assertEqual(4269, ring.srid) poly.srid = 4326 self.assertEqual(4326, poly.shell.srid) # Testing SRID keyword on GeometryCollection gc = GeometryCollection( Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021 ) self.assertEqual(32021, gc.srid) for i in range(len(gc)): self.assertEqual(32021, gc[i].srid) # GEOS may get the SRID from HEXEWKB # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS # using `SELECT GeomFromText('POINT (5 23)', 4326);`. hex = "0101000020E610000000000000000014400000000000003740" p1 = fromstr(hex) self.assertEqual(4326, p1.srid) p2 = fromstr(p1.hex) self.assertIsNone(p2.srid) p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) # Testing that geometry SRID could be set to its own value pnt_wo_srid = Point(1, 1) pnt_wo_srid.srid = pnt_wo_srid.srid # Input geometries that have an SRID. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid) self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkt, srid=1) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkb, srid=1) def test_custom_srid(self): """Test with a null srid and a srid unknown to GDAL.""" for srid in [None, 999999]: pnt = Point(111200, 220900, srid=srid) self.assertTrue( pnt.ewkt.startswith( ("SRID=%s;" % srid if srid else "") + "POINT (111200" ) ) self.assertIsInstance(pnt.ogr, gdal.OGRGeometry) self.assertIsNone(pnt.srs) # Test conversion from custom to a known srid c2w = gdal.CoordTransform( gdal.SpatialReference( "+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +datum=WGS84 " "+units=m +no_defs" ), gdal.SpatialReference(4326), ) new_pnt = pnt.transform(c2w, clone=True) self.assertEqual(new_pnt.srid, 4326) self.assertAlmostEqual(new_pnt.x, 1, 1) self.assertAlmostEqual(new_pnt.y, 2, 1) def test_mutable_geometries(self): "Testing the mutability of Polygons and Geometry Collections." # ### Testing the mutability of Polygons ### for p in self.geometries.polygons: poly = fromstr(p.wkt) # Should only be able to use __setitem__ with LinearRing geometries. with self.assertRaises(TypeError): poly.__setitem__(0, LineString((1, 1), (2, 2))) # Constructing the new shell by adding 500 to every point in the old shell. shell_tup = poly.shell.tuple new_coords = [] for point in shell_tup: new_coords.append((point[0] + 500.0, point[1] + 500.0)) new_shell = LinearRing(*tuple(new_coords)) # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) # ### Testing the mutability of Geometry Collections for tg in self.geometries.multipoints: mp = fromstr(tg.wkt) for i in range(len(mp)): # Creating a random point. pnt = mp[i] new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) # MultiPolygons involve much more memory management because each # Polygon w/in the collection has its own rings. for tg in self.geometries.multipolygons: mpoly = fromstr(tg.wkt) for i in range(len(mpoly)): poly = mpoly[i] old_poly = mpoly[i] # Offsetting the each ring in the polygon by 500. for j in range(len(poly)): r = poly[j] for k in range(len(r)): r[k] = (r[k][0] + 500.0, r[k][1] + 500.0) poly[j] = r self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) # Extreme (!!) __setitem__ -- no longer works, have to detect # in the first object that __setitem__ is called in the subsequent # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)? # mpoly[0][0][0] = (3.14, 2.71) # self.assertEqual((3.14, 2.71), mpoly[0][0][0]) # Doing it more slowly.. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0]) # del mpoly def test_point_list_assignment(self): p = Point(0, 0) p[:] = (1, 2, 3) self.assertEqual(p, Point(1, 2, 3)) p[:] = () self.assertEqual(p.wkt, Point()) p[:] = (1, 2) self.assertEqual(p.wkt, Point(1, 2)) with self.assertRaises(ValueError): p[:] = (1,) with self.assertRaises(ValueError): p[:] = (1, 2, 3, 4, 5) def test_linestring_list_assignment(self): ls = LineString((0, 0), (1, 1)) ls[:] = () self.assertEqual(ls, LineString()) ls[:] = ((0, 0), (1, 1), (2, 2)) self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2))) with self.assertRaises(ValueError): ls[:] = (1,) def test_linearring_list_assignment(self): ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) ls[:] = () self.assertEqual(ls, LinearRing()) ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) with self.assertRaises(ValueError): ls[:] = ((0, 0), (1, 1), (2, 2)) def test_polygon_list_assignment(self): pol = Polygon() pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),) self.assertEqual( pol, Polygon( ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), ), ) pol[:] = () self.assertEqual(pol, Polygon()) def test_geometry_collection_list_assignment(self): p = Point() gc = GeometryCollection() gc[:] = [p] self.assertEqual(gc, GeometryCollection(p)) gc[:] = () self.assertEqual(gc, GeometryCollection()) def test_threed(self): "Testing three-dimensional geometries." # Testing a 3D Point pnt = Point(2, 3, 8) self.assertEqual((2.0, 3.0, 8.0), pnt.coords) with self.assertRaises(TypeError): pnt.tuple = (1.0, 2.0) pnt.coords = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), pnt.coords) # Testing a 3D LineString ls = LineString((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)) self.assertEqual(((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)), ls.tuple) with self.assertRaises(TypeError): ls.__setitem__(0, (1.0, 2.0)) ls[0] = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), ls[0]) def test_distance(self): "Testing the distance() function." # Distance to self should be 0. pnt = Point(0, 0) self.assertEqual(0.0, pnt.distance(Point(0, 0))) # Distance should be 1 self.assertEqual(1.0, pnt.distance(Point(0, 1))) # Distance should be ~ sqrt(2) self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11) # Distances are from the closest vertex in each geometry -- # should be 3 (distance from (2, 2) to (5, 2)). ls1 = LineString((0, 0), (1, 1), (2, 2)) ls2 = LineString((5, 2), (6, 1), (7, 0)) self.assertEqual(3, ls1.distance(ls2)) def test_length(self): "Testing the length property." # Points have 0 length. pnt = Point(0, 0) self.assertEqual(0.0, pnt.length) # Should be ~ sqrt(2) ls = LineString((0, 0), (1, 1)) self.assertAlmostEqual(1.41421356237, ls.length, 11) # Should be circumference of Polygon poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) self.assertEqual(4.0, poly.length) # Should be sum of each element's length in collection. mpoly = MultiPolygon(poly.clone(), poly) self.assertEqual(8.0, mpoly.length) def test_emptyCollections(self): "Testing empty geometries and collections." geoms = [ GeometryCollection([]), fromstr("GEOMETRYCOLLECTION EMPTY"), GeometryCollection(), fromstr("POINT EMPTY"), Point(), fromstr("LINESTRING EMPTY"), LineString(), fromstr("POLYGON EMPTY"), Polygon(), fromstr("MULTILINESTRING EMPTY"), MultiLineString(), fromstr("MULTIPOLYGON EMPTY"), MultiPolygon(()), MultiPolygon(), ] if numpy: geoms.append(LineString(numpy.array([]))) for g in geoms: self.assertIs(g.empty, True) # Testing len() and num_geom. if isinstance(g, Polygon): self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g)) else: self.assertEqual(0, g.num_geom) self.assertEqual(0, len(g)) # Testing __getitem__ (doesn't work on Point or Polygon) if isinstance(g, Point): # IndexError is not raised in GEOS 3.8.0. if geos_version_tuple() != (3, 8, 0): with self.assertRaises(IndexError): g.x elif isinstance(g, Polygon): lr = g.shell self.assertEqual("LINEARRING EMPTY", lr.wkt) self.assertEqual(0, len(lr)) self.assertIs(lr.empty, True) with self.assertRaises(IndexError): lr.__getitem__(0) else: with self.assertRaises(IndexError): g.__getitem__(0) def test_collection_dims(self): gc = GeometryCollection([]) self.assertEqual(gc.dims, -1) gc = GeometryCollection(Point(0, 0)) self.assertEqual(gc.dims, 0) gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0)) self.assertEqual(gc.dims, 1) gc = GeometryCollection( LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0), ) self.assertEqual(gc.dims, 2) def test_collections_of_collections(self): "Testing GeometryCollection handling of other collections." # Creating a GeometryCollection WKT string composed of other # collections and polygons. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid] coll.extend(mls.wkt for mls in self.geometries.multilinestrings) coll.extend(p.wkt for p in self.geometries.polygons) coll.extend(mp.wkt for mp in self.geometries.multipoints) gc_wkt = "GEOMETRYCOLLECTION(%s)" % ",".join(coll) # Should construct ok from WKT gc1 = GEOSGeometry(gc_wkt) # Should also construct ok from individual geometry arguments. gc2 = GeometryCollection(*tuple(g for g in gc1)) # And, they should be equal. self.assertEqual(gc1, gc2) def test_gdal(self): "Testing `ogr` and `srs` properties." g1 = fromstr("POINT(5 23)") self.assertIsInstance(g1.ogr, gdal.OGRGeometry) self.assertIsNone(g1.srs) g1_3d = fromstr("POINT(5 23 8)") self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry) self.assertEqual(g1_3d.ogr.z, 8) g2 = fromstr("LINESTRING(0 0, 5 5, 23 23)", srid=4326) self.assertIsInstance(g2.ogr, gdal.OGRGeometry) self.assertIsInstance(g2.srs, gdal.SpatialReference) self.assertEqual(g2.hex, g2.ogr.hex) self.assertEqual("WGS 84", g2.srs.name) def test_copy(self): "Testing use with the Python `copy` module." import copy poly = GEOSGeometry( "POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))" ) cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr) def test_transform(self): "Testing `transform` method." orig = GEOSGeometry("POINT (-104.609 38.255)", 4326) trans = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) # Using a srid, a SpatialReference object, and a CoordTransform object # for transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(gdal.SpatialReference("EPSG:2774")) ct = gdal.CoordTransform( gdal.SpatialReference("WGS84"), gdal.SpatialReference(2774) ) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_3d(self): p3d = GEOSGeometry("POINT (5 23 100)", 4326) p3d.transform(2774) self.assertAlmostEqual(p3d.z, 100, 3) def test_transform_noop(self): """Testing `transform` method (SRID match)""" # transform() should no-op if source & dest SRIDs match, # regardless of whether GDAL is available. g = GEOSGeometry("POINT (-104.609 38.255)", 4326) gt = g.tuple g.transform(4326) self.assertEqual(g.tuple, gt) self.assertEqual(g.srid, 4326) g = GEOSGeometry("POINT (-104.609 38.255)", 4326) g1 = g.transform(4326, clone=True) self.assertEqual(g1.tuple, g.tuple) self.assertEqual(g1.srid, 4326) self.assertIsNot(g1, g, "Clone didn't happen") def test_transform_nosrid(self): """Testing `transform` method (no SRID or negative SRID)""" g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774, clone=True) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774, clone=True) def test_extent(self): "Testing `extent` method." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50)) self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) pnt = Point(5.23, 17.8) # Extent of points is just the point itself repeated. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent) # Testing on the 'real world' Polygon. poly = fromstr(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_pickle(self): "Testing pickling and unpickling support." # Creating a list of test geometries for pickling, # and setting the SRID on some of them. def get_geoms(lst, srid=None): return [GEOSGeometry(tg.wkt, srid) for tg in lst] tgeoms = get_geoms(self.geometries.points) tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326)) tgeoms.extend(get_geoms(self.geometries.polygons, 3084)) tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857)) tgeoms.append(Point(srid=4326)) tgeoms.append(Point()) for geom in tgeoms: s1 = pickle.dumps(geom) g1 = pickle.loads(s1) self.assertEqual(geom, g1) self.assertEqual(geom.srid, g1.srid) def test_prepared(self): "Testing PreparedGeometry support." # Creating a simple multipolygon and getting a prepared version. mpoly = GEOSGeometry( "MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))" ) prep = mpoly.prepared # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] for pnt in pnts: # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt)) self.assertEqual(mpoly.covers(pnt), prep.covers(pnt)) self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)"))) self.assertTrue(prep.disjoint(Point(-5, -5))) poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1))) self.assertTrue(prep.overlaps(poly)) poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0))) self.assertTrue(prep.touches(poly)) poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1))) self.assertTrue(prep.within(poly)) # Original geometry deletion should not crash the prepared one (#21662) del mpoly self.assertTrue(prep.covers(Point(5, 5))) def test_line_merge(self): "Testing line merge support" ref_geoms = ( fromstr("LINESTRING(1 1, 1 1, 3 3)"), fromstr("MULTILINESTRING((1 1, 3 3), (3 3, 4 2))"), ) ref_merged = ( fromstr("LINESTRING(1 1, 3 3)"), fromstr("LINESTRING (1 1, 3 3, 4 2)"), ) for geom, merged in zip(ref_geoms, ref_merged): self.assertEqual(merged, geom.merged) def test_valid_reason(self): "Testing IsValidReason support" g = GEOSGeometry("POINT(0 0)") self.assertTrue(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertEqual(g.valid_reason, "Valid Geometry") g = GEOSGeometry("LINESTRING(0 0, 0 0)") self.assertFalse(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertTrue( g.valid_reason.startswith("Too few points in geometry component") ) def test_linearref(self): "Testing linear referencing" ls = fromstr("LINESTRING(0 0, 0 10, 10 10, 10 0)") mls = fromstr("MULTILINESTRING((0 0, 0 10), (10 0, 10 10))") self.assertEqual(ls.project(Point(0, 20)), 10.0) self.assertEqual(ls.project(Point(7, 6)), 24) self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3) self.assertEqual(ls.interpolate(10), Point(0, 10)) self.assertEqual(ls.interpolate(24), Point(10, 6)) self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10)) self.assertEqual(mls.project(Point(0, 20)), 10) self.assertEqual(mls.project(Point(7, 6)), 16) self.assertEqual(mls.interpolate(9), Point(0, 9)) self.assertEqual(mls.interpolate(17), Point(10, 7)) def test_deconstructible(self): """ Geometry classes should be deconstructible. """ point = Point(4.337844, 50.827537, srid=4326) path, args, kwargs = point.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.point.Point") self.assertEqual(args, (4.337844, 50.827537)) self.assertEqual(kwargs, {"srid": 4326}) ls = LineString(((0, 0), (1, 1))) path, args, kwargs = ls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, (((0, 0), (1, 1)),)) self.assertEqual(kwargs, {}) ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326) path, args, kwargs = ls2.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, ([Point(0, 0), Point(1, 1)],)) self.assertEqual(kwargs, {"srid": 4326}) ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) poly = Polygon(ext_coords, int_coords) path, args, kwargs = poly.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.polygon.Polygon") self.assertEqual(args, (ext_coords, int_coords)) self.assertEqual(kwargs, {}) lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) path, args, kwargs = lr.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LinearRing") self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0))) self.assertEqual(kwargs, {}) mp = MultiPoint(Point(0, 0), Point(1, 1)) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPoint") self.assertEqual(args, (Point(0, 0), Point(1, 1))) self.assertEqual(kwargs, {}) ls1 = LineString((0, 0), (1, 1)) ls2 = LineString((2, 2), (3, 3)) mls = MultiLineString(ls1, ls2) path, args, kwargs = mls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiLineString") self.assertEqual(args, (ls1, ls2)) self.assertEqual(kwargs, {}) p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1))) mp = MultiPolygon(p1, p2) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPolygon") self.assertEqual(args, (p1, p2)) self.assertEqual(kwargs, {}) poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) path, args, kwargs = gc.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.GeometryCollection") self.assertEqual( args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) ) self.assertEqual(kwargs, {}) def test_subclassing(self): """ GEOSGeometry subclass may itself be subclassed without being forced-cast to the parent class during `__init__`. """ class ExtendedPolygon(Polygon): def __init__(self, *args, data=0, **kwargs): super().__init__(*args, **kwargs) self._data = data def __str__(self): return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt) ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3) self.assertEqual(type(ext_poly), ExtendedPolygon) # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__). self.assertEqual( str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))" ) self.assertJSONEqual( ext_poly.json, '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}', ) def test_geos_version_tuple(self): versions = ( (b"3.0.0rc4-CAPI-1.3.3", (3, 0, 0)), (b"3.0.0-CAPI-1.4.1", (3, 0, 0)), (b"3.4.0dev-CAPI-1.8.0", (3, 4, 0)), (b"3.4.0dev-CAPI-1.8.0 r0", (3, 4, 0)), (b"3.6.2-CAPI-1.10.2 4d2925d6", (3, 6, 2)), ) for version_string, version_tuple in versions: with self.subTest(version_string=version_string): with mock.patch( "django.contrib.gis.geos.libgeos.geos_version", lambda: version_string, ): self.assertEqual(geos_version_tuple(), version_tuple) def test_from_gml(self): self.assertEqual( GEOSGeometry("POINT(0 0)"), GEOSGeometry.from_gml( '<gml:Point gml:id="p21" ' 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' "</gml:Point>" ), ) def test_from_ewkt(self): self.assertEqual( GEOSGeometry.from_ewkt("SRID=1;POINT(1 1)"), Point(1, 1, srid=1) ) self.assertEqual(GEOSGeometry.from_ewkt("POINT(1 1)"), Point(1, 1)) def test_from_ewkt_empty_string(self): msg = "Expected WKT but got an empty string." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=1;") def test_from_ewkt_invalid_srid(self): msg = "EWKT has invalid SRID part." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRUD=1;POINT(1 1)") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=WGS84;POINT(1 1)") def test_fromstr_scientific_wkt(self): self.assertEqual(GEOSGeometry("POINT(1.0e-1 1.0e+1)"), Point(0.1, 10)) def test_normalize(self): multipoint = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1)) normalized = MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0)) # Geometry is normalized in-place and nothing is returned. multipoint_1 = multipoint.clone() self.assertIsNone(multipoint_1.normalize()) self.assertEqual(multipoint_1, normalized) # If the `clone` keyword is set, then the geometry is not modified and # a normalized clone of the geometry is returned instead. multipoint_2 = multipoint.normalize(clone=True) self.assertEqual(multipoint_2, normalized) self.assertNotEqual(multipoint, normalized) @skipIf(geos_version_tuple() < (3, 8), "GEOS >= 3.8.0 is required") def test_make_valid(self): poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") self.assertIs(poly.valid, False) valid_poly = poly.make_valid() self.assertIs(valid_poly.valid, True) self.assertNotEqual(valid_poly, poly) valid_poly2 = valid_poly.make_valid() self.assertIs(valid_poly2.valid, True) self.assertEqual(valid_poly, valid_poly2) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.7.3") def test_make_valid_geos_version(self): msg = "GEOSGeometry.make_valid() requires GEOS >= 3.8.0." poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") with self.assertRaisesMessage(GEOSException, msg): poly.make_valid() def test_empty_point(self): p = Point(srid=4326) self.assertEqual(p.ogr.ewkt, p.ewkt) self.assertEqual(p.transform(2774, clone=True), Point(srid=2774)) p.transform(2774) self.assertEqual(p, Point(srid=2774)) def test_linestring_iter(self): ls = LineString((0, 0), (1, 1)) it = iter(ls) # Step into CoordSeq iterator. next(it) ls[:] = [] with self.assertRaises(IndexError): next(it)
ec8dec2ea5b10d051e4cce24d6b13b3e855ffbbfd16cb8d9a5b93c6ce5401b0b
from unittest import skipIf from django.contrib.gis.gdal import ( GDAL_VERSION, AxisOrder, CoordTransform, GDALException, SpatialReference, SRSException, ) from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase class TestSRS: def __init__(self, wkt, **kwargs): self.wkt = wkt for key, value in kwargs.items(): setattr(self, key, value) # Some Spatial Reference examples srlist = ( TestSRS( 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,' 'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",' '0.0174532925199433,AUTHORITY["EPSG","9122"]],AXIS["Latitude",NORTH],' 'AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]', epsg=4326, projected=False, geographic=True, local=False, lin_name="unknown", ang_name="degree", lin_units=1.0, ang_units=0.0174532925199, auth={"GEOGCS": ("EPSG", "4326"), "spheroid": ("EPSG", "7030")}, attr=( ("DATUM", "WGS_1984"), (("SPHEROID", 1), "6378137"), ("primem|authority", "EPSG"), ), ), TestSRS( 'PROJCS["NAD83 / Texas South Central",' 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["standard_parallel_1",30.2833333333333],' 'PARAMETER["standard_parallel_2",28.3833333333333],' 'PARAMETER["latitude_of_origin",27.8333333333333],' 'PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],' 'PARAMETER["false_northing",4000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],' 'AXIS["Easting",EAST],AXIS["Northing",NORTH],AUTHORITY["EPSG","32140"]]', epsg=32140, projected=True, geographic=False, local=False, lin_name="metre", ang_name="degree", lin_units=1.0, ang_units=0.0174532925199, auth={ "PROJCS": ("EPSG", "32140"), "spheroid": ("EPSG", "7019"), "unit": ("EPSG", "9001"), }, attr=( ("DATUM", "North_American_Datum_1983"), (("SPHEROID", 2), "298.257222101"), ("PROJECTION", "Lambert_Conformal_Conic_2SP"), ), ), TestSRS( 'PROJCS["NAD83 / Texas South Central (ftUS)",' 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],' 'PRIMEM["Greenwich",0],' 'UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["false_easting",1968500],' 'PARAMETER["false_northing",13123333.3333333],' 'PARAMETER["central_meridian",-99],' 'PARAMETER["standard_parallel_1",28.3833333333333],' 'PARAMETER["standard_parallel_2",30.2833333333333],' 'PARAMETER["latitude_of_origin",27.8333333333333],' 'UNIT["US survey foot",0.304800609601219],AXIS["Easting",EAST],' 'AXIS["Northing",NORTH]]', epsg=None, projected=True, geographic=False, local=False, lin_name="US survey foot", ang_name="Degree", lin_units=0.3048006096012192, ang_units=0.0174532925199, auth={"PROJCS": (None, None)}, attr=( ("PROJCS|GeOgCs|spheroid", "GRS 1980"), (("projcs", 9), "UNIT"), (("projcs", 11), "AXIS"), ), ), # This is really ESRI format, not WKT -- but the import should work the same TestSRS( 'LOCAL_CS["Non-Earth (Meter)",LOCAL_DATUM["Local Datum",32767],' 'UNIT["Meter",1],AXIS["X",EAST],AXIS["Y",NORTH]]', esri=True, epsg=None, projected=False, geographic=False, local=True, lin_name="Meter", ang_name="degree", lin_units=1.0, ang_units=0.0174532925199, attr=(("LOCAL_DATUM", "Local Datum"),), ), ) # Well-Known Names well_known = ( TestSRS( 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,' 'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,' 'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]', wk="WGS84", name="WGS 84", attrs=(("GEOGCS|AUTHORITY", 1, "4326"), ("SPHEROID", "WGS 84")), ), TestSRS( 'GEOGCS["WGS 72",DATUM["WGS_1972",SPHEROID["WGS 72",6378135,298.26,' 'AUTHORITY["EPSG","7043"]],AUTHORITY["EPSG","6322"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4322"]]', wk="WGS72", name="WGS 72", attrs=(("GEOGCS|AUTHORITY", 1, "4322"), ("SPHEROID", "WGS 72")), ), TestSRS( 'GEOGCS["NAD27",DATUM["North_American_Datum_1927",' 'SPHEROID["Clarke 1866",6378206.4,294.9786982138982,' 'AUTHORITY["EPSG","7008"]],AUTHORITY["EPSG","6267"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4267"]]', wk="NAD27", name="NAD27", attrs=(("GEOGCS|AUTHORITY", 1, "4267"), ("SPHEROID", "Clarke 1866")), ), TestSRS( 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,' 'AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]]', wk="NAD83", name="NAD83", attrs=(("GEOGCS|AUTHORITY", 1, "4269"), ("SPHEROID", "GRS 1980")), ), TestSRS( 'PROJCS["NZGD49 / Karamea Circuit",GEOGCS["NZGD49",' 'DATUM["New_Zealand_Geodetic_Datum_1949",' 'SPHEROID["International 1924",6378388,297,' 'AUTHORITY["EPSG","7022"]],' "TOWGS84[59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993]," 'AUTHORITY["EPSG","6272"]],PRIMEM["Greenwich",0,' 'AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,' 'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4272"]],' 'PROJECTION["Transverse_Mercator"],' 'PARAMETER["latitude_of_origin",-41.28991152777778],' 'PARAMETER["central_meridian",172.1090281944444],' 'PARAMETER["scale_factor",1],PARAMETER["false_easting",300000],' 'PARAMETER["false_northing",700000],' 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","27216"]]', wk="EPSG:27216", name="NZGD49 / Karamea Circuit", attrs=( ("PROJECTION", "Transverse_Mercator"), ("SPHEROID", "International 1924"), ), ), ) bad_srlist = ( "Foobar", 'OOJCS["NAD83 / Texas South Central",GEOGCS["NAD83",' 'DATUM["North_American_Datum_1983",' 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],' 'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4269"]],PROJECTION["Lambert_Conformal_Conic_2SP"],' 'PARAMETER["standard_parallel_1",30.28333333333333],' 'PARAMETER["standard_parallel_2",28.38333333333333],' 'PARAMETER["latitude_of_origin",27.83333333333333],' 'PARAMETER["central_meridian",-99],PARAMETER["false_easting",600000],' 'PARAMETER["false_northing",4000000],UNIT["metre",1,' 'AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32140"]]', ) class SpatialRefTest(SimpleTestCase): def test01_wkt(self): "Testing initialization on valid OGC WKT." for s in srlist: SpatialReference(s.wkt) def test02_bad_wkt(self): "Testing initialization on invalid WKT." for bad in bad_srlist: try: srs = SpatialReference(bad) srs.validate() except (SRSException, GDALException): pass else: self.fail('Should not have initialized on bad WKT "%s"!') def test03_get_wkt(self): "Testing getting the WKT." for s in srlist: srs = SpatialReference(s.wkt) # GDAL 3 strips UNIT part in the last occurrence. self.assertEqual( s.wkt.replace(',UNIT["Meter",1]', ""), srs.wkt.replace(',UNIT["Meter",1]', ""), ) def test04_proj(self): """PROJ import and export.""" proj_parts = [ "+proj=longlat", "+ellps=WGS84", "+towgs84=0,0,0,0,0,0,0", "+datum=WGS84", "+no_defs", ] srs1 = SpatialReference(srlist[0].wkt) srs2 = SpatialReference("+proj=longlat +datum=WGS84 +no_defs") self.assertTrue(all(part in proj_parts for part in srs1.proj.split())) self.assertTrue(all(part in proj_parts for part in srs2.proj.split())) def test05_epsg(self): "Test EPSG import." for s in srlist: if s.epsg: srs1 = SpatialReference(s.wkt) srs2 = SpatialReference(s.epsg) srs3 = SpatialReference(str(s.epsg)) srs4 = SpatialReference("EPSG:%d" % s.epsg) for srs in (srs1, srs2, srs3, srs4): for attr, expected in s.attr: self.assertEqual(expected, srs[attr]) def test07_boolean_props(self): "Testing the boolean properties." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.projected, srs.projected) self.assertEqual(s.geographic, srs.geographic) def test08_angular_linear(self): "Testing the linear and angular units routines." for s in srlist: srs = SpatialReference(s.wkt) self.assertEqual(s.ang_name, srs.angular_name) self.assertEqual(s.lin_name, srs.linear_name) self.assertAlmostEqual(s.ang_units, srs.angular_units, 9) self.assertAlmostEqual(s.lin_units, srs.linear_units, 9) def test09_authority(self): "Testing the authority name & code routines." for s in srlist: if hasattr(s, "auth"): srs = SpatialReference(s.wkt) for target, tup in s.auth.items(): self.assertEqual(tup[0], srs.auth_name(target)) self.assertEqual(tup[1], srs.auth_code(target)) def test10_attributes(self): "Testing the attribute retrieval routines." for s in srlist: srs = SpatialReference(s.wkt) for tup in s.attr: att = tup[0] # Attribute to test exp = tup[1] # Expected result self.assertEqual(exp, srs[att]) def test11_wellknown(self): "Testing Well Known Names of Spatial References." for s in well_known: srs = SpatialReference(s.wk) self.assertEqual(s.name, srs.name) for tup in s.attrs: if len(tup) == 2: key = tup[0] exp = tup[1] elif len(tup) == 3: key = tup[:2] exp = tup[2] self.assertEqual(srs[key], exp) def test12_coordtransform(self): "Testing initialization of a CoordTransform." target = SpatialReference("WGS84") CoordTransform(SpatialReference(srlist[0].wkt), target) def test13_attr_value(self): "Testing the attr_value() method." s1 = SpatialReference("WGS84") with self.assertRaises(TypeError): s1.__getitem__(0) with self.assertRaises(TypeError): s1.__getitem__(("GEOGCS", "foo")) self.assertEqual("WGS 84", s1["GEOGCS"]) self.assertEqual("WGS_1984", s1["DATUM"]) self.assertEqual("EPSG", s1["AUTHORITY"]) self.assertEqual(4326, int(s1["AUTHORITY", 1])) self.assertIsNone(s1["FOOBAR"]) def test_unicode(self): wkt = ( 'PROJCS["DHDN / Soldner 39 Langschoß",' 'GEOGCS["DHDN",DATUM["Deutsches_Hauptdreiecksnetz",' 'SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],' 'AUTHORITY["EPSG","6314"]],' 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],' 'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],' 'AUTHORITY["EPSG","4314"]],PROJECTION["Cassini_Soldner"],' 'PARAMETER["latitude_of_origin",50.66738711],' 'PARAMETER["central_meridian",6.28935703],' 'PARAMETER["false_easting",0],PARAMETER["false_northing",0],' 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",NORTH],AXIS["Y",EAST],' 'AUTHORITY["mj10777.de","187939"]]' ) srs = SpatialReference(wkt) srs_list = [srs, srs.clone()] srs.import_wkt(wkt) for srs in srs_list: self.assertEqual(srs.name, "DHDN / Soldner 39 Langschoß") self.assertEqual(srs.wkt, wkt) self.assertIn("Langschoß", srs.pretty_wkt) self.assertIn("Langschoß", srs.xml) @skipIf(GDAL_VERSION < (3, 0), "GDAL >= 3.0 is required") def test_axis_order(self): wgs84_trad = SpatialReference(4326, axis_order=AxisOrder.TRADITIONAL) wgs84_auth = SpatialReference(4326, axis_order=AxisOrder.AUTHORITY) # Coordinate interpretation may depend on the srs axis predicate. pt = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) pt_trad = pt.transform(wgs84_trad, clone=True) self.assertAlmostEqual(pt_trad.x, -104.609, 3) self.assertAlmostEqual(pt_trad.y, 38.255, 3) pt_auth = pt.transform(wgs84_auth, clone=True) self.assertAlmostEqual(pt_auth.x, 38.255, 3) self.assertAlmostEqual(pt_auth.y, -104.609, 3) # clone() preserves the axis order. pt_auth = pt.transform(wgs84_auth.clone(), clone=True) self.assertAlmostEqual(pt_auth.x, 38.255, 3) self.assertAlmostEqual(pt_auth.y, -104.609, 3) def test_axis_order_invalid(self): msg = "SpatialReference.axis_order must be an AxisOrder instance." with self.assertRaisesMessage(ValueError, msg): SpatialReference(4326, axis_order="other") @skipIf(GDAL_VERSION > (3, 0), "GDAL < 3.0 doesn't support authority.") def test_axis_order_non_traditional_invalid(self): msg = "AxisOrder.AUTHORITY is not supported in GDAL < 3.0." with self.assertRaisesMessage(ValueError, msg): SpatialReference(4326, axis_order=AxisOrder.AUTHORITY) def test_esri(self): srs = SpatialReference("NAD83") pre_esri_wkt = srs.wkt srs.to_esri() self.assertNotEqual(srs.wkt, pre_esri_wkt) self.assertIn('DATUM["D_North_American_1983"', srs.wkt) srs.from_esri() self.assertIn('DATUM["North_American_Datum_1983"', srs.wkt)
ee447788a8e6ebd96d73d6d6b0c87620bf3de6b27415d3599a1776a401f2b1a2
from django.contrib.gis.db import models from django.db import migrations from django.db.models import deletion class Migration(migrations.Migration): dependencies = [ ("rasterapp", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="RasterModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "rast", models.fields.RasterField( blank=True, null=True, srid=4326, verbose_name="A Verbose Raster Name", ), ), ( "rastprojected", models.fields.RasterField( null=True, srid=3086, verbose_name="A Projected Raster Table", ), ), ("geom", models.fields.PointField(null=True, srid=4326)), ], options={ "required_db_features": ["supports_raster"], }, ), migrations.CreateModel( name="RasterRelatedModel", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "rastermodel", models.ForeignKey( on_delete=deletion.CASCADE, to="rasterapp.rastermodel", ), ), ], options={ "required_db_features": ["supports_raster"], }, ), ]
d49000b7a5255f3da254afe08c878d59edf7d668e9a231ef91db5a180b3af8db
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("sites", "0001_initial"), ] operations = [ migrations.CreateModel( name="CustomArticle", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=50)), ( "places_this_article_should_appear", models.ForeignKey("sites.Site", models.CASCADE), ), ], options={ "abstract": False, }, bases=(models.Model,), ), migrations.CreateModel( name="ExclusiveArticle", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=50)), ("site", models.ForeignKey("sites.Site", models.CASCADE)), ], options={ "abstract": False, }, bases=(models.Model,), ), migrations.CreateModel( name="SyndicatedArticle", fields=[ ( "id", models.AutoField( verbose_name="ID", serialize=False, auto_created=True, primary_key=True, ), ), ("title", models.CharField(max_length=50)), ("sites", models.ManyToManyField("sites.Site")), ], options={ "abstract": False, }, bases=(models.Model,), ), ]
907f13d3b288b51e142247e5a91d7fa8d62a5736335a7058635bbc1f34f329c3
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("db_functions", "0001_setup_extensions"), ] operations = [ migrations.CreateModel( name="Author", fields=[ ("name", models.CharField(max_length=50)), ("alias", models.CharField(max_length=50, null=True, blank=True)), ("goes_by", models.CharField(max_length=50, null=True, blank=True)), ("age", models.PositiveSmallIntegerField(default=30)), ], ), migrations.CreateModel( name="Article", fields=[ ( "authors", models.ManyToManyField( "db_functions.Author", related_name="articles" ), ), ("title", models.CharField(max_length=50)), ("summary", models.CharField(max_length=200, null=True, blank=True)), ("text", models.TextField()), ("written", models.DateTimeField()), ("published", models.DateTimeField(null=True, blank=True)), ("updated", models.DateTimeField(null=True, blank=True)), ("views", models.PositiveIntegerField(default=0)), ], ), migrations.CreateModel( name="Fan", fields=[ ("name", models.CharField(max_length=50)), ("age", models.PositiveSmallIntegerField(default=30)), ( "author", models.ForeignKey( "db_functions.Author", models.CASCADE, related_name="fans" ), ), ("fan_since", models.DateTimeField(null=True, blank=True)), ], ), migrations.CreateModel( name="DTModel", fields=[ ("name", models.CharField(max_length=32)), ("start_datetime", models.DateTimeField(null=True, blank=True)), ("end_datetime", models.DateTimeField(null=True, blank=True)), ("start_date", models.DateField(null=True, blank=True)), ("end_date", models.DateField(null=True, blank=True)), ("start_time", models.TimeField(null=True, blank=True)), ("end_time", models.TimeField(null=True, blank=True)), ("duration", models.DurationField(null=True, blank=True)), ], ), migrations.CreateModel( name="DecimalModel", fields=[ ("n1", models.DecimalField(decimal_places=2, max_digits=6)), ( "n2", models.DecimalField( decimal_places=7, max_digits=9, null=True, blank=True ), ), ], ), migrations.CreateModel( name="IntegerModel", fields=[ ("big", models.BigIntegerField(null=True, blank=True)), ("normal", models.IntegerField(null=True, blank=True)), ("small", models.SmallIntegerField(null=True, blank=True)), ], ), migrations.CreateModel( name="FloatModel", fields=[ ("f1", models.FloatField(null=True, blank=True)), ("f2", models.FloatField(null=True, blank=True)), ], ), ]
044a80e4b60ad9b77d0e3e96e7c69a509df015c944cca640eac393478402c94d
import zoneinfo from datetime import datetime, timedelta from datetime import timezone as datetime_timezone from django.conf import settings from django.db import DataError, OperationalError from django.db.models import ( DateField, DateTimeField, F, IntegerField, Max, OuterRef, Subquery, TimeField, ) from django.db.models.functions import ( Extract, ExtractDay, ExtractHour, ExtractIsoWeekDay, ExtractIsoYear, ExtractMinute, ExtractMonth, ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay, ExtractYear, Trunc, TruncDate, TruncDay, TruncHour, TruncMinute, TruncMonth, TruncQuarter, TruncSecond, TruncTime, TruncWeek, TruncYear, ) from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.utils import timezone from ..models import Author, DTModel, Fan def truncate_to(value, kind, tzinfo=None): # Convert to target timezone before truncation if tzinfo is not None: value = value.astimezone(tzinfo) def truncate(value, kind): if kind == "second": return value.replace(microsecond=0) if kind == "minute": return value.replace(second=0, microsecond=0) if kind == "hour": return value.replace(minute=0, second=0, microsecond=0) if kind == "day": if isinstance(value, datetime): return value.replace(hour=0, minute=0, second=0, microsecond=0) return value if kind == "week": if isinstance(value, datetime): return (value - timedelta(days=value.weekday())).replace( hour=0, minute=0, second=0, microsecond=0 ) return value - timedelta(days=value.weekday()) if kind == "month": if isinstance(value, datetime): return value.replace(day=1, hour=0, minute=0, second=0, microsecond=0) return value.replace(day=1) if kind == "quarter": month_in_quarter = value.month - (value.month - 1) % 3 if isinstance(value, datetime): return value.replace( month=month_in_quarter, day=1, hour=0, minute=0, second=0, microsecond=0, ) return value.replace(month=month_in_quarter, day=1) # otherwise, truncate to year if isinstance(value, datetime): return value.replace( month=1, day=1, hour=0, minute=0, second=0, microsecond=0 ) return value.replace(month=1, day=1) value = truncate(value, kind) if tzinfo is not None: # If there was a daylight saving transition, then reset the timezone. value = timezone.make_aware(value.replace(tzinfo=None), tzinfo) return value @override_settings(USE_TZ=False) class DateFunctionTests(TestCase): def create_model(self, start_datetime, end_datetime): return DTModel.objects.create( name=start_datetime.isoformat() if start_datetime else "None", start_datetime=start_datetime, end_datetime=end_datetime, start_date=start_datetime.date() if start_datetime else None, end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, duration=(end_datetime - start_datetime) if start_datetime and end_datetime else None, ) def test_extract_year_exact_lookup(self): """ Extract year uses a BETWEEN filter to compare the year to allow indexes to be used. """ start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter( **{"start_datetime__%s__exact" % lookup: 2015} ) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # exact is implied and should be the same qs = DTModel.objects.filter(**{"start_datetime__%s" % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # date and datetime fields should behave the same qs = DTModel.objects.filter(**{"start_date__%s" % lookup: 2015}) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 1) self.assertEqual(query_string.count("extract"), 0) # an expression rhs cannot use the between optimization. qs = DTModel.objects.annotate( start_year=ExtractYear("start_datetime"), ).filter(end_datetime__year=F("start_year") + 1) self.assertEqual(qs.count(), 1) query_string = str(qs.query).lower() self.assertEqual(query_string.count(" between "), 0) self.assertEqual(query_string.count("extract"), 3) def test_extract_year_greaterthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter(**{"start_datetime__%s__gt" % lookup: 2015}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).lower().count("extract"), 0) qs = DTModel.objects.filter( **{"start_datetime__%s__gte" % lookup: 2015} ) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).lower().count("extract"), 0) qs = DTModel.objects.annotate( start_year=ExtractYear("start_datetime"), ).filter(**{"end_datetime__%s__gte" % lookup: F("start_year")}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_year_lessthan_lookup(self): start_datetime = datetime(2015, 6, 15, 14, 10) end_datetime = datetime(2016, 6, 15, 14, 10) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) for lookup in ("year", "iso_year"): with self.subTest(lookup): qs = DTModel.objects.filter(**{"start_datetime__%s__lt" % lookup: 2016}) self.assertEqual(qs.count(), 1) self.assertEqual(str(qs.query).count("extract"), 0) qs = DTModel.objects.filter( **{"start_datetime__%s__lte" % lookup: 2016} ) self.assertEqual(qs.count(), 2) self.assertEqual(str(qs.query).count("extract"), 0) qs = DTModel.objects.annotate( end_year=ExtractYear("end_datetime"), ).filter(**{"start_datetime__%s__lte" % lookup: F("end_year")}) self.assertEqual(qs.count(), 1) self.assertGreaterEqual(str(qs.query).lower().count("extract"), 2) def test_extract_lookup_name_sql_injection(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaises((OperationalError, ValueError)): DTModel.objects.filter( start_datetime__year=Extract( "start_datetime", "day' FROM start_datetime)) OR 1=1;--" ) ).exists() def test_extract_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) with self.assertRaisesMessage(ValueError, "lookup_name must be provided"): Extract("start_datetime") msg = ( "Extract input expression must be DateField, DateTimeField, TimeField, or " "DurationField." ) with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract("name", "hour"))) with self.assertRaisesMessage( ValueError, "Cannot extract time component 'second' from DateField 'start_date'.", ): list(DTModel.objects.annotate(extracted=Extract("start_date", "second"))) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "year") ).order_by("start_datetime"), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "quarter") ).order_by("start_datetime"), [(start_datetime, 2), (end_datetime, 2)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "month") ).order_by("start_datetime"), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "day") ).order_by("start_datetime"), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "week") ).order_by("start_datetime"), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "week_day") ).order_by("start_datetime"), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "iso_week_day"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "hour") ).order_by("start_datetime"), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "minute") ).order_by("start_datetime"), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=Extract("start_datetime", "second") ).order_by("start_datetime"), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__year=Extract("start_datetime", "year") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_datetime__hour=Extract("start_datetime", "hour") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_date__month=Extract("start_date", "month") ).count(), 2, ) self.assertEqual( DTModel.objects.filter( start_time__hour=Extract("start_time", "hour") ).count(), 2, ) def test_extract_none(self): self.create_model(None, None) for t in ( Extract("start_datetime", "year"), Extract("start_date", "year"), Extract("start_time", "hour"), ): with self.subTest(t): self.assertIsNone( DTModel.objects.annotate(extracted=t).first().extracted ) def test_extract_outerref_validation(self): inner_qs = DTModel.objects.filter(name=ExtractMonth(OuterRef("name"))) msg = ( "Extract input expression must be DateField, DateTimeField, " "TimeField, or DurationField." ) with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate(related_name=Subquery(inner_qs.values("name")[:1])) @skipUnlessDBFeature("has_native_duration_field") def test_extract_duration(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=Extract("duration", "second")).order_by( "start_datetime" ), [ (start_datetime, (end_datetime - start_datetime).seconds % 60), (end_datetime, (start_datetime - end_datetime).seconds % 60), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.annotate( duration_days=Extract("duration", "day"), ) .filter(duration_days__gt=200) .count(), 1, ) @skipIfDBFeature("has_native_duration_field") def test_extract_duration_without_native_duration_field(self): msg = "Extract requires native DurationField database support." with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(extracted=Extract("duration", "second"))) def test_extract_duration_unsupported_lookups(self): msg = "Cannot extract component '%s' from DurationField 'duration'." for lookup in ( "year", "iso_year", "month", "week", "week_day", "iso_week_day", "quarter", ): with self.subTest(lookup): with self.assertRaisesMessage(ValueError, msg % lookup): DTModel.objects.annotate(extracted=Extract("duration", lookup)) def test_extract_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractYear("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractYear("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__year=ExtractYear("start_datetime") ).count(), 2, ) def test_extract_iso_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractIsoYear("start_datetime") ).order_by("start_datetime"), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractIsoYear("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)], lambda m: (m.start_datetime, m.extracted), ) # Both dates are from the same week year. self.assertEqual( DTModel.objects.filter( start_datetime__iso_year=ExtractIsoYear("start_datetime") ).count(), 2, ) def test_extract_iso_year_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015) week_52_day_2014 = timezone.make_aware(week_52_day_2014) week_53_day_2015 = timezone.make_aware(week_53_day_2015) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] obj_1_iso_2014 = self.create_model(week_52_day_2014, end_datetime) obj_1_iso_2015 = self.create_model(week_1_day_2014_2015, end_datetime) obj_2_iso_2015 = self.create_model(week_53_day_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=days) .annotate( extracted=ExtractIsoYear("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerySetEqual( qs, [ (week_52_day_2014, 2014), (week_1_day_2014_2015, 2015), (week_53_day_2015, 2015), ], lambda m: (m.start_datetime, m.extracted), ) qs = DTModel.objects.filter( start_datetime__iso_year=2015, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015]) qs = DTModel.objects.filter( start_datetime__iso_year__gt=2014, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2015, obj_2_iso_2015]) qs = DTModel.objects.filter( start_datetime__iso_year__lte=2014, ).order_by("start_datetime") self.assertSequenceEqual(qs, [obj_1_iso_2014]) def test_extract_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractMonth("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractMonth("start_date")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.month), (end_datetime, end_datetime.month), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__month=ExtractMonth("start_datetime") ).count(), 2, ) def test_extract_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractDay("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractDay("start_date")).order_by( "start_datetime" ), [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__day=ExtractDay("start_datetime") ).count(), 2, ) def test_extract_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractWeek("start_datetime")).order_by( "start_datetime" ), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractWeek("start_date")).order_by( "start_datetime" ), [(start_datetime, 25), (end_datetime, 24)], lambda m: (m.start_datetime, m.extracted), ) # both dates are from the same week. self.assertEqual( DTModel.objects.filter( start_datetime__week=ExtractWeek("start_datetime") ).count(), 2, ) def test_extract_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 8, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractQuarter("start_datetime") ).order_by("start_datetime"), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractQuarter("start_date")).order_by( "start_datetime" ), [(start_datetime, 2), (end_datetime, 3)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__quarter=ExtractQuarter("start_datetime") ).count(), 2, ) def test_extract_quarter_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) last_quarter_2014 = datetime(2014, 12, 31, 13, 0) first_quarter_2015 = datetime(2015, 1, 1, 13, 0) if settings.USE_TZ: last_quarter_2014 = timezone.make_aware(last_quarter_2014) first_quarter_2015 = timezone.make_aware(first_quarter_2015) dates = [last_quarter_2014, first_quarter_2015] self.create_model(last_quarter_2014, end_datetime) self.create_model(first_quarter_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=dates) .annotate( extracted=ExtractQuarter("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerySetEqual( qs, [ (last_quarter_2014, 4), (first_quarter_2015, 1), ], lambda m: (m.start_datetime, m.extracted), ) def test_extract_week_func_boundaries(self): end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: end_datetime = timezone.make_aware(end_datetime) week_52_day_2014 = datetime(2014, 12, 27, 13, 0) # Sunday week_1_day_2014_2015 = datetime(2014, 12, 31, 13, 0) # Wednesday week_53_day_2015 = datetime(2015, 12, 31, 13, 0) # Thursday if settings.USE_TZ: week_1_day_2014_2015 = timezone.make_aware(week_1_day_2014_2015) week_52_day_2014 = timezone.make_aware(week_52_day_2014) week_53_day_2015 = timezone.make_aware(week_53_day_2015) days = [week_52_day_2014, week_1_day_2014_2015, week_53_day_2015] self.create_model(week_53_day_2015, end_datetime) self.create_model(week_52_day_2014, end_datetime) self.create_model(week_1_day_2014_2015, end_datetime) qs = ( DTModel.objects.filter(start_datetime__in=days) .annotate( extracted=ExtractWeek("start_datetime"), ) .order_by("start_datetime") ) self.assertQuerySetEqual( qs, [ (week_52_day_2014, 52), (week_1_day_2014_2015, 1), (week_53_day_2015, 53), ], lambda m: (m.start_datetime, m.extracted), ) def test_extract_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractWeekDay("start_datetime") ).order_by("start_datetime"), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractWeekDay("start_date")).order_by( "start_datetime" ), [ (start_datetime, (start_datetime.isoweekday() % 7) + 1), (end_datetime, (end_datetime.isoweekday() % 7) + 1), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay("start_datetime") ).count(), 2, ) def test_extract_iso_weekday_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay("start_datetime"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractIsoWeekDay("start_date"), ).order_by("start_datetime"), [ (start_datetime, start_datetime.isoweekday()), (end_datetime, end_datetime.isoweekday()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__week_day=ExtractWeekDay("start_datetime"), ).count(), 2, ) def test_extract_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractHour("start_datetime")).order_by( "start_datetime" ), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractHour("start_time")).order_by( "start_datetime" ), [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__hour=ExtractHour("start_datetime") ).count(), 2, ) def test_extract_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractMinute("start_datetime") ).order_by("start_datetime"), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractMinute("start_time")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__minute=ExtractMinute("start_datetime") ).count(), 2, ) def test_extract_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( extracted=ExtractSecond("start_datetime") ).order_by("start_datetime"), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=ExtractSecond("start_time")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.second), (end_datetime, end_datetime.second), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__second=ExtractSecond("start_datetime") ).count(), 2, ) def test_extract_second_func_no_fractional(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 30, 50, 783) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) obj = self.create_model(start_datetime, end_datetime) self.assertSequenceEqual( DTModel.objects.filter(start_datetime__second=F("end_datetime__second")), [obj], ) self.assertSequenceEqual( DTModel.objects.filter(start_time__second=F("end_time__second")), [obj], ) def test_trunc_lookup_name_sql_injection(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) # Database backends raise an exception or don't return any results. try: exists = DTModel.objects.filter( start_datetime__date=Trunc( "start_datetime", "year', start_datetime)) OR 1=1;--", ) ).exists() except (DataError, OperationalError): pass else: self.assertIs(exists, False) def test_trunc_func(self): start_datetime = datetime(999, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) def test_datetime_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=DateTimeField() ) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime, kind)), (end_datetime, truncate_to(end_datetime, kind)), ], lambda m: (m.start_datetime, m.truncated), ) def test_date_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc("start_date", kind, output_field=DateField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.date(), kind)), (end_datetime, truncate_to(end_datetime.date(), kind)), ], lambda m: (m.start_datetime, m.truncated), ) def test_time_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc("start_time", kind, output_field=TimeField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)), ], lambda m: (m.start_datetime, m.truncated), ) def test_datetime_to_time_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc("start_datetime", kind, output_field=TimeField()), ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.time(), kind)), (end_datetime, truncate_to(end_datetime.time(), kind)), ], lambda m: (m.start_datetime, m.truncated), ) test_date_kind("year") test_date_kind("quarter") test_date_kind("month") test_date_kind("day") test_time_kind("hour") test_time_kind("minute") test_time_kind("second") test_datetime_kind("year") test_datetime_kind("quarter") test_datetime_kind("month") test_datetime_kind("day") test_datetime_kind("hour") test_datetime_kind("minute") test_datetime_kind("second") test_datetime_to_time_kind("hour") test_datetime_to_time_kind("minute") test_datetime_to_time_kind("second") qs = DTModel.objects.filter( start_datetime__date=Trunc( "start_datetime", "day", output_field=DateField() ) ) self.assertEqual(qs.count(), 2) def _test_trunc_week(self, start_datetime, end_datetime): if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc("start_datetime", "week", output_field=DateTimeField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime, "week")), (end_datetime, truncate_to(end_datetime, "week")), ], lambda m: (m.start_datetime, m.truncated), ) self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc("start_date", "week", output_field=DateField()) ).order_by("start_datetime"), [ (start_datetime, truncate_to(start_datetime.date(), "week")), (end_datetime, truncate_to(end_datetime.date(), "week")), ], lambda m: (m.start_datetime, m.truncated), ) def test_trunc_week(self): self._test_trunc_week( start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321), end_datetime=datetime(2016, 6, 15, 14, 10, 50, 123), ) def test_trunc_week_before_1000(self): self._test_trunc_week( start_datetime=datetime(999, 6, 15, 14, 30, 50, 321), end_datetime=datetime(2016, 6, 15, 14, 10, 50, 123), ) def test_trunc_invalid_arguments(self): msg = "output_field must be either DateField, TimeField, or DateTimeField" with self.assertRaisesMessage(ValueError, msg): list( DTModel.objects.annotate( truncated=Trunc( "start_datetime", "year", output_field=IntegerField() ), ) ) msg = "'name' isn't a DateField, TimeField, or DateTimeField." with self.assertRaisesMessage(TypeError, msg): list( DTModel.objects.annotate( truncated=Trunc("name", "year", output_field=DateTimeField()), ) ) msg = "Cannot truncate DateField 'start_date' to DateTimeField" with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(truncated=Trunc("start_date", "second"))) with self.assertRaisesMessage(ValueError, msg): list( DTModel.objects.annotate( truncated=Trunc( "start_date", "month", output_field=DateTimeField() ), ) ) msg = "Cannot truncate TimeField 'start_time' to DateTimeField" with self.assertRaisesMessage(ValueError, msg): list(DTModel.objects.annotate(truncated=Trunc("start_time", "month"))) with self.assertRaisesMessage(ValueError, msg): list( DTModel.objects.annotate( truncated=Trunc( "start_time", "second", output_field=DateTimeField() ), ) ) def test_trunc_none(self): self.create_model(None, None) for t in ( Trunc("start_datetime", "year"), Trunc("start_date", "year"), Trunc("start_time", "hour"), ): with self.subTest(t): self.assertIsNone( DTModel.objects.annotate(truncated=t).first().truncated ) def test_trunc_year_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "year") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncYear("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "year")), (end_datetime, truncate_to(end_datetime, "year")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncYear("start_date")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.date(), "year")), (end_datetime, truncate_to(end_datetime.date(), "year")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncYear("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncYear("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncYear("start_time", output_field=TimeField()) ) ) def test_trunc_quarter_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 10, 15, 14, 10, 50, 123), "quarter") last_quarter_2015 = truncate_to( datetime(2015, 12, 31, 14, 10, 50, 123), "quarter" ) first_quarter_2016 = truncate_to( datetime(2016, 1, 1, 14, 10, 50, 123), "quarter" ) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) last_quarter_2015 = timezone.make_aware(last_quarter_2015) first_quarter_2016 = timezone.make_aware(first_quarter_2016) self.create_model(start_datetime=start_datetime, end_datetime=end_datetime) self.create_model(start_datetime=end_datetime, end_datetime=start_datetime) self.create_model(start_datetime=last_quarter_2015, end_datetime=end_datetime) self.create_model(start_datetime=first_quarter_2016, end_datetime=end_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncQuarter("start_date")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.date(), "quarter")), (last_quarter_2015, truncate_to(last_quarter_2015.date(), "quarter")), (first_quarter_2016, truncate_to(first_quarter_2016.date(), "quarter")), (end_datetime, truncate_to(end_datetime.date(), "quarter")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncQuarter("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "quarter")), (last_quarter_2015, truncate_to(last_quarter_2015, "quarter")), (first_quarter_2016, truncate_to(first_quarter_2016, "quarter")), (end_datetime, truncate_to(end_datetime, "quarter")), ], lambda m: (m.start_datetime, m.extracted), ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncQuarter("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncQuarter("start_time", output_field=TimeField()) ) ) def test_trunc_month_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "month") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncMonth("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "month")), (end_datetime, truncate_to(end_datetime, "month")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncMonth("start_date")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.date(), "month")), (end_datetime, truncate_to(end_datetime.date(), "month")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncMonth("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncMonth("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncMonth("start_time", output_field=TimeField()) ) ) def test_trunc_week_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "week") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncWeek("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "week")), (end_datetime, truncate_to(end_datetime, "week")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncWeek("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncWeek("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncWeek("start_time", output_field=TimeField()) ) ) def test_trunc_date_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncDate("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.date()), (end_datetime, end_datetime.date()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__date=TruncDate("start_datetime") ).count(), 2, ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateField" ): list(DTModel.objects.annotate(truncated=TruncDate("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateField" ): list( DTModel.objects.annotate( truncated=TruncDate("start_time", output_field=TimeField()) ) ) def test_trunc_date_none(self): self.create_model(None, None) self.assertIsNone( DTModel.objects.annotate(truncated=TruncDate("start_datetime")) .first() .truncated ) def test_trunc_time_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncTime("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, start_datetime.time()), (end_datetime, end_datetime.time()), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime__time=TruncTime("start_datetime") ).count(), 2, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to TimeField" ): list(DTModel.objects.annotate(truncated=TruncTime("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to TimeField" ): list( DTModel.objects.annotate( truncated=TruncTime("start_date", output_field=DateField()) ) ) def test_trunc_time_none(self): self.create_model(None, None) self.assertIsNone( DTModel.objects.annotate(truncated=TruncTime("start_datetime")) .first() .truncated ) def test_trunc_time_comparison(self): start_datetime = datetime(2015, 6, 15, 14, 30, 26) # 0 microseconds. end_datetime = datetime(2015, 6, 15, 14, 30, 26, 321) if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.assertIs( DTModel.objects.filter( start_datetime__time=start_datetime.time(), end_datetime__time=end_datetime.time(), ).exists(), True, ) self.assertIs( DTModel.objects.annotate( extracted_start=TruncTime("start_datetime"), extracted_end=TruncTime("end_datetime"), ) .filter( extracted_start=start_datetime.time(), extracted_end=end_datetime.time(), ) .exists(), True, ) def test_trunc_day_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "day") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncDay("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "day")), (end_datetime, truncate_to(end_datetime, "day")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncDay("start_datetime")).count(), 1 ) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncDay("start_time"))) with self.assertRaisesMessage( ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncDay("start_time", output_field=TimeField()) ) ) def test_trunc_hour_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "hour") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncHour("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "hour")), (end_datetime, truncate_to(end_datetime, "hour")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncHour("start_time")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.time(), "hour")), (end_datetime, truncate_to(end_datetime.time(), "hour")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter(start_datetime=TruncHour("start_datetime")).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncHour("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncHour("start_date", output_field=DateField()) ) ) def test_trunc_minute_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "minute") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncMinute("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "minute")), (end_datetime, truncate_to(end_datetime, "minute")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncMinute("start_time")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.time(), "minute")), (end_datetime, truncate_to(end_datetime.time(), "minute")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime=TruncMinute("start_datetime") ).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncMinute("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncMinute("start_date", output_field=DateField()) ) ) def test_trunc_second_func(self): start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = truncate_to(datetime(2016, 6, 15, 14, 10, 50, 123), "second") if settings.USE_TZ: start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncSecond("start_datetime")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime, "second")), (end_datetime, truncate_to(end_datetime, "second")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertQuerySetEqual( DTModel.objects.annotate(extracted=TruncSecond("start_time")).order_by( "start_datetime" ), [ (start_datetime, truncate_to(start_datetime.time(), "second")), (end_datetime, truncate_to(end_datetime.time(), "second")), ], lambda m: (m.start_datetime, m.extracted), ) self.assertEqual( DTModel.objects.filter( start_datetime=TruncSecond("start_datetime") ).count(), 1, ) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list(DTModel.objects.annotate(truncated=TruncSecond("start_date"))) with self.assertRaisesMessage( ValueError, "Cannot truncate DateField 'start_date' to DateTimeField" ): list( DTModel.objects.annotate( truncated=TruncSecond("start_date", output_field=DateField()) ) ) def test_trunc_subquery_with_parameters(self): author_1 = Author.objects.create(name="J. R. R. Tolkien") author_2 = Author.objects.create(name="G. R. R. Martin") fan_since_1 = datetime(2016, 2, 3, 15, 0, 0) fan_since_2 = datetime(2015, 2, 3, 15, 0, 0) fan_since_3 = datetime(2017, 2, 3, 15, 0, 0) if settings.USE_TZ: fan_since_1 = timezone.make_aware(fan_since_1) fan_since_2 = timezone.make_aware(fan_since_2) fan_since_3 = timezone.make_aware(fan_since_3) Fan.objects.create(author=author_1, name="Tom", fan_since=fan_since_1) Fan.objects.create(author=author_1, name="Emma", fan_since=fan_since_2) Fan.objects.create(author=author_2, name="Isabella", fan_since=fan_since_3) inner = ( Fan.objects.filter( author=OuterRef("pk"), name__in=("Emma", "Isabella", "Tom") ) .values("author") .annotate(newest_fan=Max("fan_since")) .values("newest_fan") ) outer = Author.objects.annotate( newest_fan_year=TruncYear(Subquery(inner, output_field=DateTimeField())) ) tz = datetime_timezone.utc if settings.USE_TZ else None self.assertSequenceEqual( outer.order_by("name").values("name", "newest_fan_year"), [ { "name": "G. R. R. Martin", "newest_fan_year": datetime(2017, 1, 1, 0, 0, tzinfo=tz), }, { "name": "J. R. R. Tolkien", "newest_fan_year": datetime(2016, 1, 1, 0, 0, tzinfo=tz), }, ], ) def test_extract_outerref(self): datetime_1 = datetime(2000, 1, 1) datetime_2 = datetime(2001, 3, 5) datetime_3 = datetime(2002, 1, 3) if settings.USE_TZ: datetime_1 = timezone.make_aware(datetime_1) datetime_2 = timezone.make_aware(datetime_2) datetime_3 = timezone.make_aware(datetime_3) obj_1 = self.create_model(datetime_1, datetime_3) obj_2 = self.create_model(datetime_2, datetime_1) obj_3 = self.create_model(datetime_3, datetime_2) inner_qs = DTModel.objects.filter( start_datetime__year=2000, start_datetime__month=ExtractMonth(OuterRef("end_datetime")), ) qs = DTModel.objects.annotate( related_pk=Subquery(inner_qs.values("pk")[:1]), ) self.assertSequenceEqual( qs.order_by("name").values("pk", "related_pk"), [ {"pk": obj_1.pk, "related_pk": obj_1.pk}, {"pk": obj_2.pk, "related_pk": obj_1.pk}, {"pk": obj_3.pk, "related_pk": None}, ], ) @override_settings(USE_TZ=True, TIME_ZONE="UTC") class DateFunctionWithTimeZoneTests(DateFunctionTests): def test_extract_func_with_timezone(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) delta_tzinfo_pos = datetime_timezone(timedelta(hours=5)) delta_tzinfo_neg = datetime_timezone(timedelta(hours=-5, minutes=17)) melb = zoneinfo.ZoneInfo("Australia/Melbourne") qs = DTModel.objects.annotate( day=Extract("start_datetime", "day"), day_melb=Extract("start_datetime", "day", tzinfo=melb), week=Extract("start_datetime", "week", tzinfo=melb), isoyear=ExtractIsoYear("start_datetime", tzinfo=melb), weekday=ExtractWeekDay("start_datetime"), weekday_melb=ExtractWeekDay("start_datetime", tzinfo=melb), isoweekday=ExtractIsoWeekDay("start_datetime"), isoweekday_melb=ExtractIsoWeekDay("start_datetime", tzinfo=melb), quarter=ExtractQuarter("start_datetime", tzinfo=melb), hour=ExtractHour("start_datetime"), hour_melb=ExtractHour("start_datetime", tzinfo=melb), hour_with_delta_pos=ExtractHour("start_datetime", tzinfo=delta_tzinfo_pos), hour_with_delta_neg=ExtractHour("start_datetime", tzinfo=delta_tzinfo_neg), minute_with_delta_neg=ExtractMinute( "start_datetime", tzinfo=delta_tzinfo_neg ), ).order_by("start_datetime") utc_model = qs.get() self.assertEqual(utc_model.day, 15) self.assertEqual(utc_model.day_melb, 16) self.assertEqual(utc_model.week, 25) self.assertEqual(utc_model.isoyear, 2015) self.assertEqual(utc_model.weekday, 2) self.assertEqual(utc_model.weekday_melb, 3) self.assertEqual(utc_model.isoweekday, 1) self.assertEqual(utc_model.isoweekday_melb, 2) self.assertEqual(utc_model.quarter, 2) self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_melb, 9) self.assertEqual(utc_model.hour_with_delta_pos, 4) self.assertEqual(utc_model.hour_with_delta_neg, 18) self.assertEqual(utc_model.minute_with_delta_neg, 47) with timezone.override(melb): melb_model = qs.get() self.assertEqual(melb_model.day, 16) self.assertEqual(melb_model.day_melb, 16) self.assertEqual(melb_model.week, 25) self.assertEqual(melb_model.isoyear, 2015) self.assertEqual(melb_model.weekday, 3) self.assertEqual(melb_model.isoweekday, 2) self.assertEqual(melb_model.quarter, 2) self.assertEqual(melb_model.weekday_melb, 3) self.assertEqual(melb_model.isoweekday_melb, 2) self.assertEqual(melb_model.hour, 9) self.assertEqual(melb_model.hour_melb, 9) def test_extract_func_with_timezone_minus_no_offset(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) ust_nera = zoneinfo.ZoneInfo("Asia/Ust-Nera") qs = DTModel.objects.annotate( hour=ExtractHour("start_datetime"), hour_tz=ExtractHour("start_datetime", tzinfo=ust_nera), ).order_by("start_datetime") utc_model = qs.get() self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_tz, 9) with timezone.override(ust_nera): ust_nera_model = qs.get() self.assertEqual(ust_nera_model.hour, 9) self.assertEqual(ust_nera_model.hour_tz, 9) def test_extract_func_explicit_timezone_priority(self): start_datetime = datetime(2015, 6, 15, 23, 30, 1, 321) end_datetime = datetime(2015, 6, 16, 13, 11, 27, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) melb = zoneinfo.ZoneInfo("Australia/Melbourne") with timezone.override(melb): model = ( DTModel.objects.annotate( day_melb=Extract("start_datetime", "day"), day_utc=Extract( "start_datetime", "day", tzinfo=datetime_timezone.utc ), ) .order_by("start_datetime") .get() ) self.assertEqual(model.day_melb, 16) self.assertEqual(model.day_utc, 15) def test_extract_invalid_field_with_timezone(self): melb = zoneinfo.ZoneInfo("Australia/Melbourne") msg = "tzinfo can only be used with DateTimeField." with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( day_melb=Extract("start_date", "day", tzinfo=melb), ).get() with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( hour_melb=Extract("start_time", "hour", tzinfo=melb), ).get() def test_trunc_timezone_applied_before_truncation(self): start_datetime = datetime(2016, 1, 1, 1, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) melb = zoneinfo.ZoneInfo("Australia/Melbourne") pacific = zoneinfo.ZoneInfo("America/Los_Angeles") model = ( DTModel.objects.annotate( melb_year=TruncYear("start_datetime", tzinfo=melb), pacific_year=TruncYear("start_datetime", tzinfo=pacific), melb_date=TruncDate("start_datetime", tzinfo=melb), pacific_date=TruncDate("start_datetime", tzinfo=pacific), melb_time=TruncTime("start_datetime", tzinfo=melb), pacific_time=TruncTime("start_datetime", tzinfo=pacific), ) .order_by("start_datetime") .get() ) melb_start_datetime = start_datetime.astimezone(melb) pacific_start_datetime = start_datetime.astimezone(pacific) self.assertEqual(model.start_datetime, start_datetime) self.assertEqual(model.melb_year, truncate_to(start_datetime, "year", melb)) self.assertEqual( model.pacific_year, truncate_to(start_datetime, "year", pacific) ) self.assertEqual(model.start_datetime.year, 2016) self.assertEqual(model.melb_year.year, 2016) self.assertEqual(model.pacific_year.year, 2015) self.assertEqual(model.melb_date, melb_start_datetime.date()) self.assertEqual(model.pacific_date, pacific_start_datetime.date()) self.assertEqual(model.melb_time, melb_start_datetime.time()) self.assertEqual(model.pacific_time, pacific_start_datetime.time()) def test_trunc_func_with_timezone(self): """ If the truncated datetime transitions to a different offset (daylight saving) then the returned value will have that new timezone/offset. """ start_datetime = datetime(2015, 6, 15, 14, 30, 50, 321) end_datetime = datetime(2016, 6, 15, 14, 10, 50, 123) start_datetime = timezone.make_aware(start_datetime) end_datetime = timezone.make_aware(end_datetime) self.create_model(start_datetime, end_datetime) self.create_model(end_datetime, start_datetime) melb = zoneinfo.ZoneInfo("Australia/Melbourne") def test_datetime_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=DateTimeField(), tzinfo=melb, ) ).order_by("start_datetime"), [ ( start_datetime, truncate_to(start_datetime.astimezone(melb), kind, melb), ), ( end_datetime, truncate_to(end_datetime.astimezone(melb), kind, melb), ), ], lambda m: (m.start_datetime, m.truncated), ) def test_datetime_to_date_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=DateField(), tzinfo=melb, ), ).order_by("start_datetime"), [ ( start_datetime, truncate_to(start_datetime.astimezone(melb).date(), kind), ), ( end_datetime, truncate_to(end_datetime.astimezone(melb).date(), kind), ), ], lambda m: (m.start_datetime, m.truncated), ) def test_datetime_to_time_kind(kind): self.assertQuerySetEqual( DTModel.objects.annotate( truncated=Trunc( "start_datetime", kind, output_field=TimeField(), tzinfo=melb, ) ).order_by("start_datetime"), [ ( start_datetime, truncate_to(start_datetime.astimezone(melb).time(), kind), ), ( end_datetime, truncate_to(end_datetime.astimezone(melb).time(), kind), ), ], lambda m: (m.start_datetime, m.truncated), ) test_datetime_to_date_kind("year") test_datetime_to_date_kind("quarter") test_datetime_to_date_kind("month") test_datetime_to_date_kind("week") test_datetime_to_date_kind("day") test_datetime_to_time_kind("hour") test_datetime_to_time_kind("minute") test_datetime_to_time_kind("second") test_datetime_kind("year") test_datetime_kind("quarter") test_datetime_kind("month") test_datetime_kind("week") test_datetime_kind("day") test_datetime_kind("hour") test_datetime_kind("minute") test_datetime_kind("second") qs = DTModel.objects.filter( start_datetime__date=Trunc( "start_datetime", "day", output_field=DateField() ) ) self.assertEqual(qs.count(), 2) def test_trunc_invalid_field_with_timezone(self): melb = zoneinfo.ZoneInfo("Australia/Melbourne") msg = "tzinfo can only be used with DateTimeField." with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( day_melb=Trunc("start_date", "day", tzinfo=melb), ).get() with self.assertRaisesMessage(ValueError, msg): DTModel.objects.annotate( hour_melb=Trunc("start_time", "hour", tzinfo=melb), ).get()
e3485916497406d569e7f3b40dbd38b3706f0f3b0ccc82b4f70eaf55ac8f51cd
from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( "Signal", [ ("id", models.AutoField(primary_key=True)), ], ), ]
20aa453ce94897448946fb7b60686f8f6c78cafcfa26ebf3607c7d8c322b52e4
import argparse import ctypes import faulthandler import hashlib import io import itertools import logging import multiprocessing import os import pickle import random import sys import textwrap import unittest from collections import defaultdict from contextlib import contextmanager from importlib import import_module from io import StringIO import sqlparse import django from django.core.management import call_command from django.db import connections from django.test import SimpleTestCase, TestCase from django.test.utils import NullTimeKeeper, TimeKeeper, iter_test_cases from django.test.utils import setup_databases as _setup_databases from django.test.utils import setup_test_environment from django.test.utils import teardown_databases as _teardown_databases from django.test.utils import teardown_test_environment from django.utils.datastructures import OrderedSet try: import ipdb as pdb except ImportError: import pdb try: import tblib.pickling_support except ImportError: tblib = None class DebugSQLTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger("django.db.backends") self.logger.setLevel(logging.DEBUG) self.debug_sql_stream = None super().__init__(stream, descriptions, verbosity) def startTest(self, test): self.debug_sql_stream = StringIO() self.handler = logging.StreamHandler(self.debug_sql_stream) self.logger.addHandler(self.handler) super().startTest(test) def stopTest(self, test): super().stopTest(test) self.logger.removeHandler(self.handler) if self.showAll: self.debug_sql_stream.seek(0) self.stream.write(self.debug_sql_stream.read()) self.stream.writeln(self.separator2) def addError(self, test, err): super().addError(test, err) if self.debug_sql_stream is None: # Error before tests e.g. in setUpTestData(). sql = "" else: self.debug_sql_stream.seek(0) sql = self.debug_sql_stream.read() self.errors[-1] = self.errors[-1] + (sql,) def addFailure(self, test, err): super().addFailure(test, err) self.debug_sql_stream.seek(0) self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),) def addSubTest(self, test, subtest, err): super().addSubTest(test, subtest, err) if err is not None: self.debug_sql_stream.seek(0) errors = ( self.failures if issubclass(err[0], test.failureException) else self.errors ) errors[-1] = errors[-1] + (self.debug_sql_stream.read(),) def printErrorList(self, flavour, errors): for test, err, sql_debug in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour, self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln(err) self.stream.writeln(self.separator2) self.stream.writeln( sqlparse.format(sql_debug, reindent=True, keyword_case="upper") ) class PDBDebugResult(unittest.TextTestResult): """ Custom result class that triggers a PDB session when an error or failure occurs. """ def addError(self, test, err): super().addError(test, err) self.debug(err) def addFailure(self, test, err): super().addFailure(test, err) self.debug(err) def addSubTest(self, test, subtest, err): if err is not None: self.debug(err) super().addSubTest(test, subtest, err) def debug(self, error): self._restoreStdout() self.buffer = False exc_type, exc_value, traceback = error print("\nOpening PDB: %r" % exc_value) pdb.post_mortem(traceback) class DummyList: """ Dummy list class for faking storage of results in unittest.TestResult. """ __slots__ = () def append(self, item): pass class RemoteTestResult(unittest.TestResult): """ Extend unittest.TestResult to record events in the child processes so they can be replayed in the parent process. Events include things like which tests succeeded or failed. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Fake storage of results to reduce memory usage. These are used by the # unittest default methods, but here 'events' is used instead. dummy_list = DummyList() self.failures = dummy_list self.errors = dummy_list self.skipped = dummy_list self.expectedFailures = dummy_list self.unexpectedSuccesses = dummy_list if tblib is not None: tblib.pickling_support.install() self.events = [] def __getstate__(self): # Make this class picklable by removing the file-like buffer # attributes. This is possible since they aren't used after unpickling # after being sent to ParallelTestSuite. state = self.__dict__.copy() state.pop("_stdout_buffer", None) state.pop("_stderr_buffer", None) state.pop("_original_stdout", None) state.pop("_original_stderr", None) return state @property def test_index(self): return self.testsRun - 1 def _confirm_picklable(self, obj): """ Confirm that obj can be pickled and unpickled as multiprocessing will need to pickle the exception in the child process and unpickle it in the parent process. Let the exception rise, if not. """ pickle.loads(pickle.dumps(obj)) def _print_unpicklable_subtest(self, test, subtest, pickle_exc): print( """ Subtest failed: test: {} subtest: {} Unfortunately, the subtest that failed cannot be pickled, so the parallel test runner cannot handle it cleanly. Here is the pickling error: > {} You should re-run this test with --parallel=1 to reproduce the failure with a cleaner failure message. """.format( test, subtest, pickle_exc ) ) def check_picklable(self, test, err): # Ensure that sys.exc_info() tuples are picklable. This displays a # clear multiprocessing.pool.RemoteTraceback generated in the child # process instead of a multiprocessing.pool.MaybeEncodingError, making # the root cause easier to figure out for users who aren't familiar # with the multiprocessing module. Since we're in a forked process, # our best chance to communicate with them is to print to stdout. try: self._confirm_picklable(err) except Exception as exc: original_exc_txt = repr(err[1]) original_exc_txt = textwrap.fill( original_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) pickle_exc_txt = repr(exc) pickle_exc_txt = textwrap.fill( pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) if tblib is None: print( """ {} failed: {} Unfortunately, tracebacks cannot be pickled, making it impossible for the parallel test runner to handle this exception cleanly. In order to see the traceback, you should install tblib: python -m pip install tblib """.format( test, original_exc_txt ) ) else: print( """ {} failed: {} Unfortunately, the exception it raised cannot be pickled, making it impossible for the parallel test runner to handle it cleanly. Here's the error encountered while trying to pickle the exception: {} You should re-run this test with the --parallel=1 option to reproduce the failure and get a correct traceback. """.format( test, original_exc_txt, pickle_exc_txt ) ) raise def check_subtest_picklable(self, test, subtest): try: self._confirm_picklable(subtest) except Exception as exc: self._print_unpicklable_subtest(test, subtest, exc) raise def startTestRun(self): super().startTestRun() self.events.append(("startTestRun",)) def stopTestRun(self): super().stopTestRun() self.events.append(("stopTestRun",)) def startTest(self, test): super().startTest(test) self.events.append(("startTest", self.test_index)) def stopTest(self, test): super().stopTest(test) self.events.append(("stopTest", self.test_index)) def addError(self, test, err): self.check_picklable(test, err) self.events.append(("addError", self.test_index, err)) super().addError(test, err) def addFailure(self, test, err): self.check_picklable(test, err) self.events.append(("addFailure", self.test_index, err)) super().addFailure(test, err) def addSubTest(self, test, subtest, err): # Follow Python's implementation of unittest.TestResult.addSubTest() by # not doing anything when a subtest is successful. if err is not None: # Call check_picklable() before check_subtest_picklable() since # check_picklable() performs the tblib check. self.check_picklable(test, err) self.check_subtest_picklable(test, subtest) self.events.append(("addSubTest", self.test_index, subtest, err)) super().addSubTest(test, subtest, err) def addSuccess(self, test): self.events.append(("addSuccess", self.test_index)) super().addSuccess(test) def addSkip(self, test, reason): self.events.append(("addSkip", self.test_index, reason)) super().addSkip(test, reason) def addExpectedFailure(self, test, err): # If tblib isn't installed, pickling the traceback will always fail. # However we don't want tblib to be required for running the tests # when they pass or fail as expected. Drop the traceback when an # expected failure occurs. if tblib is None: err = err[0], err[1], None self.check_picklable(test, err) self.events.append(("addExpectedFailure", self.test_index, err)) super().addExpectedFailure(test, err) def addUnexpectedSuccess(self, test): self.events.append(("addUnexpectedSuccess", self.test_index)) super().addUnexpectedSuccess(test) def wasSuccessful(self): """Tells whether or not this result was a success.""" failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"} return all(e[0] not in failure_types for e in self.events) def _exc_info_to_string(self, err, test): # Make this method no-op. It only powers the default unittest behavior # for recording errors, but this class pickles errors into 'events' # instead. return "" class RemoteTestRunner: """ Run tests and record everything but don't display anything. The implementation matches the unpythonic coding style of unittest2. """ resultclass = RemoteTestResult def __init__(self, failfast=False, resultclass=None, buffer=False): self.failfast = failfast self.buffer = buffer if resultclass is not None: self.resultclass = resultclass def run(self, test): result = self.resultclass() unittest.registerResult(result) result.failfast = self.failfast result.buffer = self.buffer test(result) return result def get_max_test_processes(): """ The maximum number of test processes when using the --parallel option. """ # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork() or spawn(). if multiprocessing.get_start_method() not in {"fork", "spawn"}: return 1 try: return int(os.environ["DJANGO_TEST_PROCESSES"]) except KeyError: return multiprocessing.cpu_count() def parallel_type(value): """Parse value passed to the --parallel option.""" if value == "auto": return value try: return int(value) except ValueError: raise argparse.ArgumentTypeError( f"{value!r} is not an integer or the string 'auto'" ) _worker_id = 0 def _init_worker( counter, initial_settings=None, serialized_contents=None, process_setup=None, process_setup_args=None, debug_mode=None, ): """ Switch to databases dedicated to this worker. This helper lives at module-level because of the multiprocessing module's requirements. """ global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter.value start_method = multiprocessing.get_start_method() if start_method == "spawn": if process_setup and callable(process_setup): if process_setup_args is None: process_setup_args = () process_setup(*process_setup_args) django.setup() setup_test_environment(debug=debug_mode) for alias in connections: connection = connections[alias] if start_method == "spawn": # Restore initial settings in spawned processes. connection.settings_dict.update(initial_settings[alias]) if value := serialized_contents.get(alias): connection._test_serialized_contents = value connection.creation.setup_worker_connection(_worker_id) def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast, buffer = args runner = runner_class(failfast=failfast, buffer=buffer) result = runner.run(subsuite) return subsuite_index, result.events def _process_setup_stub(*args): """Stub method to simplify run() implementation.""" pass class ParallelTestSuite(unittest.TestSuite): """ Run a series of tests in parallel in several processes. While the unittest module's documentation implies that orchestrating the execution of tests is the responsibility of the test runner, in practice, it appears that TestRunner classes are more concerned with formatting and displaying test results. Since there are fewer use cases for customizing TestSuite than TestRunner, implementing parallelization at the level of the TestSuite improves interoperability with existing custom test runners. A single instance of a test runner can still collect results from all tests without being aware that they have been run in parallel. """ # In case someone wants to modify these in a subclass. init_worker = _init_worker process_setup = _process_setup_stub process_setup_args = () run_subsuite = _run_subsuite runner_class = RemoteTestRunner def __init__( self, subsuites, processes, failfast=False, debug_mode=False, buffer=False ): self.subsuites = subsuites self.processes = processes self.failfast = failfast self.debug_mode = debug_mode self.buffer = buffer self.initial_settings = None self.serialized_contents = None super().__init__() def run(self, result): """ Distribute test cases across workers. Return an identifier of each test case with its result in order to use imap_unordered to show results as soon as they're available. To minimize pickling errors when getting results from workers: - pass back numeric indexes in self.subsuites instead of tests - make tracebacks picklable with tblib, if available Even with tblib, errors may still occur for dynamically created exception classes which cannot be unpickled. """ self.initialize_suite() counter = multiprocessing.Value(ctypes.c_int, 0) pool = multiprocessing.Pool( processes=self.processes, initializer=self.init_worker.__func__, initargs=[ counter, self.initial_settings, self.serialized_contents, self.process_setup.__func__, self.process_setup_args, self.debug_mode, ], ) args = [ (self.runner_class, index, subsuite, self.failfast, self.buffer) for index, subsuite in enumerate(self.subsuites) ] test_results = pool.imap_unordered(self.run_subsuite.__func__, args) while True: if result.shouldStop: pool.terminate() break try: subsuite_index, events = test_results.next(timeout=0.1) except multiprocessing.TimeoutError: continue except StopIteration: pool.close() break tests = list(self.subsuites[subsuite_index]) for event in events: event_name = event[0] handler = getattr(result, event_name, None) if handler is None: continue test = tests[event[1]] args = event[2:] handler(test, *args) pool.join() return result def __iter__(self): return iter(self.subsuites) def initialize_suite(self): if multiprocessing.get_start_method() == "spawn": self.initial_settings = { alias: connections[alias].settings_dict for alias in connections } self.serialized_contents = { alias: connections[alias]._test_serialized_contents for alias in connections if alias in self.serialized_aliases } class Shuffler: """ This class implements shuffling with a special consistency property. Consistency means that, for a given seed and key function, if two sets of items are shuffled, the resulting order will agree on the intersection of the two sets. For example, if items are removed from an original set, the shuffled order for the new set will be the shuffled order of the original set restricted to the smaller set. """ # This doesn't need to be cryptographically strong, so use what's fastest. hash_algorithm = "md5" @classmethod def _hash_text(cls, text): h = hashlib.new(cls.hash_algorithm, usedforsecurity=False) h.update(text.encode("utf-8")) return h.hexdigest() def __init__(self, seed=None): if seed is None: # Limit seeds to 10 digits for simpler output. seed = random.randint(0, 10**10 - 1) seed_source = "generated" else: seed_source = "given" self.seed = seed self.seed_source = seed_source @property def seed_display(self): return f"{self.seed!r} ({self.seed_source})" def _hash_item(self, item, key): text = "{}{}".format(self.seed, key(item)) return self._hash_text(text) def shuffle(self, items, key): """ Return a new list of the items in a shuffled order. The `key` is a function that accepts an item in `items` and returns a string unique for that item that can be viewed as a string id. The order of the return value is deterministic. It depends on the seed and key function but not on the original order. """ hashes = {} for item in items: hashed = self._hash_item(item, key) if hashed in hashes: msg = "item {!r} has same hash {!r} as item {!r}".format( item, hashed, hashes[hashed], ) raise RuntimeError(msg) hashes[hashed] = item return [hashes[hashed] for hashed in sorted(hashes)] class DiscoverRunner: """A Django test runner that uses unittest2 test discovery.""" test_suite = unittest.TestSuite parallel_test_suite = ParallelTestSuite test_runner = unittest.TextTestRunner test_loader = unittest.defaultTestLoader reorder_by = (TestCase, SimpleTestCase) def __init__( self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, test_name_patterns=None, pdb=False, buffer=False, enable_faulthandler=True, timing=False, shuffle=False, logger=None, **kwargs, ): self.pattern = pattern self.top_level = top_level self.verbosity = verbosity self.interactive = interactive self.failfast = failfast self.keepdb = keepdb self.reverse = reverse self.debug_mode = debug_mode self.debug_sql = debug_sql self.parallel = parallel self.tags = set(tags or []) self.exclude_tags = set(exclude_tags or []) if not faulthandler.is_enabled() and enable_faulthandler: try: faulthandler.enable(file=sys.stderr.fileno()) except (AttributeError, io.UnsupportedOperation): faulthandler.enable(file=sys.__stderr__.fileno()) self.pdb = pdb if self.pdb and self.parallel > 1: raise ValueError( "You cannot use --pdb with parallel tests; pass --parallel=1 to use it." ) self.buffer = buffer self.test_name_patterns = None self.time_keeper = TimeKeeper() if timing else NullTimeKeeper() if test_name_patterns: # unittest does not export the _convert_select_pattern function # that converts command-line arguments to patterns. self.test_name_patterns = { pattern if "*" in pattern else "*%s*" % pattern for pattern in test_name_patterns } self.shuffle = shuffle self._shuffler = None self.logger = logger @classmethod def add_arguments(cls, parser): parser.add_argument( "-t", "--top-level-directory", dest="top_level", help="Top level of project for unittest discovery.", ) parser.add_argument( "-p", "--pattern", default="test*.py", help="The test matching pattern. Defaults to test*.py.", ) parser.add_argument( "--keepdb", action="store_true", help="Preserves the test DB between runs." ) parser.add_argument( "--shuffle", nargs="?", default=False, type=int, metavar="SEED", help="Shuffles test case order.", ) parser.add_argument( "-r", "--reverse", action="store_true", help="Reverses test case order.", ) parser.add_argument( "--debug-mode", action="store_true", help="Sets settings.DEBUG to True.", ) parser.add_argument( "-d", "--debug-sql", action="store_true", help="Prints logged SQL queries on failure.", ) parser.add_argument( "--parallel", nargs="?", const="auto", default=0, type=parallel_type, metavar="N", help=( "Run tests using up to N parallel processes. Use the value " '"auto" to run one test process for each processor core.' ), ) parser.add_argument( "--tag", action="append", dest="tags", help="Run only tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--exclude-tag", action="append", dest="exclude_tags", help="Do not run tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--pdb", action="store_true", help="Runs a debugger (pdb, or ipdb if installed) on error or failure.", ) parser.add_argument( "-b", "--buffer", action="store_true", help="Discard output from passing tests.", ) parser.add_argument( "--no-faulthandler", action="store_false", dest="enable_faulthandler", help="Disables the Python faulthandler module during tests.", ) parser.add_argument( "--timing", action="store_true", help=("Output timings, including database set up and total run time."), ) parser.add_argument( "-k", action="append", dest="test_name_patterns", help=( "Only run test methods and classes that match the pattern " "or substring. Can be used multiple times. Same as " "unittest -k option." ), ) @property def shuffle_seed(self): if self._shuffler is None: return None return self._shuffler.seed def log(self, msg, level=None): """ Log the message at the given logging level (the default is INFO). If a logger isn't set, the message is instead printed to the console, respecting the configured verbosity. A verbosity of 0 prints no output, a verbosity of 1 prints INFO and above, and a verbosity of 2 or higher prints all levels. """ if level is None: level = logging.INFO if self.logger is None: if self.verbosity <= 0 or (self.verbosity == 1 and level < logging.INFO): return print(msg) else: self.logger.log(level, msg) def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler() def setup_shuffler(self): if self.shuffle is False: return shuffler = Shuffler(seed=self.shuffle) self.log(f"Using shuffle seed: {shuffler.seed_display}") self._shuffler = shuffler @contextmanager def load_with_patterns(self): original_test_name_patterns = self.test_loader.testNamePatterns self.test_loader.testNamePatterns = self.test_name_patterns try: yield finally: # Restore the original patterns. self.test_loader.testNamePatterns = original_test_name_patterns def load_tests_for_label(self, label, discover_kwargs): label_as_path = os.path.abspath(label) tests = None # If a module, or "module.ClassName[.method_name]", just run those. if not os.path.exists(label_as_path): with self.load_with_patterns(): tests = self.test_loader.loadTestsFromName(label) if tests.countTestCases(): return tests # Try discovery if "label" is a package or directory. is_importable, is_package = try_importing(label) if is_importable: if not is_package: return tests elif not os.path.isdir(label_as_path): if os.path.exists(label_as_path): assert tests is None raise RuntimeError( f"One of the test labels is a path to a file: {label!r}, " f"which is not supported. Use a dotted module name or " f"path to a directory instead." ) return tests kwargs = discover_kwargs.copy() if os.path.isdir(label_as_path) and not self.top_level: kwargs["top_level_dir"] = find_top_level(label_as_path) with self.load_with_patterns(): tests = self.test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from this run, # to support running tests from two different top-levels. self.test_loader._top_level_dir = None return tests def build_suite(self, test_labels=None, **kwargs): test_labels = test_labels or ["."] discover_kwargs = {} if self.pattern is not None: discover_kwargs["pattern"] = self.pattern if self.top_level is not None: discover_kwargs["top_level_dir"] = self.top_level self.setup_shuffler() all_tests = [] for label in test_labels: tests = self.load_tests_for_label(label, discover_kwargs) all_tests.extend(iter_test_cases(tests)) if self.tags or self.exclude_tags: if self.tags: self.log( "Including test tag(s): %s." % ", ".join(sorted(self.tags)), level=logging.DEBUG, ) if self.exclude_tags: self.log( "Excluding test tag(s): %s." % ", ".join(sorted(self.exclude_tags)), level=logging.DEBUG, ) all_tests = filter_tests_by_tags(all_tests, self.tags, self.exclude_tags) # Put the failures detected at load time first for quicker feedback. # _FailedTest objects include things like test modules that couldn't be # found or that couldn't be loaded due to syntax errors. test_types = (unittest.loader._FailedTest, *self.reorder_by) all_tests = list( reorder_tests( all_tests, test_types, shuffler=self._shuffler, reverse=self.reverse, ) ) self.log("Found %d test(s)." % len(all_tests)) suite = self.test_suite(all_tests) if self.parallel > 1: subsuites = partition_suite_by_case(suite) # Since tests are distributed across processes on a per-TestCase # basis, there's no need for more processes than TestCases. processes = min(self.parallel, len(subsuites)) # Update also "parallel" because it's used to determine the number # of test databases. self.parallel = processes if processes > 1: suite = self.parallel_test_suite( subsuites, processes, self.failfast, self.debug_mode, self.buffer, ) return suite def setup_databases(self, **kwargs): return _setup_databases( self.verbosity, self.interactive, time_keeper=self.time_keeper, keepdb=self.keepdb, debug_sql=self.debug_sql, parallel=self.parallel, **kwargs, ) def get_resultclass(self): if self.debug_sql: return DebugSQLTextTestResult elif self.pdb: return PDBDebugResult def get_test_runner_kwargs(self): return { "failfast": self.failfast, "resultclass": self.get_resultclass(), "verbosity": self.verbosity, "buffer": self.buffer, } def run_checks(self, databases): # Checks are run after database creation since some checks require # database access. call_command("check", verbosity=self.verbosity, databases=databases) def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) try: return runner.run(suite) finally: if self._shuffler is not None: seed_display = self._shuffler.seed_display self.log(f"Used shuffle seed: {seed_display}") def teardown_databases(self, old_config, **kwargs): """Destroy all the non-mirror databases.""" _teardown_databases( old_config, verbosity=self.verbosity, parallel=self.parallel, keepdb=self.keepdb, ) def teardown_test_environment(self, **kwargs): unittest.removeHandler() teardown_test_environment() def suite_result(self, suite, result, **kwargs): return ( len(result.failures) + len(result.errors) + len(result.unexpectedSuccesses) ) def _get_databases(self, suite): databases = {} for test in iter_test_cases(suite): test_databases = getattr(test, "databases", None) if test_databases == "__all__": test_databases = connections if test_databases: serialized_rollback = getattr(test, "serialized_rollback", False) databases.update( (alias, serialized_rollback or databases.get(alias, False)) for alias in test_databases ) return databases def get_databases(self, suite): databases = self._get_databases(suite) unused_databases = [alias for alias in connections if alias not in databases] if unused_databases: self.log( "Skipping setup of unused database(s): %s." % ", ".join(sorted(unused_databases)), level=logging.DEBUG, ) return databases def run_tests(self, test_labels, **kwargs): """ Run the unit tests for all the test labels in the provided list. Test labels should be dotted Python paths to test modules, test classes, or test methods. Return the number of tests that failed. """ self.setup_test_environment() suite = self.build_suite(test_labels) databases = self.get_databases(suite) suite.serialized_aliases = set( alias for alias, serialize in databases.items() if serialize ) with self.time_keeper.timed("Total database setup"): old_config = self.setup_databases( aliases=databases, serialized_aliases=suite.serialized_aliases, ) run_failed = False try: self.run_checks(databases) result = self.run_suite(suite) except Exception: run_failed = True raise finally: try: with self.time_keeper.timed("Total database teardown"): self.teardown_databases(old_config) self.teardown_test_environment() except Exception: # Silence teardown exceptions if an exception was raised during # runs to avoid shadowing it. if not run_failed: raise self.time_keeper.print_results() return self.suite_result(suite, result) def try_importing(label): """ Try importing a test label, and return (is_importable, is_package). Relative labels like "." and ".." are seen as directories. """ try: mod = import_module(label) except (ImportError, TypeError): return (False, False) return (True, hasattr(mod, "__path__")) def find_top_level(top_level): # Try to be a bit smarter than unittest about finding the default top-level # for a given directory path, to avoid breaking relative imports. # (Unittest's default is to set top-level equal to the path, which means # relative imports will result in "Attempted relative import in # non-package."). # We'd be happy to skip this and require dotted module paths (which don't # cause this problem) instead of file paths (which do), but in the case of # a directory in the cwd, which would be equally valid if considered as a # top-level module or as a directory path, unittest unfortunately prefers # the latter. while True: init_py = os.path.join(top_level, "__init__.py") if not os.path.exists(init_py): break try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give up. break top_level = try_next return top_level def _class_shuffle_key(cls): return f"{cls.__module__}.{cls.__qualname__}" def shuffle_tests(tests, shuffler): """ Return an iterator over the given tests in a shuffled order, keeping tests next to other tests of their class. `tests` should be an iterable of tests. """ tests_by_type = {} for _, class_tests in itertools.groupby(tests, type): class_tests = list(class_tests) test_type = type(class_tests[0]) class_tests = shuffler.shuffle(class_tests, key=lambda test: test.id()) tests_by_type[test_type] = class_tests classes = shuffler.shuffle(tests_by_type, key=_class_shuffle_key) return itertools.chain(*(tests_by_type[cls] for cls in classes)) def reorder_test_bin(tests, shuffler=None, reverse=False): """ Return an iterator that reorders the given tests, keeping tests next to other tests of their class. `tests` should be an iterable of tests that supports reversed(). """ if shuffler is None: if reverse: return reversed(tests) # The function must return an iterator. return iter(tests) tests = shuffle_tests(tests, shuffler) if not reverse: return tests # Arguments to reversed() must be reversible. return reversed(list(tests)) def reorder_tests(tests, classes, reverse=False, shuffler=None): """ Reorder an iterable of tests, grouping by the given TestCase classes. This function also removes any duplicates and reorders so that tests of the same type are consecutive. The result is returned as an iterator. `classes` is a sequence of types. Tests that are instances of `classes[0]` are grouped first, followed by instances of `classes[1]`, etc. Tests that are not instances of any of the classes are grouped last. If `reverse` is True, the tests within each `classes` group are reversed, but without reversing the order of `classes` itself. The `shuffler` argument is an optional instance of this module's `Shuffler` class. If provided, tests will be shuffled within each `classes` group, but keeping tests with other tests of their TestCase class. Reversing is applied after shuffling to allow reversing the same random order. """ # Each bin maps TestCase class to OrderedSet of tests. This permits tests # to be grouped by TestCase class even if provided non-consecutively. bins = [defaultdict(OrderedSet) for i in range(len(classes) + 1)] *class_bins, last_bin = bins for test in tests: for test_bin, test_class in zip(class_bins, classes): if isinstance(test, test_class): break else: test_bin = last_bin test_bin[type(test)].add(test) for test_bin in bins: # Call list() since reorder_test_bin()'s input must support reversed(). tests = list(itertools.chain.from_iterable(test_bin.values())) yield from reorder_test_bin(tests, shuffler=shuffler, reverse=reverse) def partition_suite_by_case(suite): """Partition a test suite by test case, preserving the order of tests.""" suite_class = type(suite) all_tests = iter_test_cases(suite) return [suite_class(tests) for _, tests in itertools.groupby(all_tests, type)] def test_match_tags(test, tags, exclude_tags): if isinstance(test, unittest.loader._FailedTest): # Tests that couldn't load always match to prevent tests from falsely # passing due e.g. to syntax errors. return True test_tags = set(getattr(test, "tags", [])) test_fn_name = getattr(test, "_testMethodName", str(test)) if hasattr(test, test_fn_name): test_fn = getattr(test, test_fn_name) test_fn_tags = list(getattr(test_fn, "tags", [])) test_tags = test_tags.union(test_fn_tags) if tags and test_tags.isdisjoint(tags): return False return test_tags.isdisjoint(exclude_tags) def filter_tests_by_tags(tests, tags, exclude_tags): """Return the matching tests as an iterator.""" return (test for test in tests if test_match_tags(test, tags, exclude_tags))
f1d68f63721321601c8e94684508de1241c60f72e08b90a44ab0a9c1942754c2
import json import mimetypes import os import sys from copy import copy from functools import partial from http import HTTPStatus from importlib import import_module from io import BytesIO, IOBase from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit from asgiref.sync import sync_to_async from django.conf import settings from django.core.handlers.asgi import ASGIRequest from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.core.serializers.json import DjangoJSONEncoder from django.core.signals import got_request_exception, request_finished, request_started from django.db import close_old_connections from django.http import HttpHeaders, HttpRequest, QueryDict, SimpleCookie from django.test import signals from django.test.utils import ContextList from django.urls import resolve from django.utils.encoding import force_bytes from django.utils.functional import SimpleLazyObject from django.utils.http import urlencode from django.utils.itercompat import is_iterable from django.utils.regex_helper import _lazy_re_compile __all__ = ( "AsyncClient", "AsyncRequestFactory", "Client", "RedirectCycleError", "RequestFactory", "encode_file", "encode_multipart", ) BOUNDARY = "BoUnDaRyStRiNg" MULTIPART_CONTENT = "multipart/form-data; boundary=%s" % BOUNDARY CONTENT_TYPE_RE = _lazy_re_compile(r".*; charset=([\w-]+);?") # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8 JSON_CONTENT_TYPE_RE = _lazy_re_compile(r"^application\/(.+\+)?json") class RedirectCycleError(Exception): """The test client has been asked to follow a redirect loop.""" def __init__(self, message, last_response): super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain class FakePayload(IOBase): """ A wrapper around BytesIO that restricts what can be read since data from the network can't be sought and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life. """ def __init__(self, initial_bytes=None): self.__content = BytesIO() self.__len = 0 self.read_started = False if initial_bytes is not None: self.write(initial_bytes) def __len__(self): return self.__len def read(self, size=-1, /): if not self.read_started: self.__content.seek(0) self.read_started = True if size == -1 or size is None: size = self.__len assert ( self.__len >= size ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(size) self.__len -= len(content) return content def readline(self, size=-1, /): if not self.read_started: self.__content.seek(0) self.read_started = True if size == -1 or size is None: size = self.__len assert ( self.__len >= size ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.readline(size) self.__len -= len(content) return content def write(self, b, /): if self.read_started: raise ValueError("Unable to write a payload after it's been read") content = force_bytes(b) self.__content.write(content) self.__len += len(content) def closing_iterator_wrapper(iterable, close): try: yield from iterable finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) def conditional_content_removal(request, response): """ Simulate the behavior of most web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensure compliance with RFC 9112 Section 6.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): if response.streaming: response.streaming_content = [] else: response.content = b"" if request.method == "HEAD": if response.streaming: response.streaming_content = [] else: response.content = b"" return response class ClientHandler(BaseHandler): """ An HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # Emulate a WSGI server by calling the close method on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response class AsyncClientHandler(BaseHandler): """An async version of ClientHandler.""" def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) async def __call__(self, scope): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware(is_async=True) # Extract body file from the scope, if provided. if "_body_file" in scope: body_file = scope.pop("_body_file") else: body_file = FakePayload("") request_started.disconnect(close_old_connections) await sync_to_async(request_started.send, thread_sensitive=False)( sender=self.__class__, scope=scope ) request_started.connect(close_old_connections) # Wrap FakePayload body_file to allow large read() in test environment. request = ASGIRequest(scope, LimitedStream(body_file, len(body_file))) # Sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably required # for backwards compatibility with external tests against admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = await self.get_response_async(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating ASGI request to the response so that it could # be later retrieved. response.asgi_request = request # Emulate a server by calling the close method on completion. if response.streaming: response.streaming_content = await sync_to_async( closing_iterator_wrapper, thread_sensitive=False )( response.streaming_content, response.close, ) else: request_finished.disconnect(close_old_connections) # Will fire request_finished. await sync_to_async(response.close, thread_sensitive=False)() request_finished.connect(close_old_connections) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """ store.setdefault("templates", []).append(template) if "context" not in store: store["context"] = ContextList() store["context"].append(copy(context)) def encode_multipart(boundary, data): """ Encode multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. def is_file(thing): return hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for (key, value) in data.items(): if value is None: raise TypeError( "Cannot encode None for key '%s' as POST data. Did you mean " "to pass an empty string or omit the value?" % key ) elif is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, str) and is_iterable(value): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", item, ] ) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", value, ] ) lines.extend( [ to_bytes("--%s--" % boundary), b"", ] ) return b"\r\n".join(lines) def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # file.name might not be a string. For example, it's an int for # tempfile.TemporaryFile(). file_has_string_name = hasattr(file, "name") and isinstance(file.name, str) filename = os.path.basename(file.name) if file_has_string_name else "" if hasattr(file, "content_type"): content_type = file.content_type elif filename: content_type = mimetypes.guess_type(filename)[0] else: content_type = None if content_type is None: content_type = "application/octet-stream" filename = filename or key return [ to_bytes("--%s" % boundary), to_bytes( 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ), to_bytes("Content-Type: %s" % content_type), b"", to_bytes(file.read()), ] class RequestFactory: """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, *, json_encoder=DjangoJSONEncoder, headers=None, **defaults): self.json_encoder = json_encoder self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() if headers: self.defaults.update(HttpHeaders.to_wsgi_names(headers)) def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See https://www.python.org/dev/peps/pep-3333/#environ-variables return { "HTTP_COOKIE": "; ".join( sorted( "%s=%s" % (morsel.key, morsel.coded_value) for morsel in self.cookies.values() ) ), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, **self.defaults, **request, } def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match[1] else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _encode_json(self, data, content_type): """ Return encoded JSON if data is a dict, list, or tuple and content_type is application/json. """ should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance( data, (dict, list, tuple) ) return json.dumps(data, cls=self.json_encoder) if should_encode else data def _get_path(self, parsed): path = parsed.path # If there are parameters, add them if parsed.params: path += ";" + parsed.params path = unquote_to_bytes(path) # Replace the behavior where non-ASCII values in the WSGI environ are # arbitrarily decoded with ISO-8859-1. # Refs comment in `get_bytes_from_wsgi()`. return path.decode("iso-8859-1") def get(self, path, data=None, secure=False, *, headers=None, **extra): """Construct a GET request.""" data = {} if data is None else data return self.generic( "GET", path, secure=secure, headers=headers, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def post( self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, *, headers=None, **extra, ): """Construct a POST request.""" data = self._encode_json({} if data is None else data, content_type) post_data = self._encode_data(data, content_type) return self.generic( "POST", path, post_data, content_type, secure=secure, headers=headers, **extra, ) def head(self, path, data=None, secure=False, *, headers=None, **extra): """Construct a HEAD request.""" data = {} if data is None else data return self.generic( "HEAD", path, secure=secure, headers=headers, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def trace(self, path, secure=False, *, headers=None, **extra): """Construct a TRACE request.""" return self.generic("TRACE", path, secure=secure, headers=headers, **extra) def options( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): "Construct an OPTIONS request." return self.generic( "OPTIONS", path, data, content_type, secure=secure, headers=headers, **extra ) def put( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct a PUT request.""" data = self._encode_json(data, content_type) return self.generic( "PUT", path, data, content_type, secure=secure, headers=headers, **extra ) def patch( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct a PATCH request.""" data = self._encode_json(data, content_type) return self.generic( "PATCH", path, data, content_type, secure=secure, headers=headers, **extra ) def delete( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct a DELETE request.""" data = self._encode_json(data, content_type) return self.generic( "DELETE", path, data, content_type, secure=secure, headers=headers, **extra ) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { "PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": method, "SERVER_PORT": "443" if secure else "80", "wsgi.url_scheme": "https" if secure else "http", } if data: r.update( { "CONTENT_LENGTH": str(len(data)), "CONTENT_TYPE": content_type, "wsgi.input": FakePayload(data), } ) if headers: extra.update(HttpHeaders.to_wsgi_names(headers)) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get("QUERY_STRING"): # WSGI requires latin-1 encoded strings. See get_path_info(). query_string = parsed[4].encode().decode("iso-8859-1") r["QUERY_STRING"] = query_string return self.request(**r) class AsyncRequestFactory(RequestFactory): """ Class that lets you create mock ASGI-like Request objects for use in testing. Usage: rf = AsyncRequestFactory() get_request = await rf.get('/hello/') post_request = await rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, including synchronous ones. The reason we have a separate class here is: a) this makes ASGIRequest subclasses, and b) AsyncTestClient can subclass it. """ def _base_scope(self, **request): """The base scope for a request.""" # This is a minimal valid ASGI scope, plus: # - headers['cookie'] for cookie support, # - 'client' often useful, see #8551. scope = { "asgi": {"version": "3.0"}, "type": "http", "http_version": "1.1", "client": ["127.0.0.1", 0], "server": ("testserver", "80"), "scheme": "http", "method": "GET", "headers": [], **self.defaults, **request, } scope["headers"].append( ( b"cookie", b"; ".join( sorted( ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii") for morsel in self.cookies.values() ) ), ) ) return scope def request(self, **request): """Construct a generic request object.""" # This is synchronous, which means all methods on this class are. # AsyncClient, however, has an async request function, which makes all # its methods async. if "_body_file" in request: body_file = request.pop("_body_file") else: body_file = FakePayload("") # Wrap FakePayload body_file to allow large read() in test environment. return ASGIRequest( self._base_scope(**request), LimitedStream(body_file, len(body_file)) ) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy. data = force_bytes(data, settings.DEFAULT_CHARSET) s = { "method": method, "path": self._get_path(parsed), "server": ("127.0.0.1", "443" if secure else "80"), "scheme": "https" if secure else "http", "headers": [(b"host", b"testserver")], } if data: s["headers"].extend( [ (b"content-length", str(len(data)).encode("ascii")), (b"content-type", content_type.encode("ascii")), ] ) s["_body_file"] = FakePayload(data) follow = extra.pop("follow", None) if follow is not None: s["follow"] = follow if query_string := extra.pop("QUERY_STRING", None): s["query_string"] = query_string if headers: extra.update(HttpHeaders.to_asgi_names(headers)) s["headers"] += [ (key.lower().encode("ascii"), value.encode("latin1")) for key, value in extra.items() ] # If QUERY_STRING is absent or empty, we want to extract it from the # URL. if not s.get("query_string"): s["query_string"] = parsed[4] return self.request(**s) class ClientMixin: """ Mixin with common methods between Client and AsyncClient. """ def store_exc_info(self, **kwargs): """Store exceptions when they are generated by a view.""" self.exc_info = sys.exc_info() def check_exception(self, response): """ Look for a signaled exception, clear the current context exception data, re-raise the signaled exception, and clear the signaled exception from the local cache. """ response.exc_info = self.exc_info if self.exc_info: _, exc_value, _ = self.exc_info self.exc_info = None if self.raise_request_exception: raise exc_value @property def session(self): """Return the current session variables.""" engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session def login(self, **credentials): """ Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible or False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True return False def force_login(self, user, backend=None): def get_backend(): from django.contrib.auth import load_backend for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) if hasattr(backend, "get_user"): return backend_path if backend is None: backend = get_backend() user.backend = backend self._login(user, backend) def _login(self, user, backend=None): from django.contrib.auth import login # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() login(request, user, backend) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } self.cookies[session_cookie].update(cookie_data) def logout(self): """Log out the user by removing the cookies and session object.""" from django.contrib.auth import get_user, logout request = HttpRequest() if self.session: request.session = self.session request.user = get_user(request) else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie() def _parse_json(self, response, **extra): if not hasattr(response, "_json"): if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")): raise ValueError( 'Content-Type header is "%s", not "application/json"' % response.get("Content-Type") ) response._json = json.loads( response.content.decode(response.charset), **extra ) return response._json class Client(ClientMixin, RequestFactory): """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, **defaults, ): super().__init__(headers=headers, **defaults) self.handler = ClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None self.headers = None def request(self, **request): """ Make a generic request. Compose the environment dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ environ = self._base_environ(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = self.handler(environ) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.wsgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["PATH_INFO"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get( self, path, data=None, follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using GET.""" self.extra = extra self.headers = headers response = super().get(path, data=data, secure=secure, headers=headers, **extra) if follow: response = self._handle_redirects( response, data=data, headers=headers, **extra ) return response def post( self, path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using POST.""" self.extra = extra self.headers = headers response = super().post( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def head( self, path, data=None, follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using HEAD.""" self.extra = extra self.headers = headers response = super().head( path, data=data, secure=secure, headers=headers, **extra ) if follow: response = self._handle_redirects( response, data=data, headers=headers, **extra ) return response def options( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using OPTIONS.""" self.extra = extra self.headers = headers response = super().options( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def put( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Send a resource to the server using PUT.""" self.extra = extra self.headers = headers response = super().put( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def patch( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Send a resource to the server using PATCH.""" self.extra = extra self.headers = headers response = super().patch( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def delete( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Send a DELETE request to the server.""" self.extra = extra self.headers = headers response = super().delete( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def trace( self, path, data="", follow=False, secure=False, *, headers=None, **extra, ): """Send a TRACE request to the server.""" self.extra = extra self.headers = headers response = super().trace( path, data=data, secure=secure, headers=headers, **extra ) if follow: response = self._handle_redirects( response, data=data, headers=headers, **extra ) return response def _handle_redirects( self, response, data="", content_type="", headers=None, **extra, ): """ Follow any redirects by requesting responses from the server using GET. """ response.redirect_chain = [] redirect_status_codes = ( HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.FOUND, HTTPStatus.SEE_OTHER, HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ) while response.status_code in redirect_status_codes: response_url = response.url redirect_chain = response.redirect_chain redirect_chain.append((response_url, response.status_code)) url = urlsplit(response_url) if url.scheme: extra["wsgi.url_scheme"] = url.scheme if url.hostname: extra["SERVER_NAME"] = url.hostname if url.port: extra["SERVER_PORT"] = str(url.port) path = url.path # RFC 3986 Section 6.2.3: Empty path should be normalized to "/". if not path and url.netloc: path = "/" # Prepend the request path to handle relative path redirects if not path.startswith("/"): path = urljoin(response.request["PATH_INFO"], path) if response.status_code in ( HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ): # Preserve request method and query string (if needed) # post-redirect for 307/308 responses. request_method = response.request["REQUEST_METHOD"].lower() if request_method not in ("get", "head"): extra["QUERY_STRING"] = url.query request_method = getattr(self, request_method) else: request_method = self.get data = QueryDict(url.query) content_type = None response = request_method( path, data=data, content_type=content_type, follow=False, headers=headers, **extra, ) response.redirect_chain = redirect_chain if redirect_chain[-1] in redirect_chain[:-1]: # Check that we're not redirecting to somewhere we've already # been to, to prevent loops. raise RedirectCycleError( "Redirect loop detected.", last_response=response ) if len(redirect_chain) > 20: # Such a lengthy chain likely also means a loop, but one with # a growing path, changing view, or changing query argument; # 20 is the value of "network.http.redirection-limit" from Firefox. raise RedirectCycleError("Too many redirects.", last_response=response) return response class AsyncClient(ClientMixin, AsyncRequestFactory): """ An async version of Client that creates ASGIRequests and calls through an async request path. Does not currently support "follow" on its methods. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, **defaults, ): super().__init__(headers=headers, **defaults) self.handler = AsyncClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None self.headers = None async def request(self, **request): """ Make a generic request. Compose the scope dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ if "follow" in request: raise NotImplementedError( "AsyncClient request methods do not accept the follow parameter." ) scope = self._base_scope(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = await self.handler(scope) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.asgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["path"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response
0eace00c87433b773aafe6f0640793ddb5d2d2933097d53853659587f183f48a
import difflib import json import logging import posixpath import sys import threading import unittest import warnings from collections import Counter from contextlib import contextmanager from copy import copy, deepcopy from difflib import get_close_matches from functools import wraps from unittest.suite import _DebugResult from unittest.util import safe_repr from urllib.parse import ( parse_qsl, unquote, urlencode, urljoin, urlparse, urlsplit, urlunparse, ) from urllib.request import url2pathname from asgiref.sync import async_to_sync, iscoroutinefunction from django.apps import apps from django.conf import settings from django.core import mail from django.core.exceptions import ImproperlyConfigured, ValidationError from django.core.files import locks from django.core.handlers.wsgi import WSGIHandler, get_path_info from django.core.management import call_command from django.core.management.color import no_style from django.core.management.sql import emit_post_migrate_signal from django.core.servers.basehttp import ThreadedWSGIServer, WSGIRequestHandler from django.core.signals import setting_changed from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction from django.forms.fields import CharField from django.http import QueryDict from django.http.request import split_domain_port, validate_host from django.test.client import AsyncClient, Client from django.test.html import HTMLParseError, parse_html from django.test.signals import template_rendered from django.test.utils import ( CaptureQueriesContext, ContextList, compare_xml, modify_settings, override_settings, ) from django.utils.deprecation import RemovedInDjango51Warning from django.utils.functional import classproperty from django.views.static import serve logger = logging.getLogger("django.test") __all__ = ( "TestCase", "TransactionTestCase", "SimpleTestCase", "skipIfDBFeature", "skipUnlessDBFeature", ) def to_list(value): """Put value into a list if it's not already one.""" if not isinstance(value, list): value = [value] return value def assert_and_parse_html(self, html, user_msg, msg): try: dom = parse_html(html) except HTMLParseError as e: standardMsg = "%s\n%s" % (msg, e) self.fail(self._formatMessage(user_msg, standardMsg)) return dom class _AssertNumQueriesContext(CaptureQueriesContext): def __init__(self, test_case, num, connection): self.test_case = test_case self.num = num super().__init__(connection) def __exit__(self, exc_type, exc_value, traceback): super().__exit__(exc_type, exc_value, traceback) if exc_type is not None: return executed = len(self) self.test_case.assertEqual( executed, self.num, "%d queries executed, %d expected\nCaptured queries were:\n%s" % ( executed, self.num, "\n".join( "%d. %s" % (i, query["sql"]) for i, query in enumerate(self.captured_queries, start=1) ), ), ) class _AssertTemplateUsedContext: def __init__(self, test_case, template_name, msg_prefix="", count=None): self.test_case = test_case self.template_name = template_name self.msg_prefix = msg_prefix self.count = count self.rendered_templates = [] self.rendered_template_names = [] self.context = ContextList() def on_template_render(self, sender, signal, template, context, **kwargs): self.rendered_templates.append(template) self.rendered_template_names.append(template.name) self.context.append(copy(context)) def test(self): self.test_case._assert_template_used( self.template_name, self.rendered_template_names, self.msg_prefix, self.count, ) def __enter__(self): template_rendered.connect(self.on_template_render) return self def __exit__(self, exc_type, exc_value, traceback): template_rendered.disconnect(self.on_template_render) if exc_type is not None: return self.test() class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext): def test(self): self.test_case.assertFalse( self.template_name in self.rendered_template_names, f"{self.msg_prefix}Template '{self.template_name}' was used " f"unexpectedly in rendering the response", ) class DatabaseOperationForbidden(AssertionError): pass class _DatabaseFailure: def __init__(self, wrapped, message): self.wrapped = wrapped self.message = message def __call__(self): raise DatabaseOperationForbidden(self.message) class SimpleTestCase(unittest.TestCase): # The class we'll use for the test client self.client. # Can be overridden in derived classes. client_class = Client async_client_class = AsyncClient _overridden_settings = None _modified_settings = None databases = set() _disallowed_database_msg = ( "Database %(operation)s to %(alias)r are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to ensure " "proper test isolation or add %(alias)r to %(test)s.databases to silence " "this failure." ) _disallowed_connection_methods = [ ("connect", "connections"), ("temporary_connection", "connections"), ("cursor", "queries"), ("chunked_cursor", "queries"), ] @classmethod def setUpClass(cls): super().setUpClass() if cls._overridden_settings: cls._cls_overridden_context = override_settings(**cls._overridden_settings) cls._cls_overridden_context.enable() cls.addClassCleanup(cls._cls_overridden_context.disable) if cls._modified_settings: cls._cls_modified_context = modify_settings(cls._modified_settings) cls._cls_modified_context.enable() cls.addClassCleanup(cls._cls_modified_context.disable) cls._add_databases_failures() cls.addClassCleanup(cls._remove_databases_failures) @classmethod def _validate_databases(cls): if cls.databases == "__all__": return frozenset(connections) for alias in cls.databases: if alias not in connections: message = ( "%s.%s.databases refers to %r which is not defined in " "settings.DATABASES." % ( cls.__module__, cls.__qualname__, alias, ) ) close_matches = get_close_matches(alias, list(connections)) if close_matches: message += " Did you mean %r?" % close_matches[0] raise ImproperlyConfigured(message) return frozenset(cls.databases) @classmethod def _add_databases_failures(cls): cls.databases = cls._validate_databases() for alias in connections: if alias in cls.databases: continue connection = connections[alias] for name, operation in cls._disallowed_connection_methods: message = cls._disallowed_database_msg % { "test": "%s.%s" % (cls.__module__, cls.__qualname__), "alias": alias, "operation": operation, } method = getattr(connection, name) setattr(connection, name, _DatabaseFailure(method, message)) @classmethod def _remove_databases_failures(cls): for alias in connections: if alias in cls.databases: continue connection = connections[alias] for name, _ in cls._disallowed_connection_methods: method = getattr(connection, name) setattr(connection, name, method.wrapped) def __call__(self, result=None): """ Wrapper around default __call__ method to perform common Django test set up. This means that user-defined Test Cases aren't required to include a call to super().setUp(). """ self._setup_and_call(result) def debug(self): """Perform the same as __call__(), without catching the exception.""" debug_result = _DebugResult() self._setup_and_call(debug_result, debug=True) def _setup_and_call(self, result, debug=False): """ Perform the following in order: pre-setup, run test, post-teardown, skipping pre/post hooks if test is set to be skipped. If debug=True, reraise any errors in setup and use super().debug() instead of __call__() to run the test. """ testMethod = getattr(self, self._testMethodName) skipped = getattr(self.__class__, "__unittest_skip__", False) or getattr( testMethod, "__unittest_skip__", False ) # Convert async test methods. if iscoroutinefunction(testMethod): setattr(self, self._testMethodName, async_to_sync(testMethod)) if not skipped: try: self._pre_setup() except Exception: if debug: raise result.addError(self, sys.exc_info()) return if debug: super().debug() else: super().__call__(result) if not skipped: try: self._post_teardown() except Exception: if debug: raise result.addError(self, sys.exc_info()) return def _pre_setup(self): """ Perform pre-test setup: * Create a test client. * Clear the mail test outbox. """ self.client = self.client_class() self.async_client = self.async_client_class() mail.outbox = [] def _post_teardown(self): """Perform post-test things.""" pass def settings(self, **kwargs): """ A context manager that temporarily sets a setting and reverts to the original value when exiting the context. """ return override_settings(**kwargs) def modify_settings(self, **kwargs): """ A context manager that temporarily applies changes a list setting and reverts back to the original value when exiting the context. """ return modify_settings(**kwargs) def assertRedirects( self, response, expected_url, status_code=302, target_status_code=200, msg_prefix="", fetch_redirect_response=True, ): """ Assert that a response redirected to a specific URL and that the redirect URL can be loaded. Won't work for external links since it uses the test client to do a request (use fetch_redirect_response=False to check such links without fetching them). """ if msg_prefix: msg_prefix += ": " if hasattr(response, "redirect_chain"): # The request was a followed redirect self.assertTrue( response.redirect_chain, msg_prefix + ( "Response didn't redirect as expected: Response code was %d " "(expected %d)" ) % (response.status_code, status_code), ) self.assertEqual( response.redirect_chain[0][1], status_code, msg_prefix + ( "Initial response didn't redirect as expected: Response code was " "%d (expected %d)" ) % (response.redirect_chain[0][1], status_code), ) url, status_code = response.redirect_chain[-1] self.assertEqual( response.status_code, target_status_code, msg_prefix + ( "Response didn't redirect as expected: Final Response code was %d " "(expected %d)" ) % (response.status_code, target_status_code), ) else: # Not a followed redirect self.assertEqual( response.status_code, status_code, msg_prefix + ( "Response didn't redirect as expected: Response code was %d " "(expected %d)" ) % (response.status_code, status_code), ) url = response.url scheme, netloc, path, query, fragment = urlsplit(url) # Prepend the request path to handle relative path redirects. if not path.startswith("/"): url = urljoin(response.request["PATH_INFO"], url) path = urljoin(response.request["PATH_INFO"], path) if fetch_redirect_response: # netloc might be empty, or in cases where Django tests the # HTTP scheme, the convention is for netloc to be 'testserver'. # Trust both as "internal" URLs here. domain, port = split_domain_port(netloc) if domain and not validate_host(domain, settings.ALLOWED_HOSTS): raise ValueError( "The test client is unable to fetch remote URLs (got %s). " "If the host is served by Django, add '%s' to ALLOWED_HOSTS. " "Otherwise, use " "assertRedirects(..., fetch_redirect_response=False)." % (url, domain) ) # Get the redirection page, using the same client that was used # to obtain the original response. extra = response.client.extra or {} headers = response.client.headers or {} redirect_response = response.client.get( path, QueryDict(query), secure=(scheme == "https"), headers=headers, **extra, ) self.assertEqual( redirect_response.status_code, target_status_code, msg_prefix + ( "Couldn't retrieve redirection page '%s': response code was %d " "(expected %d)" ) % (path, redirect_response.status_code, target_status_code), ) self.assertURLEqual( url, expected_url, msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url), ) def assertURLEqual(self, url1, url2, msg_prefix=""): """ Assert that two URLs are the same, ignoring the order of query string parameters except for parameters with the same name. For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but /path/?a=1&a=2 isn't equal to /path/?a=2&a=1. """ def normalize(url): """Sort the URL's query string parameters.""" url = str(url) # Coerce reverse_lazy() URLs. scheme, netloc, path, params, query, fragment = urlparse(url) query_parts = sorted(parse_qsl(query)) return urlunparse( (scheme, netloc, path, params, urlencode(query_parts), fragment) ) self.assertEqual( normalize(url1), normalize(url2), msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2), ) def _assert_contains(self, response, text, status_code, msg_prefix, html): # If the response supports deferred rendering and hasn't been rendered # yet, then ensure that it does get rendered before proceeding further. if ( hasattr(response, "render") and callable(response.render) and not response.is_rendered ): response.render() if msg_prefix: msg_prefix += ": " self.assertEqual( response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code), ) if response.streaming: content = b"".join(response.streaming_content) else: content = response.content if not isinstance(text, bytes) or html: text = str(text) content = content.decode(response.charset) text_repr = "'%s'" % text else: text_repr = repr(text) if html: content = assert_and_parse_html( self, content, None, "Response's content is not valid HTML:" ) text = assert_and_parse_html( self, text, None, "Second argument is not valid HTML:" ) real_count = content.count(text) return (text_repr, real_count, msg_prefix) def assertContains( self, response, text, count=None, status_code=200, msg_prefix="", html=False ): """ Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ text_repr, real_count, msg_prefix = self._assert_contains( response, text, status_code, msg_prefix, html ) if count is not None: self.assertEqual( real_count, count, msg_prefix + "Found %d instances of %s in response (expected %d)" % (real_count, text_repr, count), ) else: self.assertTrue( real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr ) def assertNotContains( self, response, text, status_code=200, msg_prefix="", html=False ): """ Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that ``text`` doesn't occur in the content of the response. """ text_repr, real_count, msg_prefix = self._assert_contains( response, text, status_code, msg_prefix, html ) self.assertEqual( real_count, 0, msg_prefix + "Response should not contain %s" % text_repr ) def _check_test_client_response(self, response, attribute, method_name): """ Raise a ValueError if the given response doesn't have the required attribute. """ if not hasattr(response, attribute): raise ValueError( f"{method_name}() is only usable on responses fetched using " "the Django test Client." ) def _assert_form_error(self, form, field, errors, msg_prefix, form_repr): if not form.is_bound: self.fail( f"{msg_prefix}The {form_repr} is not bound, it will never have any " f"errors." ) if field is not None and field not in form.fields: self.fail( f"{msg_prefix}The {form_repr} does not contain the field {field!r}." ) if field is None: field_errors = form.non_field_errors() failure_message = f"The non-field errors of {form_repr} don't match." else: field_errors = form.errors.get(field, []) failure_message = ( f"The errors of field {field!r} on {form_repr} don't match." ) self.assertEqual(field_errors, errors, msg_prefix + failure_message) def assertFormError(self, form, field, errors, msg_prefix=""): """ Assert that a field named "field" on the given form object has specific errors. errors can be either a single error message or a list of errors messages. Using errors=[] test that the field has no errors. You can pass field=None to check the form's non-field errors. """ if msg_prefix: msg_prefix += ": " errors = to_list(errors) self._assert_form_error(form, field, errors, msg_prefix, f"form {form!r}") # RemovedInDjango51Warning. def assertFormsetError(self, *args, **kw): warnings.warn( "assertFormsetError() is deprecated in favor of assertFormSetError().", category=RemovedInDjango51Warning, stacklevel=2, ) return self.assertFormSetError(*args, **kw) def assertFormSetError(self, formset, form_index, field, errors, msg_prefix=""): """ Similar to assertFormError() but for formsets. Use form_index=None to check the formset's non-form errors (in that case, you must also use field=None). Otherwise use an integer to check the formset's n-th form for errors. Other parameters are the same as assertFormError(). """ if form_index is None and field is not None: raise ValueError("You must use field=None with form_index=None.") if msg_prefix: msg_prefix += ": " errors = to_list(errors) if not formset.is_bound: self.fail( f"{msg_prefix}The formset {formset!r} is not bound, it will never have " f"any errors." ) if form_index is not None and form_index >= formset.total_form_count(): form_count = formset.total_form_count() form_or_forms = "forms" if form_count > 1 else "form" self.fail( f"{msg_prefix}The formset {formset!r} only has {form_count} " f"{form_or_forms}." ) if form_index is not None: form_repr = f"form {form_index} of formset {formset!r}" self._assert_form_error( formset.forms[form_index], field, errors, msg_prefix, form_repr ) else: failure_message = f"The non-form errors of formset {formset!r} don't match." self.assertEqual( formset.non_form_errors(), errors, msg_prefix + failure_message ) def _get_template_used(self, response, template_name, msg_prefix, method_name): if response is None and template_name is None: raise TypeError("response and/or template_name argument must be provided") if msg_prefix: msg_prefix += ": " if template_name is not None and response is not None: self._check_test_client_response(response, "templates", method_name) if not hasattr(response, "templates") or (response is None and template_name): if response: template_name = response response = None # use this template with context manager return template_name, None, msg_prefix template_names = [t.name for t in response.templates if t.name is not None] return None, template_names, msg_prefix def _assert_template_used(self, template_name, template_names, msg_prefix, count): if not template_names: self.fail(msg_prefix + "No templates used to render the response") self.assertTrue( template_name in template_names, msg_prefix + "Template '%s' was not a template used to render" " the response. Actual template(s) used: %s" % (template_name, ", ".join(template_names)), ) if count is not None: self.assertEqual( template_names.count(template_name), count, msg_prefix + "Template '%s' was expected to be rendered %d " "time(s) but was actually rendered %d time(s)." % (template_name, count, template_names.count(template_name)), ) def assertTemplateUsed( self, response=None, template_name=None, msg_prefix="", count=None ): """ Assert that the template with the provided name was used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._get_template_used( response, template_name, msg_prefix, "assertTemplateUsed", ) if context_mgr_template: # Use assertTemplateUsed as context manager. return _AssertTemplateUsedContext( self, context_mgr_template, msg_prefix, count ) self._assert_template_used(template_name, template_names, msg_prefix, count) def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=""): """ Assert that the template with the provided name was NOT used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._get_template_used( response, template_name, msg_prefix, "assertTemplateNotUsed", ) if context_mgr_template: # Use assertTemplateNotUsed as context manager. return _AssertTemplateNotUsedContext(self, context_mgr_template, msg_prefix) self.assertFalse( template_name in template_names, msg_prefix + "Template '%s' was used unexpectedly in rendering the response" % template_name, ) @contextmanager def _assert_raises_or_warns_cm( self, func, cm_attr, expected_exception, expected_message ): with func(expected_exception) as cm: yield cm self.assertIn(expected_message, str(getattr(cm, cm_attr))) def _assertFooMessage( self, func, cm_attr, expected_exception, expected_message, *args, **kwargs ): callable_obj = None if args: callable_obj, *args = args cm = self._assert_raises_or_warns_cm( func, cm_attr, expected_exception, expected_message ) # Assertion used in context manager fashion. if callable_obj is None: return cm # Assertion was passed a callable. with cm: callable_obj(*args, **kwargs) def assertRaisesMessage( self, expected_exception, expected_message, *args, **kwargs ): """ Assert that expected_message is found in the message of a raised exception. Args: expected_exception: Exception class expected to be raised. expected_message: expected error message string value. args: Function to be called and extra positional args. kwargs: Extra kwargs. """ return self._assertFooMessage( self.assertRaises, "exception", expected_exception, expected_message, *args, **kwargs, ) def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs): """ Same as assertRaisesMessage but for assertWarns() instead of assertRaises(). """ return self._assertFooMessage( self.assertWarns, "warning", expected_warning, expected_message, *args, **kwargs, ) def assertFieldOutput( self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value="", ): """ Assert that a form field behaves correctly with various inputs. Args: fieldclass: the class of the field to be tested. valid: a dictionary mapping valid inputs to their expected cleaned values. invalid: a dictionary mapping invalid inputs to one or more raised error messages. field_args: the args passed to instantiate the field field_kwargs: the kwargs passed to instantiate the field empty_value: the expected clean output for inputs in empty_values """ if field_args is None: field_args = [] if field_kwargs is None: field_kwargs = {} required = fieldclass(*field_args, **field_kwargs) optional = fieldclass(*field_args, **{**field_kwargs, "required": False}) # test valid inputs for input, output in valid.items(): self.assertEqual(required.clean(input), output) self.assertEqual(optional.clean(input), output) # test invalid inputs for input, errors in invalid.items(): with self.assertRaises(ValidationError) as context_manager: required.clean(input) self.assertEqual(context_manager.exception.messages, errors) with self.assertRaises(ValidationError) as context_manager: optional.clean(input) self.assertEqual(context_manager.exception.messages, errors) # test required inputs error_required = [required.error_messages["required"]] for e in required.empty_values: with self.assertRaises(ValidationError) as context_manager: required.clean(e) self.assertEqual(context_manager.exception.messages, error_required) self.assertEqual(optional.clean(e), empty_value) # test that max_length and min_length are always accepted if issubclass(fieldclass, CharField): field_kwargs.update({"min_length": 2, "max_length": 20}) self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass) def assertHTMLEqual(self, html1, html2, msg=None): """ Assert that two HTML snippets are semantically the same. Whitespace in most cases is ignored, and attribute ordering is not significant. The arguments must be valid HTML. """ dom1 = assert_and_parse_html( self, html1, msg, "First argument is not valid HTML:" ) dom2 = assert_and_parse_html( self, html2, msg, "Second argument is not valid HTML:" ) if dom1 != dom2: standardMsg = "%s != %s" % (safe_repr(dom1, True), safe_repr(dom2, True)) diff = "\n" + "\n".join( difflib.ndiff( str(dom1).splitlines(), str(dom2).splitlines(), ) ) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertHTMLNotEqual(self, html1, html2, msg=None): """Assert that two HTML snippets are not semantically equivalent.""" dom1 = assert_and_parse_html( self, html1, msg, "First argument is not valid HTML:" ) dom2 = assert_and_parse_html( self, html2, msg, "Second argument is not valid HTML:" ) if dom1 == dom2: standardMsg = "%s == %s" % (safe_repr(dom1, True), safe_repr(dom2, True)) self.fail(self._formatMessage(msg, standardMsg)) def assertInHTML(self, needle, haystack, count=None, msg_prefix=""): needle = assert_and_parse_html( self, needle, None, "First argument is not valid HTML:" ) haystack = assert_and_parse_html( self, haystack, None, "Second argument is not valid HTML:" ) real_count = haystack.count(needle) if count is not None: self.assertEqual( real_count, count, msg_prefix + "Found %d instances of '%s' in response (expected %d)" % (real_count, needle, count), ) else: self.assertTrue( real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle ) def assertJSONEqual(self, raw, expected_data, msg=None): """ Assert that the JSON fragments raw and expected_data are equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except json.JSONDecodeError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, str): try: expected_data = json.loads(expected_data) except ValueError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertEqual(data, expected_data, msg=msg) def assertJSONNotEqual(self, raw, expected_data, msg=None): """ Assert that the JSON fragments raw and expected_data are not equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except json.JSONDecodeError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, str): try: expected_data = json.loads(expected_data) except json.JSONDecodeError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertNotEqual(data, expected_data, msg=msg) def assertXMLEqual(self, xml1, xml2, msg=None): """ Assert that two XML snippets are semantically the same. Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML. """ try: result = compare_xml(xml1, xml2) except Exception as e: standardMsg = "First or second argument is not valid XML\n%s" % e self.fail(self._formatMessage(msg, standardMsg)) else: if not result: standardMsg = "%s != %s" % ( safe_repr(xml1, True), safe_repr(xml2, True), ) diff = "\n" + "\n".join( difflib.ndiff(xml1.splitlines(), xml2.splitlines()) ) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertXMLNotEqual(self, xml1, xml2, msg=None): """ Assert that two XML snippets are not semantically equivalent. Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML. """ try: result = compare_xml(xml1, xml2) except Exception as e: standardMsg = "First or second argument is not valid XML\n%s" % e self.fail(self._formatMessage(msg, standardMsg)) else: if result: standardMsg = "%s == %s" % ( safe_repr(xml1, True), safe_repr(xml2, True), ) self.fail(self._formatMessage(msg, standardMsg)) class TransactionTestCase(SimpleTestCase): # Subclasses can ask for resetting of auto increment sequence before each # test case reset_sequences = False # Subclasses can enable only a subset of apps for faster tests available_apps = None # Subclasses can define fixtures which will be automatically installed. fixtures = None databases = {DEFAULT_DB_ALIAS} _disallowed_database_msg = ( "Database %(operation)s to %(alias)r are not allowed in this test. " "Add %(alias)r to %(test)s.databases to ensure proper test isolation " "and silence this failure." ) # If transactions aren't available, Django will serialize the database # contents into a fixture during setup and flush and reload them # during teardown (as flush does not restore data from migrations). # This can be slow; this flag allows enabling on a per-case basis. serialized_rollback = False def _pre_setup(self): """ Perform pre-test setup: * If the class has an 'available_apps' attribute, restrict the app registry to these applications, then fire the post_migrate signal -- it must run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, install those fixtures. """ super()._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=self.available_apps, enter=True, ) for db_name in self._databases_names(include_mirrors=False): emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name) try: self._fixture_setup() except Exception: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=settings.INSTALLED_APPS, enter=False, ) raise # Clear the queries_log so that it's less likely to overflow (a single # test probably won't execute 9K queries). If queries_log overflows, # then assertNumQueries() doesn't work. for db_name in self._databases_names(include_mirrors=False): connections[db_name].queries_log.clear() @classmethod def _databases_names(cls, include_mirrors=True): # Only consider allowed database aliases, including mirrors or not. return [ alias for alias in connections if alias in cls.databases and ( include_mirrors or not connections[alias].settings_dict["TEST"]["MIRROR"] ) ] def _reset_sequences(self, db_name): conn = connections[db_name] if conn.features.supports_sequence_reset: sql_list = conn.ops.sequence_reset_by_name_sql( no_style(), conn.introspection.sequence_list() ) if sql_list: with transaction.atomic(using=db_name): with conn.cursor() as cursor: for sql in sql_list: cursor.execute(sql) def _fixture_setup(self): for db_name in self._databases_names(include_mirrors=False): # Reset sequences if self.reset_sequences: self._reset_sequences(db_name) # Provide replica initial data from migrated apps, if needed. if self.serialized_rollback and hasattr( connections[db_name], "_test_serialized_contents" ): if self.available_apps is not None: apps.unset_available_apps() connections[db_name].creation.deserialize_db_from_string( connections[db_name]._test_serialized_contents ) if self.available_apps is not None: apps.set_available_apps(self.available_apps) if self.fixtures: # We have to use this slightly awkward syntax due to the fact # that we're using *args and **kwargs together. call_command( "loaddata", *self.fixtures, **{"verbosity": 0, "database": db_name} ) def _should_reload_connections(self): return True def _post_teardown(self): """ Perform post-test things: * Flush the contents of the database to leave a clean slate. If the class has an 'available_apps' attribute, don't fire post_migrate. * Force-close the connection so the next test gets a clean cursor. """ try: self._fixture_teardown() super()._post_teardown() if self._should_reload_connections(): # Some DB cursors include SQL statements as part of cursor # creation. If you have a test that does a rollback, the effect # of these statements is lost, which can affect the operation of # tests (e.g., losing a timezone setting causing objects to be # created with the wrong time). To make sure this doesn't # happen, get a clean connection at the start of every test. for conn in connections.all(initialized_only=True): conn.close() finally: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=settings.INSTALLED_APPS, enter=False, ) def _fixture_teardown(self): # Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal # when flushing only a subset of the apps for db_name in self._databases_names(include_mirrors=False): # Flush the database inhibit_post_migrate = ( self.available_apps is not None or ( # Inhibit the post_migrate signal when using serialized # rollback to avoid trying to recreate the serialized data. self.serialized_rollback and hasattr(connections[db_name], "_test_serialized_contents") ) ) call_command( "flush", verbosity=0, interactive=False, database=db_name, reset_sequences=False, allow_cascade=self.available_apps is not None, inhibit_post_migrate=inhibit_post_migrate, ) # RemovedInDjango51Warning. def assertQuerysetEqual(self, *args, **kw): warnings.warn( "assertQuerysetEqual() is deprecated in favor of assertQuerySetEqual().", category=RemovedInDjango51Warning, stacklevel=2, ) return self.assertQuerySetEqual(*args, **kw) def assertQuerySetEqual(self, qs, values, transform=None, ordered=True, msg=None): values = list(values) items = qs if transform is not None: items = map(transform, items) if not ordered: return self.assertDictEqual(Counter(items), Counter(values), msg=msg) # For example qs.iterator() could be passed as qs, but it does not # have 'ordered' attribute. if len(values) > 1 and hasattr(qs, "ordered") and not qs.ordered: raise ValueError( "Trying to compare non-ordered queryset against more than one " "ordered value." ) return self.assertEqual(list(items), values, msg=msg) def assertNumQueries(self, num, func=None, *args, using=DEFAULT_DB_ALIAS, **kwargs): conn = connections[using] context = _AssertNumQueriesContext(self, num, conn) if func is None: return context with context: func(*args, **kwargs) def connections_support_transactions(aliases=None): """ Return whether or not all (or specified) connections support transactions. """ conns = ( connections.all() if aliases is None else (connections[alias] for alias in aliases) ) return all(conn.features.supports_transactions for conn in conns) class TestData: """ Descriptor to provide TestCase instance isolation for attributes assigned during the setUpTestData() phase. Allow safe alteration of objects assigned in setUpTestData() by test methods by exposing deep copies instead of the original objects. Objects are deep copied using a memo kept on the test case instance in order to maintain their original relationships. """ memo_attr = "_testdata_memo" def __init__(self, name, data): self.name = name self.data = data def get_memo(self, testcase): try: memo = getattr(testcase, self.memo_attr) except AttributeError: memo = {} setattr(testcase, self.memo_attr, memo) return memo def __get__(self, instance, owner): if instance is None: return self.data memo = self.get_memo(instance) data = deepcopy(self.data, memo) setattr(instance, self.name, data) return data def __repr__(self): return "<TestData: name=%r, data=%r>" % (self.name, self.data) class TestCase(TransactionTestCase): """ Similar to TransactionTestCase, but use `transaction.atomic()` to achieve test isolation. In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior). On database backends with no transaction support, TestCase behaves as TransactionTestCase. """ @classmethod def _enter_atomics(cls): """Open atomic blocks for multiple databases.""" atomics = {} for db_name in cls._databases_names(): atomic = transaction.atomic(using=db_name) atomic._from_testcase = True atomic.__enter__() atomics[db_name] = atomic return atomics @classmethod def _rollback_atomics(cls, atomics): """Rollback atomic blocks opened by the previous method.""" for db_name in reversed(cls._databases_names()): transaction.set_rollback(True, using=db_name) atomics[db_name].__exit__(None, None, None) @classmethod def _databases_support_transactions(cls): return connections_support_transactions(cls.databases) @classmethod def setUpClass(cls): super().setUpClass() if not cls._databases_support_transactions(): return cls.cls_atomics = cls._enter_atomics() if cls.fixtures: for db_name in cls._databases_names(include_mirrors=False): try: call_command( "loaddata", *cls.fixtures, **{"verbosity": 0, "database": db_name}, ) except Exception: cls._rollback_atomics(cls.cls_atomics) raise pre_attrs = cls.__dict__.copy() try: cls.setUpTestData() except Exception: cls._rollback_atomics(cls.cls_atomics) raise for name, value in cls.__dict__.items(): if value is not pre_attrs.get(name): setattr(cls, name, TestData(name, value)) @classmethod def tearDownClass(cls): if cls._databases_support_transactions(): cls._rollback_atomics(cls.cls_atomics) for conn in connections.all(initialized_only=True): conn.close() super().tearDownClass() @classmethod def setUpTestData(cls): """Load initial data for the TestCase.""" pass def _should_reload_connections(self): if self._databases_support_transactions(): return False return super()._should_reload_connections() def _fixture_setup(self): if not self._databases_support_transactions(): # If the backend does not support transactions, we should reload # class data before each test self.setUpTestData() return super()._fixture_setup() if self.reset_sequences: raise TypeError("reset_sequences cannot be used on TestCase instances") self.atomics = self._enter_atomics() def _fixture_teardown(self): if not self._databases_support_transactions(): return super()._fixture_teardown() try: for db_name in reversed(self._databases_names()): if self._should_check_constraints(connections[db_name]): connections[db_name].check_constraints() finally: self._rollback_atomics(self.atomics) def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() ) @classmethod @contextmanager def captureOnCommitCallbacks(cls, *, using=DEFAULT_DB_ALIAS, execute=False): """Context manager to capture transaction.on_commit() callbacks.""" callbacks = [] start_count = len(connections[using].run_on_commit) try: yield callbacks finally: while True: callback_count = len(connections[using].run_on_commit) for _, callback, robust in connections[using].run_on_commit[ start_count: ]: callbacks.append(callback) if execute: if robust: try: callback() except Exception as e: logger.error( f"Error calling {callback.__qualname__} in " f"on_commit() (%s).", e, exc_info=True, ) else: callback() if callback_count == len(connections[using].run_on_commit): break start_count = callback_count class CheckCondition: """Descriptor class for deferred condition checking.""" def __init__(self, *conditions): self.conditions = conditions def add_condition(self, condition, reason): return self.__class__(*self.conditions, (condition, reason)) def __get__(self, instance, cls=None): # Trigger access for all bases. if any(getattr(base, "__unittest_skip__", False) for base in cls.__bases__): return True for condition, reason in self.conditions: if condition(): # Override this descriptor's value and set the skip reason. cls.__unittest_skip__ = True cls.__unittest_skip_why__ = reason return True return False def _deferredSkip(condition, reason, name): def decorator(test_func): nonlocal condition if not ( isinstance(test_func, type) and issubclass(test_func, unittest.TestCase) ): @wraps(test_func) def skip_wrapper(*args, **kwargs): if ( args and isinstance(args[0], unittest.TestCase) and connection.alias not in getattr(args[0], "databases", {}) ): raise ValueError( "%s cannot be used on %s as %s doesn't allow queries " "against the %r database." % ( name, args[0], args[0].__class__.__qualname__, connection.alias, ) ) if condition(): raise unittest.SkipTest(reason) return test_func(*args, **kwargs) test_item = skip_wrapper else: # Assume a class is decorated test_item = test_func databases = getattr(test_item, "databases", None) if not databases or connection.alias not in databases: # Defer raising to allow importing test class's module. def condition(): raise ValueError( "%s cannot be used on %s as it doesn't allow queries " "against the '%s' database." % ( name, test_item, connection.alias, ) ) # Retrieve the possibly existing value from the class's dict to # avoid triggering the descriptor. skip = test_func.__dict__.get("__unittest_skip__") if isinstance(skip, CheckCondition): test_item.__unittest_skip__ = skip.add_condition(condition, reason) elif skip is not True: test_item.__unittest_skip__ = CheckCondition((condition, reason)) return test_item return decorator def skipIfDBFeature(*features): """Skip a test if a database has at least one of the named features.""" return _deferredSkip( lambda: any( getattr(connection.features, feature, False) for feature in features ), "Database has feature(s) %s" % ", ".join(features), "skipIfDBFeature", ) def skipUnlessDBFeature(*features): """Skip a test unless a database has all the named features.""" return _deferredSkip( lambda: not all( getattr(connection.features, feature, False) for feature in features ), "Database doesn't support feature(s): %s" % ", ".join(features), "skipUnlessDBFeature", ) def skipUnlessAnyDBFeature(*features): """Skip a test unless a database has any of the named features.""" return _deferredSkip( lambda: not any( getattr(connection.features, feature, False) for feature in features ), "Database doesn't support any of the feature(s): %s" % ", ".join(features), "skipUnlessAnyDBFeature", ) class QuietWSGIRequestHandler(WSGIRequestHandler): """ A WSGIRequestHandler that doesn't log to standard output any of the requests received, so as to not clutter the test result output. """ def log_message(*args): pass class FSFilesHandler(WSGIHandler): """ WSGI middleware that intercepts calls to a directory, as defined by one of the *_ROOT settings, and serves those files, publishing them under *_URL. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super().__init__() def _should_handle(self, path): """ Check if the path should be handled. Ignore the path if: * the host is provided as part of the base_url * the request's path isn't under the media path (or equal) """ return path.startswith(self.base_url[2]) and not self.base_url[1] def file_path(self, url): """Return the relative path to the file on disk for the given URL.""" relative_url = url.removeprefix(self.base_url[2]) return url2pathname(relative_url) def get_response(self, request): from django.http import Http404 if self._should_handle(request.path): try: return self.serve(request) except Http404: pass return super().get_response(request) def serve(self, request): os_rel_path = self.file_path(request.path) os_rel_path = posixpath.normpath(unquote(os_rel_path)) # Emulate behavior of django.contrib.staticfiles.views.serve() when it # invokes staticfiles' finders functionality. # TODO: Modify if/when that internal API is refactored final_rel_path = os_rel_path.replace("\\", "/").lstrip("/") return serve(request, final_rel_path, document_root=self.get_base_dir()) def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) return super().__call__(environ, start_response) class _StaticFilesHandler(FSFilesHandler): """ Handler for serving static files. A private class that is meant to be used solely as a convenience by LiveServerThread. """ def get_base_dir(self): return settings.STATIC_ROOT def get_base_url(self): return settings.STATIC_URL class _MediaFilesHandler(FSFilesHandler): """ Handler for serving the media files. A private class that is meant to be used solely as a convenience by LiveServerThread. """ def get_base_dir(self): return settings.MEDIA_ROOT def get_base_url(self): return settings.MEDIA_URL class LiveServerThread(threading.Thread): """Thread for running a live HTTP server while the tests are running.""" server_class = ThreadedWSGIServer def __init__(self, host, static_handler, connections_override=None, port=0): self.host = host self.port = port self.is_ready = threading.Event() self.error = None self.static_handler = static_handler self.connections_override = connections_override super().__init__() def run(self): """ Set up the live server and databases, and then loop over handling HTTP requests. """ if self.connections_override: # Override this thread's database connections with the ones # provided by the main thread. for alias, conn in self.connections_override.items(): connections[alias] = conn try: # Create the handler for serving static and media files handler = self.static_handler(_MediaFilesHandler(WSGIHandler())) self.httpd = self._create_server( connections_override=self.connections_override, ) # If binding to port zero, assign the port allocated by the OS. if self.port == 0: self.port = self.httpd.server_address[1] self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever() except Exception as e: self.error = e self.is_ready.set() finally: connections.close_all() def _create_server(self, connections_override=None): return self.server_class( (self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False, connections_override=connections_override, ) def terminate(self): if hasattr(self, "httpd"): # Stop the WSGI server self.httpd.shutdown() self.httpd.server_close() self.join() class LiveServerTestCase(TransactionTestCase): """ Do basically the same as TransactionTestCase but also launch a live HTTP server in a separate thread so that the tests may use another testing framework, such as Selenium for example, instead of the built-in dummy client. It inherits from TransactionTestCase instead of TestCase because the threads don't share the same transactions (unless if using in-memory sqlite) and each thread needs to commit all their transactions so that the other thread can see the changes. """ host = "localhost" port = 0 server_thread_class = LiveServerThread static_handler = _StaticFilesHandler @classproperty def live_server_url(cls): return "http://%s:%s" % (cls.host, cls.server_thread.port) @classproperty def allowed_host(cls): return cls.host @classmethod def _make_connections_override(cls): connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if conn.vendor == "sqlite" and conn.is_in_memory_db(): connections_override[conn.alias] = conn return connections_override @classmethod def setUpClass(cls): super().setUpClass() cls._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={"append": cls.allowed_host}, ) cls._live_server_modified_settings.enable() cls.addClassCleanup(cls._live_server_modified_settings.disable) cls._start_server_thread() @classmethod def _start_server_thread(cls): connections_override = cls._make_connections_override() for conn in connections_override.values(): # Explicitly enable thread-shareability for this connection. conn.inc_thread_sharing() cls.server_thread = cls._create_server_thread(connections_override) cls.server_thread.daemon = True cls.server_thread.start() cls.addClassCleanup(cls._terminate_thread) # Wait for the live server to be ready cls.server_thread.is_ready.wait() if cls.server_thread.error: raise cls.server_thread.error @classmethod def _create_server_thread(cls, connections_override): return cls.server_thread_class( cls.host, cls.static_handler, connections_override=connections_override, port=cls.port, ) @classmethod def _terminate_thread(cls): # Terminate the live server's thread. cls.server_thread.terminate() # Restore shared connections' non-shareability. for conn in cls.server_thread.connections_override.values(): conn.dec_thread_sharing() class SerializeMixin: """ Enforce serialization of TestCases that share a common resource. Define a common 'lockfile' for each set of TestCases to serialize. This file must exist on the filesystem. Place it early in the MRO in order to isolate setUpClass()/tearDownClass(). """ lockfile = None def __init_subclass__(cls, /, **kwargs): super().__init_subclass__(**kwargs) if cls.lockfile is None: raise ValueError( "{}.lockfile isn't set. Set it to a unique value " "in the base class.".format(cls.__name__) ) @classmethod def setUpClass(cls): cls._lockfile = open(cls.lockfile) cls.addClassCleanup(cls._lockfile.close) locks.lock(cls._lockfile, locks.LOCK_EX) super().setUpClass()
a53aa22f9a437a4191ba88b49ebba5ce1ef7c7da59aec721953056f1cda29190
from decimal import Decimal from django.conf import settings from django.utils.safestring import mark_safe def format( number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep="", force_grouping=False, use_l10n=None, ): """ Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-uniform digit grouping, it can be a sequence with the number of digit group sizes following the format used by the Python locale module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example ",") """ if number is None or number == "": return mark_safe(number) if use_l10n is None: use_l10n = True use_grouping = use_l10n and settings.USE_THOUSAND_SEPARATOR use_grouping = use_grouping or force_grouping use_grouping = use_grouping and grouping != 0 # Make the common case fast if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(number) # sign sign = "" # Treat potentially very large/small floats as Decimals. if isinstance(number, float) and "e" in str(number).lower(): number = Decimal(str(number)) if isinstance(number, Decimal): if decimal_pos is not None: # If the provided number is too small to affect any of the visible # decimal places, consider it equal to '0'. cutoff = Decimal("0." + "1".rjust(decimal_pos, "0")) if abs(number) < cutoff: number = Decimal("0") # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponent = number.as_tuple() if abs(exponent) + len(digits) > 200: number = "{:e}".format(number) coefficient, exponent = number.split("e") # Format the coefficient. coefficient = format( coefficient, decimal_sep, decimal_pos, grouping, thousand_sep, force_grouping, use_l10n, ) return "{}e{}".format(coefficient, exponent) else: str_number = "{:f}".format(number) else: str_number = str(number) if str_number[0] == "-": sign = "-" str_number = str_number[1:] # decimal part if "." in str_number: int_part, dec_part = str_number.split(".") if decimal_pos is not None: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, "" if decimal_pos is not None: dec_part += "0" * (decimal_pos - len(dec_part)) dec_part = dec_part and decimal_sep + dec_part # grouping if use_grouping: try: # if grouping is a sequence intervals = list(grouping) except TypeError: # grouping is a single value intervals = [grouping, 0] active_interval = intervals.pop(0) int_part_gd = "" cnt = 0 for digit in int_part[::-1]: if cnt and cnt == active_interval: if intervals: active_interval = intervals.pop(0) or active_interval int_part_gd += thousand_sep[::-1] cnt = 0 int_part_gd += digit cnt += 1 int_part = int_part_gd[::-1] return sign + int_part + dec_part
150aa1f8c737f27a1272245d449b6fd31256181a6cf5cab69ee5423f34653b22
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see RFC 9110 Section 12.5.5. Essentially, the "Vary" HTTP header defines which headers a cache should take into account when building its cache key. Requests with the same path but different header content for headers named in "Vary" need to get different cache keys to prevent delivery of wrong content. An example: i18n middleware would need to distinguish caches by the "Accept-language" header. """ import time from collections import defaultdict from hashlib import md5 from django.conf import settings from django.core.cache import caches from django.http import HttpResponse, HttpResponseNotModified from django.utils.http import http_date, parse_etags, parse_http_date_safe, quote_etag from django.utils.log import log_response from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import get_current_timezone_name from django.utils.translation import get_language cc_delim_re = _lazy_re_compile(r"\s*,\s*") def patch_cache_control(response, **kwargs): """ Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true value), only the parameter name is added to the header. * All other parameters are added with their value, after applying str() to it. """ def dictitem(s): t = s.split("=", 1) if len(t) > 1: return (t[0].lower(), t[1]) else: return (t[0].lower(), True) def dictvalue(*t): if t[1] is True: return t[0] else: return "%s=%s" % (t[0], t[1]) cc = defaultdict(set) if response.get("Cache-Control"): for field in cc_delim_re.split(response.headers["Cache-Control"]): directive, value = dictitem(field) if directive == "no-cache": # no-cache supports multiple field names. cc[directive].add(value) else: cc[directive] = value # If there's already a max-age header but we're being asked to set a new # max-age, use the minimum of the two ages. In practice this happens when # a decorator and a piece of middleware both operate on a given view. if "max-age" in cc and "max_age" in kwargs: kwargs["max_age"] = min(int(cc["max-age"]), kwargs["max_age"]) # Allow overriding private caching and vice versa if "private" in cc and "public" in kwargs: del cc["private"] elif "public" in cc and "private" in kwargs: del cc["public"] for (k, v) in kwargs.items(): directive = k.replace("_", "-") if directive == "no-cache": # no-cache supports multiple field names. cc[directive].add(v) else: cc[directive] = v directives = [] for directive, values in cc.items(): if isinstance(values, set): if True in values: # True takes precedence. values = {True} directives.extend([dictvalue(directive, value) for value in values]) else: directives.append(dictvalue(directive, values)) cc = ", ".join(directives) response.headers["Cache-Control"] = cc def get_max_age(response): """ Return the max-age from the response Cache-Control header as an integer, or None if it wasn't found or wasn't an integer. """ if not response.has_header("Cache-Control"): return cc = dict( _to_tuple(el) for el in cc_delim_re.split(response.headers["Cache-Control"]) ) try: return int(cc["max-age"]) except (ValueError, TypeError, KeyError): pass def set_response_etag(response): if not response.streaming and response.content: response.headers["ETag"] = quote_etag( md5(response.content, usedforsecurity=False).hexdigest(), ) return response def _precondition_failed(request): response = HttpResponse(status=412) log_response( "Precondition Failed: %s", request.path, response=response, request=request, ) return response def _not_modified(request, response=None): new_response = HttpResponseNotModified() if response: # Preserve the headers required by RFC 9110 Section 15.4.5, as well as # Last-Modified. for header in ( "Cache-Control", "Content-Location", "Date", "ETag", "Expires", "Last-Modified", "Vary", ): if header in response: new_response.headers[header] = response.headers[header] # Preserve cookies as per the cookie specification: "If a proxy server # receives a response which contains a Set-cookie header, it should # propagate the Set-cookie header to the client, regardless of whether # the response was 304 (Not Modified) or 200 (OK). # https://curl.haxx.se/rfc/cookie_spec.html new_response.cookies = response.cookies return new_response def get_conditional_response(request, etag=None, last_modified=None, response=None): # Only return conditional responses on successful requests. if response and not (200 <= response.status_code < 300): return response # Get HTTP request headers. if_match_etags = parse_etags(request.META.get("HTTP_IF_MATCH", "")) if_unmodified_since = request.META.get("HTTP_IF_UNMODIFIED_SINCE") if_unmodified_since = if_unmodified_since and parse_http_date_safe( if_unmodified_since ) if_none_match_etags = parse_etags(request.META.get("HTTP_IF_NONE_MATCH", "")) if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE") if_modified_since = if_modified_since and parse_http_date_safe(if_modified_since) # Evaluation of request preconditions below follows RFC 9110 Section # 13.2.2. # Step 1: Test the If-Match precondition. if if_match_etags and not _if_match_passes(etag, if_match_etags): return _precondition_failed(request) # Step 2: Test the If-Unmodified-Since precondition. if ( not if_match_etags and if_unmodified_since and not _if_unmodified_since_passes(last_modified, if_unmodified_since) ): return _precondition_failed(request) # Step 3: Test the If-None-Match precondition. if if_none_match_etags and not _if_none_match_passes(etag, if_none_match_etags): if request.method in ("GET", "HEAD"): return _not_modified(request, response) else: return _precondition_failed(request) # Step 4: Test the If-Modified-Since precondition. if ( not if_none_match_etags and if_modified_since and not _if_modified_since_passes(last_modified, if_modified_since) and request.method in ("GET", "HEAD") ): return _not_modified(request, response) # Step 5: Test the If-Range precondition (not supported). # Step 6: Return original response since there isn't a conditional response. return response def _if_match_passes(target_etag, etags): """ Test the If-Match comparison as defined in RFC 9110 Section 13.1.1. """ if not target_etag: # If there isn't an ETag, then there can't be a match. return False elif etags == ["*"]: # The existence of an ETag means that there is "a current # representation for the target resource", even if the ETag is weak, # so there is a match to '*'. return True elif target_etag.startswith("W/"): # A weak ETag can never strongly match another ETag. return False else: # Since the ETag is strong, this will only return True if there's a # strong match. return target_etag in etags def _if_unmodified_since_passes(last_modified, if_unmodified_since): """ Test the If-Unmodified-Since comparison as defined in RFC 9110 Section 13.1.4. """ return last_modified and last_modified <= if_unmodified_since def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in RFC 9110 Section 13.1.2. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ["*"]: # The existence of an ETag means that there is "a current # representation for the target resource", so there is a match to '*'. return False else: # The comparison should be weak, so look for a match after stripping # off any weak indicators. target_etag = target_etag.strip("W/") etags = (etag.strip("W/") for etag in etags) return target_etag not in etags def _if_modified_since_passes(last_modified, if_modified_since): """ Test the If-Modified-Since comparison as defined in RFC 9110 Section 13.1.3. """ return not last_modified or last_modified > if_modified_since def patch_response_headers(response, cache_timeout=None): """ Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS if cache_timeout < 0: cache_timeout = 0 # Can't have max-age negative if not response.has_header("Expires"): response.headers["Expires"] = http_date(time.time() + cache_timeout) patch_cache_control(response, max_age=cache_timeout) def add_never_cache_headers(response): """ Add headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) patch_cache_control( response, no_cache=True, no_store=True, must_revalidate=True, private=True ) def patch_vary_headers(response, newheaders): """ Add (or update) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". If headers contains an asterisk, then "Vary" header will consist of a single asterisk '*'. Otherwise, existing headers in "Vary" aren't removed. """ # Note that we need to keep the original order intact, because cache # implementations may rely on the order of the Vary contents in, say, # computing an MD5 hash. if response.has_header("Vary"): vary_headers = cc_delim_re.split(response.headers["Vary"]) else: vary_headers = [] # Use .lower() here so we treat headers as case-insensitive. existing_headers = {header.lower() for header in vary_headers} additional_headers = [ newheader for newheader in newheaders if newheader.lower() not in existing_headers ] vary_headers += additional_headers if "*" in vary_headers: response.headers["Vary"] = "*" else: response.headers["Vary"] = ", ".join(vary_headers) def has_vary_header(response, header_query): """ Check to see if the response has a given header name in its Vary header. """ if not response.has_header("Vary"): return False vary_headers = cc_delim_re.split(response.headers["Vary"]) existing_headers = {header.lower() for header in vary_headers} return header_query.lower() in existing_headers def _i18n_cache_key_suffix(request, cache_key): """If necessary, add the current locale or time zone to the cache key.""" if settings.USE_I18N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language # which in turn can also fall back to settings.LANGUAGE_CODE cache_key += ".%s" % getattr(request, "LANGUAGE_CODE", get_language()) if settings.USE_TZ: cache_key += ".%s" % get_current_timezone_name() return cache_key def _generate_cache_key(request, method, headerlist, key_prefix): """Return a cache key from the headers given in the header list.""" ctx = md5(usedforsecurity=False) for header in headerlist: value = request.META.get(header) if value is not None: ctx.update(value.encode()) url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) cache_key = "views.decorators.cache.cache_page.%s.%s.%s.%s" % ( key_prefix, method, url.hexdigest(), ctx.hexdigest(), ) return _i18n_cache_key_suffix(request, cache_key) def _generate_cache_header_key(key_prefix, request): """Return a cache key for the header cache.""" url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) cache_key = "views.decorators.cache.cache_header.%s.%s" % ( key_prefix, url.hexdigest(), ) return _i18n_cache_key_suffix(request, cache_key) def get_cache_key(request, key_prefix=None, method="GET", cache=None): """ Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there isn't a headerlist stored, return None, indicating that the page needs to be rebuilt. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learn what headers to take into account for some request URL from the response object. Store those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] if response.has_header("Vary"): is_accept_language_redundant = settings.USE_I18N # If i18n is used, the generated cache key will be suffixed with the # current locale. Adding the raw value of Accept-Language is redundant # in that case and would result in storing the same content under # multiple keys in the cache. See #18191 for details. headerlist = [] for header in cc_delim_re.split(response.headers["Vary"]): header = header.upper().replace("-", "_") if header != "ACCEPT_LANGUAGE" or not is_accept_language_redundant: headerlist.append("HTTP_" + header) headerlist.sort() cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, request.method, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.build_absolute_uri() cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, request.method, [], key_prefix) def _to_tuple(s): t = s.split("=", 1) if len(t) == 2: return t[0].lower(), t[1] return t[0].lower(), True
1ba651e2ad62575a14dabb6bf38be322964c15c92eb5ef8759b4bd951e0eebf9
""" HTML Widget classes """ import copy import datetime import warnings from collections import defaultdict from graphlib import CycleError, TopologicalSorter from itertools import chain from django.forms.utils import to_current_timezone from django.templatetags.static import static from django.utils import formats from django.utils.dates import MONTHS from django.utils.formats import get_format from django.utils.html import format_html, html_safe from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer __all__ = ( "Media", "MediaDefiningClass", "Widget", "TextInput", "NumberInput", "EmailInput", "URLInput", "PasswordInput", "HiddenInput", "MultipleHiddenInput", "FileInput", "ClearableFileInput", "Textarea", "DateInput", "DateTimeInput", "TimeInput", "CheckboxInput", "Select", "NullBooleanSelect", "SelectMultiple", "RadioSelect", "CheckboxSelectMultiple", "MultiWidget", "SplitDateTimeWidget", "SplitHiddenDateTimeWidget", "SelectDateWidget", ) MEDIA_TYPES = ("css", "js") class MediaOrderConflictWarning(RuntimeWarning): pass @html_safe class Media: def __init__(self, media=None, css=None, js=None): if media is not None: css = getattr(media, "css", {}) js = getattr(media, "js", []) else: if css is None: css = {} if js is None: js = [] self._css_lists = [css] self._js_lists = [js] def __repr__(self): return "Media(css=%r, js=%r)" % (self._css, self._js) def __str__(self): return self.render() @property def _css(self): css = defaultdict(list) for css_list in self._css_lists: for medium, sublist in css_list.items(): css[medium].append(sublist) return {medium: self.merge(*lists) for medium, lists in css.items()} @property def _js(self): return self.merge(*self._js_lists) def render(self): return mark_safe( "\n".join( chain.from_iterable( getattr(self, "render_" + name)() for name in MEDIA_TYPES ) ) ) def render_js(self): return [ path.__html__() if hasattr(path, "__html__") else format_html('<script src="{}"></script>', self.absolute_path(path)) for path in self._js ] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = sorted(self._css) return chain.from_iterable( [ path.__html__() if hasattr(path, "__html__") else format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), medium, ) for path in self._css[medium] ] for medium in media ) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __getitem__(self, name): """Return a Media object that only contains media of the given type.""" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, "_" + name)}) raise KeyError('Unknown media type "%s"' % name) @staticmethod def merge(*lists): """ Merge lists while trying to keep the relative order of the elements. Warn if the lists have the same elements in a different relative order. For static assets it can be important to have them included in the DOM in a certain order. In JavaScript you may not be able to reference a global or in CSS you might want to override a style. """ ts = TopologicalSorter() for head, *tail in filter(None, lists): ts.add(head) # Ensure that the first items are included. for item in tail: if head != item: # Avoid circular dependency to self. ts.add(item, head) head = item try: return list(ts.static_order()) except CycleError: warnings.warn( "Detected duplicate Media files in an opposite order: {}".format( ", ".join(repr(list_) for list_ in lists) ), MediaOrderConflictWarning, ) return list(dict.fromkeys(chain.from_iterable(filter(None, lists)))) def __add__(self, other): combined = Media() combined._css_lists = self._css_lists[:] combined._js_lists = self._js_lists[:] for item in other._css_lists: if item and item not in self._css_lists: combined._css_lists.append(item) for item in other._js_lists: if item and item not in self._js_lists: combined._js_lists.append(item) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.media except AttributeError: base = Media() # Get the media definition for this class definition = getattr(cls, "Media", None) if definition: extend = getattr(definition, "extend", True) if extend: if extend is True: m = base else: m = Media() for medium in extend: m += base[medium] return m + Media(definition) return Media(definition) return base return property(_media) class MediaDefiningClass(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True use_fieldset = False def __init__(self, attrs=None): self.attrs = {} if attrs is None else attrs.copy() def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj @property def is_hidden(self): return self.input_type == "hidden" if hasattr(self, "input_type") else False def subwidgets(self, name, value, attrs=None): context = self.get_context(name, value, attrs) yield context["widget"] def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == "" or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) def get_context(self, name, value, attrs): return { "widget": { "name": name, "is_hidden": self.is_hidden, "required": self.is_required, "value": self.format_value(value), "attrs": self.build_attrs(self.attrs, attrs), "template_name": self.template_name, }, } def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" return {**base_attrs, **(extra_attrs or {})} def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ return data.get(name) def value_omitted_from_data(self, data, files, name): return name not in data def id_for_label(self, id_): """ Return the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Return an empty string if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ def use_required_attribute(self, initial): return not self.is_hidden class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = "django/forms/widgets/input.html" def __init__(self, attrs=None): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop("type", self.input_type) super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["type"] = self.input_type return context class TextInput(Input): input_type = "text" template_name = "django/forms/widgets/text.html" class NumberInput(Input): input_type = "number" template_name = "django/forms/widgets/number.html" class EmailInput(Input): input_type = "email" template_name = "django/forms/widgets/email.html" class URLInput(Input): input_type = "url" template_name = "django/forms/widgets/url.html" class PasswordInput(Input): input_type = "password" template_name = "django/forms/widgets/password.html" def __init__(self, attrs=None, render_value=False): super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None return super().get_context(name, value, attrs) class HiddenInput(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html" class MultipleHiddenInput(HiddenInput): """ Handle <input type="hidden"> for fields that have a list of values. """ template_name = "django/forms/widgets/multiple_hidden.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) final_attrs = context["widget"]["attrs"] id_ = context["widget"]["attrs"].get("id") subwidgets = [] for index, value_ in enumerate(context["widget"]["value"]): widget_attrs = final_attrs.copy() if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. widget_attrs["id"] = "%s_%s" % (id_, index) widget = HiddenInput() widget.is_required = self.is_required subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"]) context["widget"]["subwidgets"] = subwidgets return context def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def format_value(self, value): return [] if value is None else value class FileInput(Input): input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def format_value(self, value): """File input never renders a value.""" return def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" return files.get(name) def value_omitted_from_data(self, data, files, name): return name not in files def use_required_attribute(self, initial): return super().use_required_attribute(initial) and not initial FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + "-clear" def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + "_id" def is_initial(self, value): """ Return whether value is considered to be initial value. """ return bool(value and getattr(value, "url", False)) def format_value(self, value): """ Return the file object if it has a defined url attribute. """ if self.is_initial(value): return value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context["widget"].update( { "checkbox_name": checkbox_name, "checkbox_id": checkbox_id, "is_initial": self.is_initial(value), "input_text": self.input_text, "initial_text": self.initial_text, "clear_checkbox_label": self.clear_checkbox_label, } ) context["widget"]["attrs"].setdefault("disabled", False) return context def value_from_datadict(self, data, files, name): upload = super().value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name) ): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload def value_omitted_from_data(self, data, files, name): return ( super().value_omitted_from_data(data, files, name) and self.clear_checkbox_name(name) not in data ) class Textarea(Widget): template_name = "django/forms/widgets/textarea.html" def __init__(self, attrs=None): # Use slightly better defaults than HTML's 20x2 box default_attrs = {"cols": "40", "rows": "10"} if attrs: default_attrs.update(attrs) super().__init__(default_attrs) class DateTimeBaseInput(TextInput): format_key = "" supports_microseconds = False def __init__(self, attrs=None, format=None): super().__init__(attrs) self.format = format or None def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0] ) class DateInput(DateTimeBaseInput): format_key = "DATE_INPUT_FORMATS" template_name = "django/forms/widgets/date.html" class DateTimeInput(DateTimeBaseInput): format_key = "DATETIME_INPUT_FORMATS" template_name = "django/forms/widgets/datetime.html" class TimeInput(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "") class CheckboxInput(Input): input_type = "checkbox" template_name = "django/forms/widgets/checkbox.html" def __init__(self, attrs=None, check_test=None): super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test def format_value(self, value): """Only return the 'value' attribute if value isn't empty.""" if value is True or value is False or value is None or value == "": return return str(value) def get_context(self, name, value, attrs): if self.check_test(value): attrs = {**(attrs or {}), "checked": True} return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {"true": True, "false": False} if isinstance(value, str): value = values.get(value.lower(), value) return bool(value) def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class ChoiceWidget(Widget): allow_multiple_selected = False input_type = None template_name = None option_template_name = None add_id_index = True checked_attribute = {"checked": True} option_inherits_attrs = True def __init__(self, attrs=None, choices=()): super().__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() obj.choices = copy.copy(self.choices) memo[id(self)] = obj return obj def subwidgets(self, name, value, attrs=None): """ Yield all "subwidgets" of this widget. Used to enable iterating options from a BoundField for choice widgets. """ value = self.format_value(value) yield from self.options(name, value, attrs) def options(self, name, value, attrs=None): """Yield a flat list of options for this widget.""" for group in self.optgroups(name, value, attrs): yield from group[1] def optgroups(self, name, value, attrs=None): """Return a list of optgroups for this widget.""" groups = [] has_selected = False for index, (option_value, option_label) in enumerate(self.choices): if option_value is None: option_value = "" subgroup = [] if isinstance(option_label, (list, tuple)): group_name = option_value subindex = 0 choices = option_label else: group_name = None subindex = None choices = [(option_value, option_label)] groups.append((group_name, subgroup, index)) for subvalue, sublabel in choices: selected = (not has_selected or self.allow_multiple_selected) and str( subvalue ) in value has_selected |= selected subgroup.append( self.create_option( name, subvalue, sublabel, selected, index, subindex=subindex, attrs=attrs, ) ) if subindex is not None: subindex += 1 return groups def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): index = str(index) if subindex is None else "%s_%s" % (index, subindex) option_attrs = ( self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} ) if selected: option_attrs.update(self.checked_attribute) if "id" in option_attrs: option_attrs["id"] = self.id_for_label(option_attrs["id"], index) return { "name": name, "value": value, "label": label, "selected": selected, "index": index, "attrs": option_attrs, "type": self.input_type, "template_name": self.option_template_name, "wrap_label": True, } def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["optgroups"] = self.optgroups( name, context["widget"]["value"], attrs ) return context def id_for_label(self, id_, index="0"): """ Use an incremented id for each option where the main widget references the zero index. """ if id_ and self.add_id_index: id_ = "%s_%s" % (id_, index) return id_ def value_from_datadict(self, data, files, name): getter = data.get if self.allow_multiple_selected: try: getter = data.getlist except AttributeError: pass return getter(name) def format_value(self, value): """Return selected values as a list.""" if value is None and self.allow_multiple_selected: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else "" for v in value] class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context["widget"]["attrs"]["multiple"] = True return context @staticmethod def _choice_has_empty_value(choice): """Return True if the choice's value is empty string or None.""" value, _ = choice return value is None or value == "" def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return ( use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) ) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ( ("unknown", _("Unknown")), ("true", _("Yes")), ("false", _("No")), ) super().__init__(attrs, choices) def format_value(self, value): try: return { True: "true", False: "false", "true": "true", "false": "false", # For backwards compatibility with Django < 2.2. "2": "true", "3": "false", }[value] except KeyError: return "unknown" def value_from_datadict(self, data, files, name): value = data.get(name) return { True: True, "True": True, "False": False, False: False, "true": True, "false": False, # For backwards compatibility with Django < 2.2. "2": True, "3": False, }.get(value) class SelectMultiple(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False class RadioSelect(ChoiceWidget): input_type = "radio" template_name = "django/forms/widgets/radio.html" option_template_name = "django/forms/widgets/radio_option.html" use_fieldset = True def id_for_label(self, id_, index=None): """ Don't include for="field_0" in <label> to improve accessibility when using a screen reader, in addition clicking such a label would toggle the first input. """ if index is None: return "" return super().id_for_label(id_, index) class CheckboxSelectMultiple(RadioSelect): allow_multiple_selected = True input_type = "checkbox" template_name = "django/forms/widgets/checkbox_select.html" option_template_name = "django/forms/widgets/checkbox_option.html" def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class MultiWidget(Widget): """ A widget that is composed of multiple widgets. In addition to the values added by Widget.get_context(), this widget adds a list of subwidgets to the context as widget['subwidgets']. These can be looped over and rendered like normal widgets. You'll probably want to use this class with MultiValueField. """ template_name = "django/forms/widgets/multiwidget.html" use_fieldset = True def __init__(self, widgets, attrs=None): if isinstance(widgets, dict): self.widgets_names = [("_%s" % name) if name else "" for name in widgets] widgets = widgets.values() else: self.widgets_names = ["_%s" % i for i in range(len(widgets))] self.widgets = [w() if isinstance(w, type) else w for w in widgets] super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list/tuple of values, each corresponding to a widget # in self.widgets. if not isinstance(value, (list, tuple)): value = self.decompress(value) final_attrs = context["widget"]["attrs"] input_type = final_attrs.pop("type", None) id_ = final_attrs.get("id") subwidgets = [] for i, (widget_name, widget) in enumerate( zip(self.widgets_names, self.widgets) ): if input_type is not None: widget.input_type = input_type widget_name = name + widget_name try: widget_value = value[i] except IndexError: widget_value = None if id_: widget_attrs = final_attrs.copy() widget_attrs["id"] = "%s_%s" % (id_, i) else: widget_attrs = final_attrs subwidgets.append( widget.get_context(widget_name, widget_value, widget_attrs)["widget"] ) context["widget"]["subwidgets"] = subwidgets return context def id_for_label(self, id_): return "" def value_from_datadict(self, data, files, name): return [ widget.value_from_datadict(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ] def value_omitted_from_data(self, data, files, name): return all( widget.value_omitted_from_data(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ) def decompress(self, value): """ Return a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError("Subclasses must implement this method.") def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = Media() for w in self.widgets: media += w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super().__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj @property def needs_multipart_form(self): return any(w.needs_multipart_form for w in self.widgets) class SplitDateTimeWidget(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): widgets = ( DateInput( attrs=attrs if date_attrs is None else date_attrs, format=date_format, ), TimeInput( attrs=attrs if time_attrs is None else time_attrs, format=time_format, ), ) super().__init__(widgets) def decompress(self, value): if value: value = to_current_timezone(value) return [value.date(), value.time()] return [None, None] class SplitHiddenDateTimeWidget(SplitDateTimeWidget): """ A widget that splits datetime input into two <input type="hidden"> inputs. """ template_name = "django/forms/widgets/splithiddendatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): super().__init__(attrs, date_format, time_format, date_attrs, time_attrs) for widget in self.widgets: widget.input_type = "hidden" class SelectDateWidget(Widget): """ A widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = ("", "---") month_field = "%s_month" day_field = "%s_day" year_field = "%s_year" template_name = "django/forms/widgets/select_date.html" input_type = "select" select_widget = Select date_re = _lazy_re_compile(r"(\d{4}|0)-(\d\d?)-(\d\d?)$") use_fieldset = True def __init__(self, attrs=None, years=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional list or tuple of years to use in the "year" select box. if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10) # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError("empty_label list/tuple must have 3 elements.") self.year_none_value = ("", empty_label[0]) self.month_none_value = ("", empty_label[1]) self.day_none_value = ("", empty_label[2]) else: if empty_label is not None: self.none_value = ("", empty_label) self.year_none_value = self.none_value self.month_none_value = self.none_value self.day_none_value = self.none_value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) date_context = {} year_choices = [(i, str(i)) for i in self.years] if not self.is_required: year_choices.insert(0, self.year_none_value) year_name = self.year_field % name date_context["year"] = self.select_widget( attrs, choices=year_choices ).get_context( name=year_name, value=context["widget"]["value"]["year"], attrs={**context["widget"]["attrs"], "id": "id_%s" % year_name}, ) month_choices = list(self.months.items()) if not self.is_required: month_choices.insert(0, self.month_none_value) month_name = self.month_field % name date_context["month"] = self.select_widget( attrs, choices=month_choices ).get_context( name=month_name, value=context["widget"]["value"]["month"], attrs={**context["widget"]["attrs"], "id": "id_%s" % month_name}, ) day_choices = [(i, i) for i in range(1, 32)] if not self.is_required: day_choices.insert(0, self.day_none_value) day_name = self.day_field % name date_context["day"] = self.select_widget( attrs, choices=day_choices, ).get_context( name=day_name, value=context["widget"]["value"]["day"], attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name}, ) subwidgets = [] for field in self._parse_date_fmt(): subwidgets.append(date_context[field]["widget"]) context["widget"]["subwidgets"] = subwidgets return context def format_value(self, value): """ Return a dict containing the year, month, and day of the current value. Use dict instead of a datetime to allow invalid dates such as February 31 to display correctly. """ year, month, day = None, None, None if isinstance(value, (datetime.date, datetime.datetime)): year, month, day = value.year, value.month, value.day elif isinstance(value, str): match = self.date_re.match(value) if match: # Convert any zeros in the date to empty strings to match the # empty option value. year, month, day = [int(val) or "" for val in match.groups()] else: input_format = get_format("DATE_INPUT_FORMATS")[0] try: d = datetime.datetime.strptime(value, input_format) except ValueError: pass else: year, month, day = d.year, d.month, d.day return {"year": year, "month": month, "day": day} @staticmethod def _parse_date_fmt(): fmt = get_format("DATE_FORMAT") escaped = False for char in fmt: if escaped: escaped = False elif char == "\\": escaped = True elif char in "Yy": yield "year" elif char in "bEFMmNn": yield "month" elif char in "dj": yield "day" def id_for_label(self, id_): for first_select in self._parse_date_fmt(): return "%s_%s" % (id_, first_select) return "%s_month" % id_ def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "": return None if y is not None and m is not None and d is not None: input_format = get_format("DATE_INPUT_FORMATS")[0] input_format = formats.sanitize_strftime_format(input_format) try: date_value = datetime.date(int(y), int(m), int(d)) except ValueError: # Return pseudo-ISO dates with zeros for any unselected values, # e.g. '2017-0-23'. return "%s-%s-%s" % (y or 0, m or 0, d or 0) return date_value.strftime(input_format) return data.get(name) def value_omitted_from_data(self, data, files, name): return not any( ("{}_{}".format(name, interval) in data) for interval in ("year", "month", "day") )
e07489b24373a80435c15e7e5c7138eeefea2069ae3a9f75137ffc76b21139f9
from pathlib import Path import jinja2 from django.conf import settings from django.template import TemplateDoesNotExist, TemplateSyntaxError from django.utils.functional import cached_property from django.utils.module_loading import import_string from .base import BaseEngine from .utils import csrf_input_lazy, csrf_token_lazy class Jinja2(BaseEngine): app_dirname = "jinja2" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() super().__init__(params) self.context_processors = options.pop("context_processors", []) environment = options.pop("environment", "jinja2.Environment") environment_cls = import_string(environment) if "loader" not in options: options["loader"] = jinja2.FileSystemLoader(self.template_dirs) options.setdefault("autoescape", True) options.setdefault("auto_reload", settings.DEBUG) options.setdefault( "undefined", jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined ) self.env = environment_cls(**options) def from_string(self, template_code): return Template(self.env.from_string(template_code), self) def get_template(self, template_name): try: return Template(self.env.get_template(template_name), self) except jinja2.TemplateNotFound as exc: raise TemplateDoesNotExist(exc.name, backend=self) from exc except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) raise new from exc @cached_property def template_context_processors(self): return [import_string(path) for path in self.context_processors] class Template: def __init__(self, template, backend): self.template = template self.backend = backend self.origin = Origin( name=template.filename, template_name=template.name, ) def render(self, context=None, request=None): if context is None: context = {} if request is not None: context["request"] = request context["csrf_input"] = csrf_input_lazy(request) context["csrf_token"] = csrf_token_lazy(request) for context_processor in self.backend.template_context_processors: context.update(context_processor(request)) try: return self.template.render(context) except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) raise new from exc class Origin: """ A container to hold debug information as described in the template API documentation. """ def __init__(self, name, template_name): self.name = name self.template_name = template_name def get_exception_info(exception): """ Format exception information for display on the debug page using the structure described in the template API documentation. """ context_lines = 10 lineno = exception.lineno source = exception.source if source is None: exception_file = Path(exception.filename) if exception_file.exists(): source = exception_file.read_text() if source is not None: lines = list(enumerate(source.strip().split("\n"), start=1)) during = lines[lineno - 1][1] total = len(lines) top = max(0, lineno - context_lines - 1) bottom = min(total, lineno + context_lines) else: during = "" lines = [] total = top = bottom = 0 return { "name": exception.filename, "message": exception.message, "source_lines": lines[top:bottom], "line": lineno, "before": "", "during": during, "after": "", "total": total, "top": top, "bottom": bottom, }
4cbe9f55b472ffdb5e73c366d47e28297f7bdcd058eed00def4faccf30c53684
from importlib import import_module from pkgutil import walk_packages from django.apps import apps from django.conf import settings from django.template import TemplateDoesNotExist from django.template.context import make_context from django.template.engine import Engine from django.template.library import InvalidTemplateLibrary from .base import BaseEngine class DjangoTemplates(BaseEngine): app_dirname = "templates" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() options.setdefault("autoescape", True) options.setdefault("debug", settings.DEBUG) options.setdefault("file_charset", "utf-8") libraries = options.get("libraries", {}) options["libraries"] = self.get_templatetag_libraries(libraries) super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code), self) def get_template(self, template_name): try: return Template(self.engine.get_template(template_name), self) except TemplateDoesNotExist as exc: reraise(exc, self) def get_templatetag_libraries(self, custom_libraries): """ Return a collation of template tag libraries from installed applications and the supplied custom_libraries argument. """ libraries = get_installed_libraries() libraries.update(custom_libraries) return libraries class Template: def __init__(self, template, backend): self.template = template self.backend = backend @property def origin(self): return self.template.origin def render(self, context=None, request=None): context = make_context( context, request, autoescape=self.backend.engine.autoescape ) try: return self.template.render(context) except TemplateDoesNotExist as exc: reraise(exc, self.backend) def copy_exception(exc, backend=None): """ Create a new TemplateDoesNotExist. Preserve its declared attributes and template debug data but discard __traceback__, __context__, and __cause__ to make this object suitable for keeping around (in a cache, for example). """ backend = backend or exc.backend new = exc.__class__(*exc.args, tried=exc.tried, backend=backend, chain=exc.chain) if hasattr(exc, "template_debug"): new.template_debug = exc.template_debug return new def reraise(exc, backend): """ Reraise TemplateDoesNotExist while maintaining template debug information. """ new = copy_exception(exc, backend) raise new from exc def get_template_tag_modules(): """ Yield (module_name, module_path) pairs for all installed template tag libraries. """ candidates = ["django.templatetags"] candidates.extend( f"{app_config.name}.templatetags" for app_config in apps.get_app_configs() ) for candidate in candidates: try: pkg = import_module(candidate) except ImportError: # No templatetags package defined. This is safe to ignore. continue if hasattr(pkg, "__path__"): for name in get_package_libraries(pkg): yield name.removeprefix(candidate).lstrip("."), name def get_installed_libraries(): """ Return the built-in template tag libraries and those from installed applications. Libraries are stored in a dictionary where keys are the individual module names, not the full module paths. Example: django.templatetags.i18n is stored as i18n. """ return { module_name: full_name for module_name, full_name in get_template_tag_modules() } def get_package_libraries(pkg): """ Recursively yield template tag libraries defined in submodules of a package. """ for entry in walk_packages(pkg.__path__, pkg.__name__ + "."): try: module = import_module(entry[1]) except ImportError as e: raise InvalidTemplateLibrary( "Invalid template library specified. ImportError raised when " "trying to load '%s': %s" % (entry[1], e) ) from e if hasattr(module, "register"): yield entry[1]
a189f7a1fb4cb17ba66382e2a9b4647d0c7f73a4cbfce8ca63ac67281287c347
""" The main QuerySet implementation. This provides the public API for the ORM. """ import copy import operator import warnings from itertools import chain, islice from asgiref.sync import sync_to_async import django from django.conf import settings from django.core import exceptions from django.db import ( DJANGO_VERSION_PICKLE_KEY, IntegrityError, NotSupportedError, connections, router, transaction, ) from django.db.models import AutoField, DateField, DateTimeField, Field, sql from django.db.models.constants import LOOKUP_SEP, OnConflict from django.db.models.deletion import Collector from django.db.models.expressions import Case, F, Value, When from django.db.models.functions import Cast, Trunc from django.db.models.query_utils import FilteredRelation, Q from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE from django.db.models.utils import ( AltersData, create_namedtuple_class, resolve_callables, ) from django.utils import timezone from django.utils.functional import cached_property, partition # The maximum number of results to fetch in a get() query. MAX_GET_RESULTS = 21 # The maximum number of items to display in a QuerySet.__repr__ REPR_OUTPUT_SIZE = 20 class BaseIterable: def __init__( self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): self.queryset = queryset self.chunked_fetch = chunked_fetch self.chunk_size = chunk_size async def _async_generator(self): # Generators don't actually start running until the first time you call # next() on them, so make the generator object in the async thread and # then repeatedly dispatch to it in a sync thread. sync_generator = self.__iter__() def next_slice(gen): return list(islice(gen, self.chunk_size)) while True: chunk = await sync_to_async(next_slice)(sync_generator) for item in chunk: yield item if len(chunk) < self.chunk_size: break # __aiter__() is a *synchronous* method that has to then return an # *asynchronous* iterator/generator. Thus, nest an async generator inside # it. # This is a generic iterable converter for now, and is going to suffer a # performance penalty on large sets of items due to the cost of crossing # over the sync barrier for each chunk. Custom __aiter__() methods should # be added to each Iterable subclass, but that needs some work in the # Compiler first. def __aiter__(self): return self._async_generator() class ModelIterable(BaseIterable): """Iterable that yields a model instance for each row.""" def __iter__(self): queryset = self.queryset db = queryset.db compiler = queryset.query.get_compiler(using=db) # Execute the query. This will also fill compiler.select, klass_info, # and annotations. results = compiler.execute_sql( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ) select, klass_info, annotation_col_map = ( compiler.select, compiler.klass_info, compiler.annotation_col_map, ) model_cls = klass_info["model"] select_fields = klass_info["select_fields"] model_fields_start, model_fields_end = select_fields[0], select_fields[-1] + 1 init_list = [ f[0].target.attname for f in select[model_fields_start:model_fields_end] ] related_populators = get_related_populators(klass_info, select, db) known_related_objects = [ ( field, related_objs, operator.attrgetter( *[ field.attname if from_field == "self" else queryset.model._meta.get_field(from_field).attname for from_field in field.from_fields ] ), ) for field, related_objs in queryset._known_related_objects.items() ] for row in compiler.results_iter(results): obj = model_cls.from_db( db, init_list, row[model_fields_start:model_fields_end] ) for rel_populator in related_populators: rel_populator.populate(row, obj) if annotation_col_map: for attr_name, col_pos in annotation_col_map.items(): setattr(obj, attr_name, row[col_pos]) # Add the known related objects to the model. for field, rel_objs, rel_getter in known_related_objects: # Avoid overwriting objects loaded by, e.g., select_related(). if field.is_cached(obj): continue rel_obj_id = rel_getter(obj) try: rel_obj = rel_objs[rel_obj_id] except KeyError: pass # May happen in qs1 | qs2 scenarios. else: setattr(obj, field.name, rel_obj) yield obj class RawModelIterable(BaseIterable): """ Iterable that yields a model instance for each row from a raw queryset. """ def __iter__(self): # Cache some things for performance reasons outside the loop. db = self.queryset.db query = self.queryset.query connection = connections[db] compiler = connection.ops.compiler("SQLCompiler")(query, connection, db) query_iterator = iter(query) try: ( model_init_names, model_init_pos, annotation_fields, ) = self.queryset.resolve_model_init_order() model_cls = self.queryset.model if model_cls._meta.pk.attname not in model_init_names: raise exceptions.FieldDoesNotExist( "Raw query must include the primary key" ) fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns] converters = compiler.get_converters( [f.get_col(f.model._meta.db_table) if f else None for f in fields] ) if converters: query_iterator = compiler.apply_converters(query_iterator, converters) for values in query_iterator: # Associate fields to values model_init_values = [values[pos] for pos in model_init_pos] instance = model_cls.from_db(db, model_init_names, model_init_values) if annotation_fields: for column, pos in annotation_fields: setattr(instance, column, values[pos]) yield instance finally: # Done iterating the Query. If it has its own cursor, close it. if hasattr(query, "cursor") and query.cursor: query.cursor.close() class ValuesIterable(BaseIterable): """ Iterable returned by QuerySet.values() that yields a dict for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] indexes = range(len(names)) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield {names[i]: row[i] for i in indexes} class ValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=False) that yields a tuple for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) if queryset._fields: # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] fields = [ *queryset._fields, *(f for f in query.annotation_select if f not in queryset._fields), ] if fields != names: # Reorder according to fields. index_map = {name: idx for idx, name in enumerate(names)} rowfactory = operator.itemgetter(*[index_map[f] for f in fields]) return map( rowfactory, compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ), ) return compiler.results_iter( tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size, ) class NamedValuesListIterable(ValuesListIterable): """ Iterable returned by QuerySet.values_list(named=True) that yields a namedtuple for each row. """ def __iter__(self): queryset = self.queryset if queryset._fields: names = queryset._fields else: query = queryset.query names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] tuple_class = create_namedtuple_class(*names) new = tuple.__new__ for row in super().__iter__(): yield new(tuple_class, row) class FlatValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=True) that yields single values. """ def __iter__(self): queryset = self.queryset compiler = queryset.query.get_compiler(queryset.db) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield row[0] class QuerySet(AltersData): """Represent a lazy database lookup for a set of objects.""" def __init__(self, model=None, query=None, using=None, hints=None): self.model = model self._db = using self._hints = hints or {} self._query = query or sql.Query(self.model) self._result_cache = None self._sticky_filter = False self._for_write = False self._prefetch_related_lookups = () self._prefetch_done = False self._known_related_objects = {} # {rel_field: {pk: rel_obj}} self._iterable_class = ModelIterable self._fields = None self._defer_next_filter = False self._deferred_filter = None @property def query(self): if self._deferred_filter: negate, args, kwargs = self._deferred_filter self._filter_or_exclude_inplace(negate, args, kwargs) self._deferred_filter = None return self._query @query.setter def query(self, value): if value.values_select: self._iterable_class = ValuesIterable self._query = value def as_manager(cls): # Address the circular dependency between `Queryset` and `Manager`. from django.db.models.manager import Manager manager = Manager.from_queryset(cls)() manager._built_with_as_manager = True return manager as_manager.queryset_only = True as_manager = classmethod(as_manager) ######################## # PYTHON MAGIC METHODS # ######################## def __deepcopy__(self, memo): """Don't populate the QuerySet's cache.""" obj = self.__class__() for k, v in self.__dict__.items(): if k == "_result_cache": obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return obj def __getstate__(self): # Force the cache to be fully populated. self._fetch_all() return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__} def __setstate__(self, state): pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: if pickled_version != django.__version__: warnings.warn( "Pickled queryset instance's Django version %s does not " "match the current version %s." % (pickled_version, django.__version__), RuntimeWarning, stacklevel=2, ) else: warnings.warn( "Pickled queryset instance's Django version is not specified.", RuntimeWarning, stacklevel=2, ) self.__dict__.update(state) def __repr__(self): data = list(self[: REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." return "<%s %r>" % (self.__class__.__name__, data) def __len__(self): self._fetch_all() return len(self._result_cache) def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql.compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects. """ self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def __bool__(self): self._fetch_all() return bool(self._result_cache) def __getitem__(self, k): """Retrieve an item or slice from the set of results.""" if not isinstance(k, (int, slice)): raise TypeError( "QuerySet indices must be integers or slices, not %s." % type(k).__name__ ) if (isinstance(k, int) and k < 0) or ( isinstance(k, slice) and ( (k.start is not None and k.start < 0) or (k.stop is not None and k.stop < 0) ) ): raise ValueError("Negative indexing is not supported.") if self._result_cache is not None: return self._result_cache[k] if isinstance(k, slice): qs = self._chain() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return list(qs)[:: k.step] if k.step else qs qs = self._chain() qs.query.set_limits(k, k + 1) qs._fetch_all() return qs._result_cache[0] def __class_getitem__(cls, *args, **kwargs): return cls def __and__(self, other): self._check_operator_queryset(other, "&") self._merge_sanity_check(other) if isinstance(other, EmptyQuerySet): return other if isinstance(self, EmptyQuerySet): return self combined = self._chain() combined._merge_known_related_objects(other) combined.query.combine(other.query, sql.AND) return combined def __or__(self, other): self._check_operator_queryset(other, "|") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.OR) return combined def __xor__(self, other): self._check_operator_queryset(other, "^") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.XOR) return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def _iterator(self, use_chunked_fetch, chunk_size): iterable = self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size or 2000, ) if not self._prefetch_related_lookups or chunk_size is None: yield from iterable return iterator = iter(iterable) while results := list(islice(iterator, chunk_size)): prefetch_related_objects(results, *self._prefetch_related_lookups) yield from results def iterator(self, chunk_size=None): """ An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied. """ if chunk_size is None: if self._prefetch_related_lookups: raise ValueError( "chunk_size must be provided when using QuerySet.iterator() after " "prefetch_related()." ) elif chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) return self._iterator(use_chunked_fetch, chunk_size) async def aiterator(self, chunk_size=2000): """ An asynchronous iterator over the results from applying this QuerySet to the database. """ if self._prefetch_related_lookups: raise NotSupportedError( "Using QuerySet.aiterator() after prefetch_related() is not supported." ) if chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) async for item in self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size ): yield item def aggregate(self, *args, **kwargs): """ Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") self._validate_values_are_expressions( (*args, *kwargs.values()), method_name="aggregate" ) for arg in args: # The default_alias property raises TypeError if default_alias # can't be set automatically or AttributeError if it isn't an # attribute. try: arg.default_alias except (AttributeError, TypeError): raise TypeError("Complex aggregates require an alias") kwargs[arg.default_alias] = arg return self.query.chain().get_aggregation(self.db, kwargs) async def aaggregate(self, *args, **kwargs): return await sync_to_async(self.aggregate)(*args, **kwargs) def count(self): """ Perform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None: return len(self._result_cache) return self.query.get_count(using=self.db) async def acount(self): return await sync_to_async(self.count)() def get(self, *args, **kwargs): """ Perform the query and return a single object matching the given keyword arguments. """ if self.query.combinator and (args or kwargs): raise NotSupportedError( "Calling QuerySet.get(...) with filters after %s() is not " "supported." % self.query.combinator ) clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() limit = None if ( not clone.query.select_for_update or connections[clone.db].features.supports_select_for_update_with_limit ): limit = MAX_GET_RESULTS clone.query.set_limits(high=limit) num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist( "%s matching query does not exist." % self.model._meta.object_name ) raise self.model.MultipleObjectsReturned( "get() returned more than one %s -- it returned %s!" % ( self.model._meta.object_name, num if not limit or num < limit else "more than %s" % (limit - 1), ) ) async def aget(self, *args, **kwargs): return await sync_to_async(self.get)(*args, **kwargs) def create(self, **kwargs): """ Create a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj async def acreate(self, **kwargs): return await sync_to_async(self.create)(**kwargs) def _prepare_for_bulk_create(self, objs): for obj in objs: if obj.pk is None: # Populate new PK values. obj.pk = obj._meta.pk.get_pk_value_on_save(obj) obj._prepare_related_fields_for_save(operation_name="bulk_create") def _check_bulk_create_options( self, ignore_conflicts, update_conflicts, update_fields, unique_fields ): if ignore_conflicts and update_conflicts: raise ValueError( "ignore_conflicts and update_conflicts are mutually exclusive." ) db_features = connections[self.db].features if ignore_conflicts: if not db_features.supports_ignore_conflicts: raise NotSupportedError( "This database backend does not support ignoring conflicts." ) return OnConflict.IGNORE elif update_conflicts: if not db_features.supports_update_conflicts: raise NotSupportedError( "This database backend does not support updating conflicts." ) if not update_fields: raise ValueError( "Fields that will be updated when a row insertion fails " "on conflicts must be provided." ) if unique_fields and not db_features.supports_update_conflicts_with_target: raise NotSupportedError( "This database backend does not support updating " "conflicts with specifying unique fields that can trigger " "the upsert." ) if not unique_fields and db_features.supports_update_conflicts_with_target: raise ValueError( "Unique fields that can trigger the upsert must be provided." ) # Updating primary keys and non-concrete fields is forbidden. if any(not f.concrete or f.many_to_many for f in update_fields): raise ValueError( "bulk_create() can only be used with concrete fields in " "update_fields." ) if any(f.primary_key for f in update_fields): raise ValueError( "bulk_create() cannot be used with primary keys in " "update_fields." ) if unique_fields: if any(not f.concrete or f.many_to_many for f in unique_fields): raise ValueError( "bulk_create() can only be used with concrete fields " "in unique_fields." ) return OnConflict.UPDATE return None def bulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): """ Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported. """ # When you bulk insert you don't get the primary keys back (if it's an # autoincrement, except if can_return_rows_from_bulk_insert=True), so # you can't insert into the child tables which references this. There # are two workarounds: # 1) This could be implemented if you didn't have an autoincrement pk # 2) You could do it by doing O(n) normal inserts into the parent # tables to get the primary keys back and then doing a single bulk # insert into the childmost table. # We currently set the primary keys on the objects when using # PostgreSQL via the RETURNING ID clause. It should be possible for # Oracle as well, but the semantics for extracting the primary keys is # trickier so it's not done yet. if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") # Check that the parents share the same concrete model with the our # model to detect the inheritance pattern ConcreteGrandParent -> # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy # would not identify that case as involving multiple tables. for parent in self.model._meta.get_parent_list(): if parent._meta.concrete_model is not self.model._meta.concrete_model: raise ValueError("Can't bulk create a multi-table inherited model") if not objs: return objs opts = self.model._meta if unique_fields: # Primary key is allowed in unique_fields. unique_fields = [ self.model._meta.get_field(opts.pk.name if name == "pk" else name) for name in unique_fields ] if update_fields: update_fields = [self.model._meta.get_field(name) for name in update_fields] on_conflict = self._check_bulk_create_options( ignore_conflicts, update_conflicts, update_fields, unique_fields, ) self._for_write = True fields = opts.concrete_fields objs = list(objs) self._prepare_for_bulk_create(objs) with transaction.atomic(using=self.db, savepoint=False): objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs) if objs_with_pk: returned_columns = self._batched_insert( objs_with_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) for obj_with_pk, results in zip(objs_with_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): if field != opts.pk: setattr(obj_with_pk, field.attname, result) for obj_with_pk in objs_with_pk: obj_with_pk._state.adding = False obj_with_pk._state.db = self.db if objs_without_pk: fields = [f for f in fields if not isinstance(f, AutoField)] returned_columns = self._batched_insert( objs_without_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) connection = connections[self.db] if ( connection.features.can_return_rows_from_bulk_insert and on_conflict is None ): assert len(returned_columns) == len(objs_without_pk) for obj_without_pk, results in zip(objs_without_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): setattr(obj_without_pk, field.attname, result) obj_without_pk._state.adding = False obj_without_pk._state.db = self.db return objs async def abulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): return await sync_to_async(self.bulk_create)( objs=objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts, update_conflicts=update_conflicts, update_fields=update_fields, unique_fields=unique_fields, ) def bulk_update(self, objs, fields, batch_size=None): """ Update the given fields in each of the given objects in the database. """ if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") if not fields: raise ValueError("Field names must be given to bulk_update().") objs = tuple(objs) if any(obj.pk is None for obj in objs): raise ValueError("All bulk_update() objects must have a primary key set.") fields = [self.model._meta.get_field(name) for name in fields] if any(not f.concrete or f.many_to_many for f in fields): raise ValueError("bulk_update() can only be used with concrete fields.") if any(f.primary_key for f in fields): raise ValueError("bulk_update() cannot be used with primary key fields.") if not objs: return 0 for obj in objs: obj._prepare_related_fields_for_save( operation_name="bulk_update", fields=fields ) # PK is used twice in the resulting update query, once in the filter # and once in the WHEN. Each field will also have one CAST. self._for_write = True connection = connections[self.db] max_batch_size = connection.ops.bulk_batch_size(["pk", "pk"] + fields, objs) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size requires_casting = connection.features.requires_casted_case_in_updates batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size)) updates = [] for batch_objs in batches: update_kwargs = {} for field in fields: when_statements = [] for obj in batch_objs: attr = getattr(obj, field.attname) if not hasattr(attr, "resolve_expression"): attr = Value(attr, output_field=field) when_statements.append(When(pk=obj.pk, then=attr)) case_statement = Case(*when_statements, output_field=field) if requires_casting: case_statement = Cast(case_statement, output_field=field) update_kwargs[field.attname] = case_statement updates.append(([obj.pk for obj in batch_objs], update_kwargs)) rows_updated = 0 queryset = self.using(self.db) with transaction.atomic(using=self.db, savepoint=False): for pks, update_kwargs in updates: rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs) return rows_updated bulk_update.alters_data = True async def abulk_update(self, objs, fields, batch_size=None): return await sync_to_async(self.bulk_update)( objs=objs, fields=fields, batch_size=batch_size, ) abulk_update.alters_data = True def get_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. """ # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: return self.get(**kwargs), False except self.model.DoesNotExist: params = self._extract_model_params(defaults, **kwargs) # Try to create an object using passed params. try: with transaction.atomic(using=self.db): params = dict(resolve_callables(params)) return self.create(**params), True except IntegrityError: try: return self.get(**kwargs), False except self.model.DoesNotExist: pass raise async def aget_or_create(self, defaults=None, **kwargs): return await sync_to_async(self.get_or_create)( defaults=defaults, **kwargs, ) def update_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Return a tuple (object, created), where created is a boolean specifying whether an object was created. """ defaults = defaults or {} self._for_write = True with transaction.atomic(using=self.db): # Lock the row so that a concurrent update is blocked until # update_or_create() has performed its save. obj, created = self.select_for_update().get_or_create(defaults, **kwargs) if created: return obj, created for k, v in resolve_callables(defaults): setattr(obj, k, v) update_fields = set(defaults) concrete_field_names = self.model._meta._non_pk_concrete_field_names # update_fields does not support non-concrete fields. if concrete_field_names.issuperset(update_fields): # Add fields which are set on pre_save(), e.g. auto_now fields. # This is to maintain backward compatibility as these fields # are not updated unless explicitly specified in the # update_fields list. for field in self.model._meta.local_concrete_fields: if not ( field.primary_key or field.__class__.pre_save is Field.pre_save ): update_fields.add(field.name) if field.name != field.attname: update_fields.add(field.attname) obj.save(using=self.db, update_fields=update_fields) else: obj.save(using=self.db) return obj, False async def aupdate_or_create(self, defaults=None, **kwargs): return await sync_to_async(self.update_or_create)( defaults=defaults, **kwargs, ) def _extract_model_params(self, defaults, **kwargs): """ Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create(). """ defaults = defaults or {} params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k} params.update(defaults) property_names = self.model._meta._property_names invalid_params = [] for param in params: try: self.model._meta.get_field(param) except exceptions.FieldDoesNotExist: # It's okay to use a model's property if it has a setter. if not (param in property_names and getattr(self.model, param).fset): invalid_params.append(param) if invalid_params: raise exceptions.FieldError( "Invalid field name(s) for model %s: '%s'." % ( self.model._meta.object_name, "', '".join(sorted(invalid_params)), ) ) return params def _earliest(self, *fields): """ Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by. """ if fields: order_by = fields else: order_by = getattr(self.model._meta, "get_latest_by") if order_by and not isinstance(order_by, (tuple, list)): order_by = (order_by,) if order_by is None: raise ValueError( "earliest() and latest() require either fields as positional " "arguments or 'get_latest_by' in the model's Meta." ) obj = self._chain() obj.query.set_limits(high=1) obj.query.clear_ordering(force=True) obj.query.add_ordering(*order_by) return obj.get() def earliest(self, *fields): if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self._earliest(*fields) async def aearliest(self, *fields): return await sync_to_async(self.earliest)(*fields) def latest(self, *fields): """ Return the latest object according to fields (if given) or by the model's Meta.get_latest_by. """ if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self.reverse()._earliest(*fields) async def alatest(self, *fields): return await sync_to_async(self.latest)(*fields) def first(self): """Return the first object of a query or None if no match is found.""" if self.ordered: queryset = self else: self._check_ordering_first_last_queryset_aggregation(method="first") queryset = self.order_by("pk") for obj in queryset[:1]: return obj async def afirst(self): return await sync_to_async(self.first)() def last(self): """Return the last object of a query or None if no match is found.""" if self.ordered: queryset = self.reverse() else: self._check_ordering_first_last_queryset_aggregation(method="last") queryset = self.order_by("-pk") for obj in queryset[:1]: return obj async def alast(self): return await sync_to_async(self.last)() def in_bulk(self, id_list=None, *, field_name="pk"): """ Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet. """ if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with in_bulk().") opts = self.model._meta unique_fields = [ constraint.fields[0] for constraint in opts.total_unique_constraints if len(constraint.fields) == 1 ] if ( field_name != "pk" and not opts.get_field(field_name).unique and field_name not in unique_fields and self.query.distinct_fields != (field_name,) ): raise ValueError( "in_bulk()'s field_name must be a unique field but %r isn't." % field_name ) if id_list is not None: if not id_list: return {} filter_key = "{}__in".format(field_name) batch_size = connections[self.db].features.max_query_params id_list = tuple(id_list) # If the database has a limit on the number of query parameters # (e.g. SQLite), retrieve objects in batches if necessary. if batch_size and batch_size < len(id_list): qs = () for offset in range(0, len(id_list), batch_size): batch = id_list[offset : offset + batch_size] qs += tuple(self.filter(**{filter_key: batch}).order_by()) else: qs = self.filter(**{filter_key: id_list}).order_by() else: qs = self._chain() return {getattr(obj, field_name): obj for obj in qs} async def ain_bulk(self, id_list=None, *, field_name="pk"): return await sync_to_async(self.in_bulk)( id_list=id_list, field_name=field_name, ) def delete(self): """Delete the records in the current QuerySet.""" self._not_support_combined_queries("delete") if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with delete().") if self.query.distinct or self.query.distinct_fields: raise TypeError("Cannot call delete() after .distinct().") if self._fields is not None: raise TypeError("Cannot call delete() after .values() or .values_list()") del_query = self._chain() # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force=True) collector = Collector(using=del_query.db, origin=self) collector.collect(del_query) deleted, _rows_count = collector.delete() # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None return deleted, _rows_count delete.alters_data = True delete.queryset_only = True async def adelete(self): return await sync_to_async(self.delete)() adelete.alters_data = True adelete.queryset_only = True def _raw_delete(self, using): """ Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades. """ query = self.query.clone() query.__class__ = sql.DeleteQuery cursor = query.get_compiler(using).execute_sql(CURSOR) if cursor: with cursor: return cursor.rowcount return 0 _raw_delete.alters_data = True def update(self, **kwargs): """ Update all elements in the current QuerySet, setting all the given fields to the appropriate values. """ self._not_support_combined_queries("update") if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") self._for_write = True query = self.query.chain(sql.UpdateQuery) query.add_update_values(kwargs) # Inline annotations in order_by(), if possible. new_order_by = [] for col in query.order_by: if annotation := query.annotations.get(col): if getattr(annotation, "contains_aggregate", False): raise exceptions.FieldError( f"Cannot update when ordering by an aggregate: {annotation}" ) new_order_by.append(annotation) else: new_order_by.append(col) query.order_by = tuple(new_order_by) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} with transaction.mark_for_rollback_on_error(using=self.db): rows = query.get_compiler(self.db).execute_sql(CURSOR) self._result_cache = None return rows update.alters_data = True async def aupdate(self, **kwargs): return await sync_to_async(self.update)(**kwargs) aupdate.alters_data = True def _update(self, values): """ A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") query = self.query.chain(sql.UpdateQuery) query.add_update_fields(values) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} self._result_cache = None return query.get_compiler(self.db).execute_sql(CURSOR) _update.alters_data = True _update.queryset_only = False def exists(self): """ Return True if the QuerySet would have any results, False otherwise. """ if self._result_cache is None: return self.query.has_results(using=self.db) return bool(self._result_cache) async def aexists(self): return await sync_to_async(self.exists)() def contains(self, obj): """ Return True if the QuerySet contains the provided obj, False otherwise. """ self._not_support_combined_queries("contains") if self._fields is not None: raise TypeError( "Cannot call QuerySet.contains() after .values() or .values_list()." ) try: if obj._meta.concrete_model != self.model._meta.concrete_model: return False except AttributeError: raise TypeError("'obj' must be a model instance.") if obj.pk is None: raise ValueError("QuerySet.contains() cannot be used on unsaved objects.") if self._result_cache is not None: return obj in self._result_cache return self.filter(pk=obj.pk).exists() async def acontains(self, obj): return await sync_to_async(self.contains)(obj=obj) def _prefetch_related_objects(self): # This method can only be called once the result cache has been filled. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def explain(self, *, format=None, **options): """ Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results. """ return self.query.explain(using=self.db, format=format, **options) async def aexplain(self, *, format=None, **options): return await sync_to_async(self.explain)(format=format, **options) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=(), translations=None, using=None): if using is None: using = self.db qs = RawQuerySet( raw_query, model=self.model, params=params, translations=translations, using=using, ) qs._prefetch_related_lookups = self._prefetch_related_lookups[:] return qs def _values(self, *fields, **expressions): clone = self._chain() if expressions: clone = clone.annotate(**expressions) clone._fields = fields clone.query.set_values(fields) return clone def values(self, *fields, **expressions): fields += tuple(expressions) clone = self._values(*fields, **expressions) clone._iterable_class = ValuesIterable return clone def values_list(self, *fields, flat=False, named=False): if flat and named: raise TypeError("'flat' and 'named' can't be used together.") if flat and len(fields) > 1: raise TypeError( "'flat' is not valid when values_list is called with more than one " "field." ) field_names = {f for f in fields if not hasattr(f, "resolve_expression")} _fields = [] expressions = {} counter = 1 for field in fields: if hasattr(field, "resolve_expression"): field_id_prefix = getattr( field, "default_alias", field.__class__.__name__.lower() ) while True: field_id = field_id_prefix + str(counter) counter += 1 if field_id not in field_names: break expressions[field_id] = field _fields.append(field_id) else: _fields.append(field) clone = self._values(*_fields, **expressions) clone._iterable_class = ( NamedValuesListIterable if named else FlatValuesListIterable if flat else ValuesListIterable ) return clone def dates(self, field_name, kind, order="ASC"): """ Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day"): raise ValueError("'kind' must be one of 'year', 'month', 'week', or 'day'.") if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") return ( self.annotate( datefield=Trunc(field_name, kind, output_field=DateField()), plain_field=F(field_name), ) .values_list("datefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datefield") ) def datetimes(self, field_name, kind, order="ASC", tzinfo=None): """ Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day", "hour", "minute", "second"): raise ValueError( "'kind' must be one of 'year', 'month', 'week', 'day', " "'hour', 'minute', or 'second'." ) if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return ( self.annotate( datetimefield=Trunc( field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo, ), plain_field=F(field_name), ) .values_list("datetimefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datetimefield") ) def none(self): """Return an empty QuerySet.""" clone = self._chain() clone.query.set_empty() return clone ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self): """ Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._chain() def filter(self, *args, **kwargs): """ Return a new QuerySet instance with the args ANDed to the existing set. """ self._not_support_combined_queries("filter") return self._filter_or_exclude(False, args, kwargs) def exclude(self, *args, **kwargs): """ Return a new QuerySet instance with NOT (args) ANDed to the existing set. """ self._not_support_combined_queries("exclude") return self._filter_or_exclude(True, args, kwargs) def _filter_or_exclude(self, negate, args, kwargs): if (args or kwargs) and self.query.is_sliced: raise TypeError("Cannot filter a query once a slice has been taken.") clone = self._chain() if self._defer_next_filter: self._defer_next_filter = False clone._deferred_filter = negate, args, kwargs else: clone._filter_or_exclude_inplace(negate, args, kwargs) return clone def _filter_or_exclude_inplace(self, negate, args, kwargs): if negate: self._query.add_q(~Q(*args, **kwargs)) else: self._query.add_q(Q(*args, **kwargs)) def complex_filter(self, filter_obj): """ Return a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. """ if isinstance(filter_obj, Q): clone = self._chain() clone.query.add_q(filter_obj) return clone else: return self._filter_or_exclude(False, args=(), kwargs=filter_obj) def _combinator_query(self, combinator, *other_qs, all=False): # Clone the query to inherit the select list and everything clone = self._chain() # Clear limits and ordering so they can be reapplied clone.query.clear_ordering(force=True) clone.query.clear_limits() clone.query.combined_queries = (self.query,) + tuple( qs.query for qs in other_qs ) clone.query.combinator = combinator clone.query.combinator_all = all return clone def union(self, *other_qs, all=False): # If the query is an EmptyQuerySet, combine all nonempty querysets. if isinstance(self, EmptyQuerySet): qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)] if not qs: return self if len(qs) == 1: return qs[0] return qs[0]._combinator_query("union", *qs[1:], all=all) return self._combinator_query("union", *other_qs, all=all) def intersection(self, *other_qs): # If any query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self for other in other_qs: if isinstance(other, EmptyQuerySet): return other return self._combinator_query("intersection", *other_qs) def difference(self, *other_qs): # If the query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self return self._combinator_query("difference", *other_qs) def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False): """ Return a new QuerySet instance that will select objects with a FOR UPDATE lock. """ if nowait and skip_locked: raise ValueError("The nowait option cannot be used with skip_locked.") obj = self._chain() obj._for_write = True obj.query.select_for_update = True obj.query.select_for_update_nowait = nowait obj.query.select_for_update_skip_locked = skip_locked obj.query.select_for_update_of = of obj.query.select_for_no_key_update = no_key return obj def select_related(self, *fields): """ Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list. """ self._not_support_combined_queries("select_related") if self._fields is not None: raise TypeError( "Cannot call select_related() after .values() or .values_list()" ) obj = self._chain() if fields == (None,): obj.query.select_related = False elif fields: obj.query.add_select_related(fields) else: obj.query.select_related = True return obj def prefetch_related(self, *lookups): """ Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list. """ self._not_support_combined_queries("prefetch_related") clone = self._chain() if lookups == (None,): clone._prefetch_related_lookups = () else: for lookup in lookups: if isinstance(lookup, Prefetch): lookup = lookup.prefetch_to lookup = lookup.split(LOOKUP_SEP, 1)[0] if lookup in self.query._filtered_relations: raise ValueError( "prefetch_related() is not supported with FilteredRelation." ) clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with extra data or aggregations. """ self._not_support_combined_queries("annotate") return self._annotate(args, kwargs, select=True) def alias(self, *args, **kwargs): """ Return a query set with added aliases for extra data or aggregations. """ self._not_support_combined_queries("alias") return self._annotate(args, kwargs, select=False) def _annotate(self, args, kwargs, select=True): self._validate_values_are_expressions( args + tuple(kwargs.values()), method_name="annotate" ) annotations = {} for arg in args: # The default_alias property may raise a TypeError. try: if arg.default_alias in kwargs: raise ValueError( "The named annotation '%s' conflicts with the " "default name for another annotation." % arg.default_alias ) except TypeError: raise TypeError("Complex annotations require an alias") annotations[arg.default_alias] = arg annotations.update(kwargs) clone = self._chain() names = self._fields if names is None: names = set( chain.from_iterable( (field.name, field.attname) if hasattr(field, "attname") else (field.name,) for field in self.model._meta.get_fields() ) ) for alias, annotation in annotations.items(): if alias in names: raise ValueError( "The annotation '%s' conflicts with a field on " "the model." % alias ) if isinstance(annotation, FilteredRelation): clone.query.add_filtered_relation(annotation, alias) else: clone.query.add_annotation( annotation, alias, select=select, ) for alias, annotation in clone.query.annotations.items(): if alias in annotations and annotation.contains_aggregate: if clone._fields is None: clone.query.group_by = True else: clone.query.set_group_by() break return clone def order_by(self, *field_names): """Return a new QuerySet instance with the ordering changed.""" if self.query.is_sliced: raise TypeError("Cannot reorder a query once a slice has been taken.") obj = self._chain() obj.query.clear_ordering(force=True, clear_default=False) obj.query.add_ordering(*field_names) return obj def distinct(self, *field_names): """ Return a new QuerySet instance that will select only distinct results. """ self._not_support_combined_queries("distinct") if self.query.is_sliced: raise TypeError( "Cannot create distinct fields once a slice has been taken." ) obj = self._chain() obj.query.add_distinct_fields(*field_names) return obj def extra( self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None, ): """Add extra SQL fragments to the query.""" self._not_support_combined_queries("extra") if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") clone = self._chain() clone.query.add_extra(select, select_params, where, params, tables, order_by) return clone def reverse(self): """Reverse the ordering of the QuerySet.""" if self.query.is_sliced: raise TypeError("Cannot reverse a query once a slice has been taken.") clone = self._chain() clone.query.standard_ordering = not clone.query.standard_ordering return clone def defer(self, *fields): """ Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals. """ self._not_support_combined_queries("defer") if self._fields is not None: raise TypeError("Cannot call defer() after .values() or .values_list()") clone = self._chain() if fields == (None,): clone.query.clear_deferred_loading() else: clone.query.add_deferred_loading(fields) return clone def only(self, *fields): """ Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ self._not_support_combined_queries("only") if self._fields is not None: raise TypeError("Cannot call only() after .values() or .values_list()") if fields == (None,): # Can only pass None to defer(), not only(), as the rest option. # That won't stop people trying to do this, so let's be explicit. raise TypeError("Cannot pass None as an argument to only().") for field in fields: field = field.split(LOOKUP_SEP, 1)[0] if field in self.query._filtered_relations: raise ValueError("only() is not supported with FilteredRelation.") clone = self._chain() clone.query.add_immediate_loading(fields) return clone def using(self, alias): """Select which database this QuerySet should execute against.""" clone = self._chain() clone._db = alias return clone ################################### # PUBLIC INTROSPECTION ATTRIBUTES # ################################### @property def ordered(self): """ Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty). """ if isinstance(self, EmptyQuerySet): return True if self.query.extra_order_by or self.query.order_by: return True elif ( self.query.default_ordering and self.query.get_meta().ordering and # A default ordering doesn't affect GROUP BY queries. not self.query.group_by ): return True else: return False @property def db(self): """Return the database used if this query is executed now.""" if self._for_write: return self._db or router.db_for_write(self.model, **self._hints) return self._db or router.db_for_read(self.model, **self._hints) ################### # PRIVATE METHODS # ################### def _insert( self, objs, fields, returning_fields=None, raw=False, using=None, on_conflict=None, update_fields=None, unique_fields=None, ): """ Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. """ self._for_write = True if using is None: using = self.db query = sql.InsertQuery( self.model, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) query.insert_values(fields, objs, raw=raw) return query.get_compiler(using=using).execute_sql(returning_fields) _insert.alters_data = True _insert.queryset_only = False def _batched_insert( self, objs, fields, batch_size, on_conflict=None, update_fields=None, unique_fields=None, ): """ Helper method for bulk_create() to insert objs one batch at a time. """ connection = connections[self.db] ops = connection.ops max_batch_size = max(ops.bulk_batch_size(fields, objs), 1) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size inserted_rows = [] bulk_return = connection.features.can_return_rows_from_bulk_insert for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: if bulk_return and on_conflict is None: inserted_rows.extend( self._insert( item, fields=fields, using=self.db, returning_fields=self.model._meta.db_returning_fields, ) ) else: self._insert( item, fields=fields, using=self.db, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) return inserted_rows def _chain(self): """ Return a copy of the current QuerySet that's ready for another operation. """ obj = self._clone() if obj._sticky_filter: obj.query.filter_is_sticky = True obj._sticky_filter = False return obj def _clone(self): """ Return a copy of the current QuerySet. A lightweight alternative to deepcopy(). """ c = self.__class__( model=self.model, query=self.query.chain(), using=self._db, hints=self._hints, ) c._sticky_filter = self._sticky_filter c._for_write = self._for_write c._prefetch_related_lookups = self._prefetch_related_lookups[:] c._known_related_objects = self._known_related_objects c._iterable_class = self._iterable_class c._fields = self._fields return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self._iterable_class(self)) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def _next_is_sticky(self): """ Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. """ self._sticky_filter = True return self def _merge_sanity_check(self, other): """Check that two QuerySet classes may be merged.""" if self._fields is not None and ( set(self.query.values_select) != set(other.query.values_select) or set(self.query.extra_select) != set(other.query.extra_select) or set(self.query.annotation_select) != set(other.query.annotation_select) ): raise TypeError( "Merging '%s' classes must involve the same values in each case." % self.__class__.__name__ ) def _merge_known_related_objects(self, other): """ Keep track of all known related objects from either QuerySet instance. """ for field, objects in other._known_related_objects.items(): self._known_related_objects.setdefault(field, {}).update(objects) def resolve_expression(self, *args, **kwargs): if self._fields and len(self._fields) > 1: # values() queryset can only be used as nested queries # if they are set up to select only a single field. raise TypeError("Cannot use multi-field values as a filter value.") query = self.query.resolve_expression(*args, **kwargs) query._db = self._db return query resolve_expression.queryset_only = True def _add_hints(self, **hints): """ Update hinting information for use by routers. Add new key/values or overwrite existing key/values. """ self._hints.update(hints) def _has_filters(self): """ Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False. """ return self.query.has_filters() @staticmethod def _validate_values_are_expressions(values, method_name): invalid_args = sorted( str(arg) for arg in values if not hasattr(arg, "resolve_expression") ) if invalid_args: raise TypeError( "QuerySet.%s() received non-expression(s): %s." % ( method_name, ", ".join(invalid_args), ) ) def _not_support_combined_queries(self, operation_name): if self.query.combinator: raise NotSupportedError( "Calling QuerySet.%s() after %s() is not supported." % (operation_name, self.query.combinator) ) def _check_operator_queryset(self, other, operator_): if self.query.combinator or other.query.combinator: raise TypeError(f"Cannot use {operator_} operator with combined queryset.") def _check_ordering_first_last_queryset_aggregation(self, method): if isinstance(self.query.group_by, tuple) and not any( col.output_field is self.model._meta.pk for col in self.query.group_by ): raise TypeError( f"Cannot use QuerySet.{method}() on an unordered queryset performing " f"aggregation. Add an ordering with order_by()." ) class InstanceCheckMeta(type): def __instancecheck__(self, instance): return isinstance(instance, QuerySet) and instance.query.is_empty() class EmptyQuerySet(metaclass=InstanceCheckMeta): """ Marker class to checking if a queryset is empty by .none(): isinstance(qs.none(), EmptyQuerySet) -> True """ def __init__(self, *args, **kwargs): raise TypeError("EmptyQuerySet can't be instantiated") class RawQuerySet: """ Provide an iterator which converts the results of raw SQL queries into annotated model instances. """ def __init__( self, raw_query, model=None, query=None, params=(), translations=None, using=None, hints=None, ): self.raw_query = raw_query self.model = model self._db = using self._hints = hints or {} self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params) self.params = params self.translations = translations or {} self._result_cache = None self._prefetch_related_lookups = () self._prefetch_done = False def resolve_model_init_order(self): """Resolve the init field names and value positions.""" converter = connections[self.db].introspection.identifier_converter model_init_fields = [ f for f in self.model._meta.fields if converter(f.column) in self.columns ] annotation_fields = [ (column, pos) for pos, column in enumerate(self.columns) if column not in self.model_fields ] model_init_order = [ self.columns.index(converter(f.column)) for f in model_init_fields ] model_init_names = [f.attname for f in model_init_fields] return model_init_names, model_init_order, annotation_fields def prefetch_related(self, *lookups): """Same as QuerySet.prefetch_related()""" clone = self._clone() if lookups == (None,): clone._prefetch_related_lookups = () else: clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def _prefetch_related_objects(self): prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def _clone(self): """Same as QuerySet._clone()""" c = self.__class__( self.raw_query, model=self.model, query=self.query, params=self.params, translations=self.translations, using=self._db, hints=self._hints, ) c._prefetch_related_lookups = self._prefetch_related_lookups[:] return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def __len__(self): self._fetch_all() return len(self._result_cache) def __bool__(self): self._fetch_all() return bool(self._result_cache) def __iter__(self): self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def iterator(self): yield from RawModelIterable(self) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.query) def __getitem__(self, k): return list(self)[k] @property def db(self): """Return the database used if this query is executed now.""" return self._db or router.db_for_read(self.model, **self._hints) def using(self, alias): """Select the database this RawQuerySet should execute against.""" return RawQuerySet( self.raw_query, model=self.model, query=self.query.chain(using=alias), params=self.params, translations=self.translations, using=alias, ) @cached_property def columns(self): """ A list of model field names in the order they'll appear in the query results. """ columns = self.query.get_columns() # Adjust any column names which don't match field names for (query_name, model_name) in self.translations.items(): # Ignore translations for nonexistent column names try: index = columns.index(query_name) except ValueError: pass else: columns[index] = model_name return columns @cached_property def model_fields(self): """A dict mapping column names to model field names.""" converter = connections[self.db].introspection.identifier_converter model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() model_fields[converter(column)] = field return model_fields class Prefetch: def __init__(self, lookup, queryset=None, to_attr=None): # `prefetch_through` is the path we traverse to perform the prefetch. self.prefetch_through = lookup # `prefetch_to` is the path to the attribute that stores the result. self.prefetch_to = lookup if queryset is not None and ( isinstance(queryset, RawQuerySet) or ( hasattr(queryset, "_iterable_class") and not issubclass(queryset._iterable_class, ModelIterable) ) ): raise ValueError( "Prefetch querysets cannot use raw(), values(), and values_list()." ) if to_attr: self.prefetch_to = LOOKUP_SEP.join( lookup.split(LOOKUP_SEP)[:-1] + [to_attr] ) self.queryset = queryset self.to_attr = to_attr def __getstate__(self): obj_dict = self.__dict__.copy() if self.queryset is not None: queryset = self.queryset._chain() # Prevent the QuerySet from being evaluated queryset._result_cache = [] queryset._prefetch_done = True obj_dict["queryset"] = queryset return obj_dict def add_prefix(self, prefix): self.prefetch_through = prefix + LOOKUP_SEP + self.prefetch_through self.prefetch_to = prefix + LOOKUP_SEP + self.prefetch_to def get_current_prefetch_to(self, level): return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[: level + 1]) def get_current_to_attr(self, level): parts = self.prefetch_to.split(LOOKUP_SEP) to_attr = parts[level] as_attr = self.to_attr and level == len(parts) - 1 return to_attr, as_attr def get_current_queryset(self, level): if self.get_current_prefetch_to(level) == self.prefetch_to: return self.queryset return None def __eq__(self, other): if not isinstance(other, Prefetch): return NotImplemented return self.prefetch_to == other.prefetch_to def __hash__(self): return hash((self.__class__, self.prefetch_to)) def normalize_prefetch_lookups(lookups, prefix=None): """Normalize lookups into Prefetch objects.""" ret = [] for lookup in lookups: if not isinstance(lookup, Prefetch): lookup = Prefetch(lookup) if prefix: lookup.add_prefix(prefix) ret.append(lookup) return ret def prefetch_related_objects(model_instances, *related_lookups): """ Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given. """ if not model_instances: return # nothing to do # We need to be able to dynamically add to the list of prefetch_related # lookups that we look up (see below). So we need some book keeping to # ensure we don't do duplicate work. done_queries = {} # dictionary of things like 'foo__bar': [results] auto_lookups = set() # we add to this as we go through. followed_descriptors = set() # recursion protection all_lookups = normalize_prefetch_lookups(reversed(related_lookups)) while all_lookups: lookup = all_lookups.pop() if lookup.prefetch_to in done_queries: if lookup.queryset is not None: raise ValueError( "'%s' lookup was already seen with a different queryset. " "You may need to adjust the ordering of your lookups." % lookup.prefetch_to ) continue # Top level, the list of objects to decorate is the result cache # from the primary QuerySet. It won't be for deeper levels. obj_list = model_instances through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) for level, through_attr in enumerate(through_attrs): # Prepare main instances if not obj_list: break prefetch_to = lookup.get_current_prefetch_to(level) if prefetch_to in done_queries: # Skip any prefetching, and any object preparation obj_list = done_queries[prefetch_to] continue # Prepare objects: good_objects = True for obj in obj_list: # Since prefetching can re-use instances, it is possible to have # the same instance multiple times in obj_list, so obj might # already be prepared. if not hasattr(obj, "_prefetched_objects_cache"): try: obj._prefetched_objects_cache = {} except (AttributeError, TypeError): # Must be an immutable object from # values_list(flat=True), for example (TypeError) or # a QuerySet subclass that isn't returning Model # instances (AttributeError), either in Django or a 3rd # party. prefetch_related() doesn't make sense, so quit. good_objects = False break if not good_objects: break # Descend down tree # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] to_attr = lookup.get_current_to_attr(level)[0] prefetcher, descriptor, attr_found, is_fetched = get_prefetcher( first_obj, through_attr, to_attr ) if not attr_found: raise AttributeError( "Cannot find '%s' on %s object, '%s' is an invalid " "parameter to prefetch_related()" % ( through_attr, first_obj.__class__.__name__, lookup.prefetch_through, ) ) if level == len(through_attrs) - 1 and prefetcher is None: # Last one, this *must* resolve to something that supports # prefetching, otherwise there is no point adding it and the # developer asking for it has made a mistake. raise ValueError( "'%s' does not resolve to an item that supports " "prefetching - this is an invalid parameter to " "prefetch_related()." % lookup.prefetch_through ) obj_to_fetch = None if prefetcher is not None: obj_to_fetch = [obj for obj in obj_list if not is_fetched(obj)] if obj_to_fetch: obj_list, additional_lookups = prefetch_one_level( obj_to_fetch, prefetcher, lookup, level, ) # We need to ensure we don't keep adding lookups from the # same relationships to stop infinite recursion. So, if we # are already on an automatically added lookup, don't add # the new lookups from relationships we've seen already. if not ( prefetch_to in done_queries and lookup in auto_lookups and descriptor in followed_descriptors ): done_queries[prefetch_to] = obj_list new_lookups = normalize_prefetch_lookups( reversed(additional_lookups), prefetch_to ) auto_lookups.update(new_lookups) all_lookups.extend(new_lookups) followed_descriptors.add(descriptor) else: # Either a singly related object that has already been fetched # (e.g. via select_related), or hopefully some other property # that doesn't support prefetching but needs to be traversed. # We replace the current list of parent objects with the list # of related objects, filtering out empty or missing values so # that we can continue with nullable or reverse relations. new_obj_list = [] for obj in obj_list: if through_attr in getattr(obj, "_prefetched_objects_cache", ()): # If related objects have been prefetched, use the # cache rather than the object's through_attr. new_obj = list(obj._prefetched_objects_cache.get(through_attr)) else: try: new_obj = getattr(obj, through_attr) except exceptions.ObjectDoesNotExist: continue if new_obj is None: continue # We special-case `list` rather than something more generic # like `Iterable` because we don't want to accidentally match # user models that define __iter__. if isinstance(new_obj, list): new_obj_list.extend(new_obj) else: new_obj_list.append(new_obj) obj_list = new_obj_list def get_prefetcher(instance, through_attr, to_attr): """ For the attribute 'through_attr' on the given instance, find an object that has a get_prefetch_queryset(). Return a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute was not found at all, a function that takes an instance and returns a boolean that is True if the attribute has already been fetched for that instance) """ def has_to_attr_attribute(instance): return hasattr(instance, to_attr) prefetcher = None is_fetched = has_to_attr_attribute # For singly related objects, we have to avoid getting the attribute # from the object, as this will trigger the query. So we first try # on the class, in order to get the descriptor object. rel_obj_descriptor = getattr(instance.__class__, through_attr, None) if rel_obj_descriptor is None: attr_found = hasattr(instance, through_attr) else: attr_found = True if rel_obj_descriptor: # singly related object, descriptor object has the # get_prefetch_queryset() method. if hasattr(rel_obj_descriptor, "get_prefetch_queryset"): prefetcher = rel_obj_descriptor is_fetched = rel_obj_descriptor.is_cached else: # descriptor doesn't support prefetching, so we go ahead and get # the attribute on the instance rather than the class to # support many related managers rel_obj = getattr(instance, through_attr) if hasattr(rel_obj, "get_prefetch_queryset"): prefetcher = rel_obj if through_attr != to_attr: # Special case cached_property instances because hasattr # triggers attribute computation and assignment. if isinstance( getattr(instance.__class__, to_attr, None), cached_property ): def has_cached_property(instance): return to_attr in instance.__dict__ is_fetched = has_cached_property else: def in_prefetched_cache(instance): return through_attr in instance._prefetched_objects_cache is_fetched = in_prefetched_cache return prefetcher, rel_obj_descriptor, attr_found, is_fetched def prefetch_one_level(instances, prefetcher, lookup, level): """ Helper function for prefetch_related_objects(). Run prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. Return the prefetched objects along with any additional prefetches that must be done due to prefetch_related lookups found from default managers. """ # prefetcher must have a method get_prefetch_queryset() which takes a list # of instances, and returns a tuple: # (queryset of instances of self.model that are related to passed in instances, # callable that gets value to be matched for returned instances, # callable that gets value to be matched for passed in instances, # boolean that is True for singly related objects, # cache or field name to assign to, # boolean that is True when the previous argument is a cache name vs a field name). # The 'values to be matched' must be hashable as they will be used # in a dictionary. ( rel_qs, rel_obj_attr, instance_attr, single, cache_name, is_descriptor, ) = prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level)) # We have to handle the possibility that the QuerySet we just got back # contains some prefetch_related lookups. We don't want to trigger the # prefetch_related functionality by evaluating the query. Rather, we need # to merge in the prefetch_related lookups. # Copy the lookups in case it is a Prefetch object which could be reused # later (happens in nested prefetch_related). additional_lookups = [ copy.copy(additional_lookup) for additional_lookup in getattr(rel_qs, "_prefetch_related_lookups", ()) ] if additional_lookups: # Don't need to clone because the manager should have given us a fresh # instance, so we access an internal instead of using public interface # for performance reasons. rel_qs._prefetch_related_lookups = () all_related_objects = list(rel_qs) rel_obj_cache = {} for rel_obj in all_related_objects: rel_attr_val = rel_obj_attr(rel_obj) rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj) to_attr, as_attr = lookup.get_current_to_attr(level) # Make sure `to_attr` does not conflict with a field. if as_attr and instances: # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. model = instances[0].__class__ try: model._meta.get_field(to_attr) except exceptions.FieldDoesNotExist: pass else: msg = "to_attr={} conflicts with a field on the {} model." raise ValueError(msg.format(to_attr, model.__name__)) # Whether or not we're prefetching the last part of the lookup. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level for obj in instances: instance_attr_val = instance_attr(obj) vals = rel_obj_cache.get(instance_attr_val, []) if single: val = vals[0] if vals else None if as_attr: # A to_attr has been given for the prefetch. setattr(obj, to_attr, val) elif is_descriptor: # cache_name points to a field name in obj. # This field is a descriptor for a related object. setattr(obj, cache_name, val) else: # No to_attr has been given for this prefetch operation and the # cache_name does not point to a descriptor. Store the value of # the field in the object's field cache. obj._state.fields_cache[cache_name] = val else: if as_attr: setattr(obj, to_attr, vals) else: manager = getattr(obj, to_attr) if leaf and lookup.queryset is not None: qs = manager._apply_rel_filters(lookup.queryset) else: qs = manager.get_queryset() qs._result_cache = vals # We don't want the individual qs doing prefetch_related now, # since we have merged this into the current work. qs._prefetch_done = True obj._prefetched_objects_cache[cache_name] = qs return all_related_objects, additional_lookups class RelatedPopulator: """ RelatedPopulator is used for select_related() object instantiation. The idea is that each select_related() model will be populated by a different RelatedPopulator instance. The RelatedPopulator instances get klass_info and select (computed in SQLCompiler) plus the used db as input for initialization. That data is used to compute which columns to use, how to instantiate the model, and how to populate the links between the objects. The actual creation of the objects is done in populate() method. This method gets row and from_obj as input and populates the select_related() model instance. """ def __init__(self, klass_info, select, db): self.db = db # Pre-compute needed attributes. The attributes are: # - model_cls: the possibly deferred model class to instantiate # - either: # - cols_start, cols_end: usually the columns in the row are # in the same order model_cls.__init__ expects them, so we # can instantiate by model_cls(*row[cols_start:cols_end]) # - reorder_for_init: When select_related descends to a child # class, then we want to reuse the already selected parent # data. However, in this case the parent data isn't necessarily # in the same order that Model.__init__ expects it to be, so # we have to reorder the parent data. The reorder_for_init # attribute contains a function used to reorder the field data # in the order __init__ expects it. # - pk_idx: the index of the primary key field in the reordered # model data. Used to check if a related object exists at all. # - init_list: the field attnames fetched from the database. For # deferred models this isn't the same as all attnames of the # model's fields. # - related_populators: a list of RelatedPopulator instances if # select_related() descends to related models from this model. # - local_setter, remote_setter: Methods to set cached values on # the object being populated and on the remote object. Usually # these are Field.set_cached_value() methods. select_fields = klass_info["select_fields"] from_parent = klass_info["from_parent"] if not from_parent: self.cols_start = select_fields[0] self.cols_end = select_fields[-1] + 1 self.init_list = [ f[0].target.attname for f in select[self.cols_start : self.cols_end] ] self.reorder_for_init = None else: attname_indexes = { select[idx][0].target.attname: idx for idx in select_fields } model_init_attnames = ( f.attname for f in klass_info["model"]._meta.concrete_fields ) self.init_list = [ attname for attname in model_init_attnames if attname in attname_indexes ] self.reorder_for_init = operator.itemgetter( *[attname_indexes[attname] for attname in self.init_list] ) self.model_cls = klass_info["model"] self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname) self.related_populators = get_related_populators(klass_info, select, self.db) self.local_setter = klass_info["local_setter"] self.remote_setter = klass_info["remote_setter"] def populate(self, row, from_obj): if self.reorder_for_init: obj_data = self.reorder_for_init(row) else: obj_data = row[self.cols_start : self.cols_end] if obj_data[self.pk_idx] is None: obj = None else: obj = self.model_cls.from_db(self.db, self.init_list, obj_data) for rel_iter in self.related_populators: rel_iter.populate(row, obj) self.local_setter(from_obj, obj) if obj is not None: self.remote_setter(obj, from_obj) def get_related_populators(klass_info, select, db): iterators = [] related_klass_infos = klass_info.get("related_klass_infos", []) for rel_klass_info in related_klass_infos: rel_cls = RelatedPopulator(rel_klass_info, select, db) iterators.append(rel_cls) return iterators
4db0c21eb9a4202e32266c88faf78af1fd756c0fcef3f53da81d5e3cd6178ad8
import copy import datetime import functools import inspect from collections import defaultdict from decimal import Decimal from types import NoneType from uuid import UUID from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError, connection from django.db.models import fields from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import Q from django.utils.deconstruct import deconstructible from django.utils.functional import cached_property from django.utils.hashable import make_hashable class SQLiteNumericMixin: """ Some expressions with output_field=DecimalField() must be cast to numeric to be properly filtered. """ def as_sqlite(self, compiler, connection, **extra_context): sql, params = self.as_sql(compiler, connection, **extra_context) try: if self.output_field.get_internal_type() == "DecimalField": sql = "CAST(%s AS NUMERIC)" % sql except FieldError: pass return sql, params class Combinable: """ Provide the ability to combine one or two objects with some connector. For example F('foo') + F('bar'). """ # Arithmetic connectors ADD = "+" SUB = "-" MUL = "*" DIV = "/" POW = "^" # The following is a quoted % operator - it is quoted because it can be # used in strings that also have parameter substitution. MOD = "%%" # Bitwise operators - note that these are generated by .bitand() # and .bitor(), the '&' and '|' are reserved for boolean operator # usage. BITAND = "&" BITOR = "|" BITLEFTSHIFT = "<<" BITRIGHTSHIFT = ">>" BITXOR = "#" def _combine(self, other, connector, reversed): if not hasattr(other, "resolve_expression"): # everything must be resolvable to an expression other = Value(other) if reversed: return CombinedExpression(other, connector, self) return CombinedExpression(self, connector, other) ############# # OPERATORS # ############# def __neg__(self): return self._combine(-1, self.MUL, False) def __add__(self, other): return self._combine(other, self.ADD, False) def __sub__(self, other): return self._combine(other, self.SUB, False) def __mul__(self, other): return self._combine(other, self.MUL, False) def __truediv__(self, other): return self._combine(other, self.DIV, False) def __mod__(self, other): return self._combine(other, self.MOD, False) def __pow__(self, other): return self._combine(other, self.POW, False) def __and__(self, other): if getattr(self, "conditional", False) and getattr(other, "conditional", False): return Q(self) & Q(other) raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def bitand(self, other): return self._combine(other, self.BITAND, False) def bitleftshift(self, other): return self._combine(other, self.BITLEFTSHIFT, False) def bitrightshift(self, other): return self._combine(other, self.BITRIGHTSHIFT, False) def __xor__(self, other): if getattr(self, "conditional", False) and getattr(other, "conditional", False): return Q(self) ^ Q(other) raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def bitxor(self, other): return self._combine(other, self.BITXOR, False) def __or__(self, other): if getattr(self, "conditional", False) and getattr(other, "conditional", False): return Q(self) | Q(other) raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def bitor(self, other): return self._combine(other, self.BITOR, False) def __radd__(self, other): return self._combine(other, self.ADD, True) def __rsub__(self, other): return self._combine(other, self.SUB, True) def __rmul__(self, other): return self._combine(other, self.MUL, True) def __rtruediv__(self, other): return self._combine(other, self.DIV, True) def __rmod__(self, other): return self._combine(other, self.MOD, True) def __rpow__(self, other): return self._combine(other, self.POW, True) def __rand__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __ror__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __rxor__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __invert__(self): return NegatedExpression(self) class BaseExpression: """Base class for all query expressions.""" empty_result_set_value = NotImplemented # aggregate specific fields is_summary = False _output_field_resolved_to_none = False # Can the expression be used in a WHERE clause? filterable = True # Can the expression can be used as a source expression in Window? window_compatible = False def __init__(self, output_field=None): if output_field is not None: self.output_field = output_field def __getstate__(self): state = self.__dict__.copy() state.pop("convert_value", None) return state def get_db_converters(self, connection): return ( [] if self.convert_value is self._convert_value_noop else [self.convert_value] ) + self.output_field.get_db_converters(connection) def get_source_expressions(self): return [] def set_source_expressions(self, exprs): assert not exprs def _parse_expressions(self, *expressions): return [ arg if hasattr(arg, "resolve_expression") else (F(arg) if isinstance(arg, str) else Value(arg)) for arg in expressions ] def as_sql(self, compiler, connection): """ Responsible for returning a (sql, [params]) tuple to be included in the current query. Different backends can provide their own implementation, by providing an `as_{vendor}` method and patching the Expression: ``` def override_as_sql(self, compiler, connection): # custom logic return super().as_sql(compiler, connection) setattr(Expression, 'as_' + connection.vendor, override_as_sql) ``` Arguments: * compiler: the query compiler responsible for generating the query. Must have a compile method, returning a (sql, [params]) tuple. Calling compiler(value) will return a quoted `value`. * connection: the database connection used for the current query. Return: (sql, params) Where `sql` is a string containing ordered sql parameters to be replaced with the elements of the list `params`. """ raise NotImplementedError("Subclasses must implement as_sql()") @cached_property def contains_aggregate(self): return any( expr and expr.contains_aggregate for expr in self.get_source_expressions() ) @cached_property def contains_over_clause(self): return any( expr and expr.contains_over_clause for expr in self.get_source_expressions() ) @cached_property def contains_column_references(self): return any( expr and expr.contains_column_references for expr in self.get_source_expressions() ) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): """ Provide the chance to do any preprocessing or validation before being added to the query. Arguments: * query: the backend query implementation * allow_joins: boolean allowing or denying use of joins in this query * reuse: a set of reusable joins for multijoins * summarize: a terminal aggregate clause * for_save: whether this expression about to be used in a save or update Return: an Expression to be added to the query. """ c = self.copy() c.is_summary = summarize c.set_source_expressions( [ expr.resolve_expression(query, allow_joins, reuse, summarize) if expr else None for expr in c.get_source_expressions() ] ) return c @property def conditional(self): return isinstance(self.output_field, fields.BooleanField) @property def field(self): return self.output_field @cached_property def output_field(self): """Return the output type of this expressions.""" output_field = self._resolve_output_field() if output_field is None: self._output_field_resolved_to_none = True raise FieldError("Cannot resolve expression type, unknown output_field") return output_field @cached_property def _output_field_or_none(self): """ Return the output field of this expression, or None if _resolve_output_field() didn't return an output type. """ try: return self.output_field except FieldError: if not self._output_field_resolved_to_none: raise def _resolve_output_field(self): """ Attempt to infer the output type of the expression. As a guess, if the output fields of all source fields match then simply infer the same type here. If a source's output field resolves to None, exclude it from this check. If all sources are None, then an error is raised higher up the stack in the output_field property. """ # This guess is mostly a bad idea, but there is quite a lot of code # (especially 3rd party Func subclasses) that depend on it, we'd need a # deprecation path to fix it. sources_iter = ( source for source in self.get_source_fields() if source is not None ) for output_field in sources_iter: for source in sources_iter: if not isinstance(output_field, source.__class__): raise FieldError( "Expression contains mixed types: %s, %s. You must " "set output_field." % ( output_field.__class__.__name__, source.__class__.__name__, ) ) return output_field @staticmethod def _convert_value_noop(value, expression, connection): return value @cached_property def convert_value(self): """ Expressions provide their own converters because users have the option of manually specifying the output_field which may be a different type from the one the database returns. """ field = self.output_field internal_type = field.get_internal_type() if internal_type == "FloatField": return ( lambda value, expression, connection: None if value is None else float(value) ) elif internal_type.endswith("IntegerField"): return ( lambda value, expression, connection: None if value is None else int(value) ) elif internal_type == "DecimalField": return ( lambda value, expression, connection: None if value is None else Decimal(value) ) return self._convert_value_noop def get_lookup(self, lookup): return self.output_field.get_lookup(lookup) def get_transform(self, name): return self.output_field.get_transform(name) def relabeled_clone(self, change_map): clone = self.copy() clone.set_source_expressions( [ e.relabeled_clone(change_map) if e is not None else None for e in self.get_source_expressions() ] ) return clone def replace_expressions(self, replacements): if replacement := replacements.get(self): return replacement clone = self.copy() source_expressions = clone.get_source_expressions() clone.set_source_expressions( [ expr.replace_expressions(replacements) if expr else None for expr in source_expressions ] ) return clone def get_refs(self): refs = set() for expr in self.get_source_expressions(): refs |= expr.get_refs() return refs def copy(self): return copy.copy(self) def prefix_references(self, prefix): clone = self.copy() clone.set_source_expressions( [ F(f"{prefix}{expr.name}") if isinstance(expr, F) else expr.prefix_references(prefix) for expr in self.get_source_expressions() ] ) return clone def get_group_by_cols(self): if not self.contains_aggregate: return [self] cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def get_source_fields(self): """Return the underlying field types used by this aggregate.""" return [e._output_field_or_none for e in self.get_source_expressions()] def asc(self, **kwargs): return OrderBy(self, **kwargs) def desc(self, **kwargs): return OrderBy(self, descending=True, **kwargs) def reverse_ordering(self): return self def flatten(self): """ Recursively yield this expression and all subexpressions, in depth-first order. """ yield self for expr in self.get_source_expressions(): if expr: if hasattr(expr, "flatten"): yield from expr.flatten() else: yield expr def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, EXISTS expressions need to be wrapped in CASE WHEN on Oracle. """ if hasattr(self.output_field, "select_format"): return self.output_field.select_format(compiler, sql, params) return sql, params @deconstructible class Expression(BaseExpression, Combinable): """An expression that can be combined with other expressions.""" @cached_property def identity(self): constructor_signature = inspect.signature(self.__init__) args, kwargs = self._constructor_args signature = constructor_signature.bind_partial(*args, **kwargs) signature.apply_defaults() arguments = signature.arguments.items() identity = [self.__class__] for arg, value in arguments: if isinstance(value, fields.Field): if value.name and value.model: value = (value.model._meta.label, value.name) else: value = type(value) else: value = make_hashable(value) identity.append((arg, value)) return tuple(identity) def __eq__(self, other): if not isinstance(other, Expression): return NotImplemented return other.identity == self.identity def __hash__(self): return hash(self.identity) # Type inference for CombinedExpression.output_field. # Missing items will result in FieldError, by design. # # The current approach for NULL is based on lowest common denominator behavior # i.e. if one of the supported databases is raising an error (rather than # return NULL) for `val <op> NULL`, then Django raises FieldError. _connector_combinations = [ # Numeric operations - operands of same type. { connector: [ (fields.IntegerField, fields.IntegerField, fields.IntegerField), (fields.FloatField, fields.FloatField, fields.FloatField), (fields.DecimalField, fields.DecimalField, fields.DecimalField), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, # Behavior for DIV with integer arguments follows Postgres/SQLite, # not MySQL/Oracle. Combinable.DIV, Combinable.MOD, Combinable.POW, ) }, # Numeric operations - operands of different type. { connector: [ (fields.IntegerField, fields.DecimalField, fields.DecimalField), (fields.DecimalField, fields.IntegerField, fields.DecimalField), (fields.IntegerField, fields.FloatField, fields.FloatField), (fields.FloatField, fields.IntegerField, fields.FloatField), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV, Combinable.MOD, ) }, # Bitwise operators. { connector: [ (fields.IntegerField, fields.IntegerField, fields.IntegerField), ] for connector in ( Combinable.BITAND, Combinable.BITOR, Combinable.BITLEFTSHIFT, Combinable.BITRIGHTSHIFT, Combinable.BITXOR, ) }, # Numeric with NULL. { connector: [ (field_type, NoneType, field_type), (NoneType, field_type, field_type), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV, Combinable.MOD, Combinable.POW, ) for field_type in (fields.IntegerField, fields.DecimalField, fields.FloatField) }, # Date/DateTimeField/DurationField/TimeField. { Combinable.ADD: [ # Date/DateTimeField. (fields.DateField, fields.DurationField, fields.DateTimeField), (fields.DateTimeField, fields.DurationField, fields.DateTimeField), (fields.DurationField, fields.DateField, fields.DateTimeField), (fields.DurationField, fields.DateTimeField, fields.DateTimeField), # DurationField. (fields.DurationField, fields.DurationField, fields.DurationField), # TimeField. (fields.TimeField, fields.DurationField, fields.TimeField), (fields.DurationField, fields.TimeField, fields.TimeField), ], }, { Combinable.SUB: [ # Date/DateTimeField. (fields.DateField, fields.DurationField, fields.DateTimeField), (fields.DateTimeField, fields.DurationField, fields.DateTimeField), (fields.DateField, fields.DateField, fields.DurationField), (fields.DateField, fields.DateTimeField, fields.DurationField), (fields.DateTimeField, fields.DateField, fields.DurationField), (fields.DateTimeField, fields.DateTimeField, fields.DurationField), # DurationField. (fields.DurationField, fields.DurationField, fields.DurationField), # TimeField. (fields.TimeField, fields.DurationField, fields.TimeField), (fields.TimeField, fields.TimeField, fields.DurationField), ], }, ] _connector_combinators = defaultdict(list) def register_combinable_fields(lhs, connector, rhs, result): """ Register combinable types: lhs <connector> rhs -> result e.g. register_combinable_fields( IntegerField, Combinable.ADD, FloatField, FloatField ) """ _connector_combinators[connector].append((lhs, rhs, result)) for d in _connector_combinations: for connector, field_types in d.items(): for lhs, rhs, result in field_types: register_combinable_fields(lhs, connector, rhs, result) @functools.lru_cache(maxsize=128) def _resolve_combined_type(connector, lhs_type, rhs_type): combinators = _connector_combinators.get(connector, ()) for combinator_lhs_type, combinator_rhs_type, combined_type in combinators: if issubclass(lhs_type, combinator_lhs_type) and issubclass( rhs_type, combinator_rhs_type ): return combined_type class CombinedExpression(SQLiteNumericMixin, Expression): def __init__(self, lhs, connector, rhs, output_field=None): super().__init__(output_field=output_field) self.connector = connector self.lhs = lhs self.rhs = rhs def __repr__(self): return "<{}: {}>".format(self.__class__.__name__, self) def __str__(self): return "{} {} {}".format(self.lhs, self.connector, self.rhs) def get_source_expressions(self): return [self.lhs, self.rhs] def set_source_expressions(self, exprs): self.lhs, self.rhs = exprs def _resolve_output_field(self): # We avoid using super() here for reasons given in # Expression._resolve_output_field() combined_type = _resolve_combined_type( self.connector, type(self.lhs._output_field_or_none), type(self.rhs._output_field_or_none), ) if combined_type is None: raise FieldError( f"Cannot infer type of {self.connector!r} expression involving these " f"types: {self.lhs.output_field.__class__.__name__}, " f"{self.rhs.output_field.__class__.__name__}. You must set " f"output_field." ) return combined_type() def as_sql(self, compiler, connection): expressions = [] expression_params = [] sql, params = compiler.compile(self.lhs) expressions.append(sql) expression_params.extend(params) sql, params = compiler.compile(self.rhs) expressions.append(sql) expression_params.extend(params) # order of precedence expression_wrapper = "(%s)" sql = connection.ops.combine_expression(self.connector, expressions) return expression_wrapper % sql, expression_params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): lhs = self.lhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) rhs = self.rhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) if not isinstance(self, (DurationExpression, TemporalSubtraction)): try: lhs_type = lhs.output_field.get_internal_type() except (AttributeError, FieldError): lhs_type = None try: rhs_type = rhs.output_field.get_internal_type() except (AttributeError, FieldError): rhs_type = None if "DurationField" in {lhs_type, rhs_type} and lhs_type != rhs_type: return DurationExpression( self.lhs, self.connector, self.rhs ).resolve_expression( query, allow_joins, reuse, summarize, for_save, ) datetime_fields = {"DateField", "DateTimeField", "TimeField"} if ( self.connector == self.SUB and lhs_type in datetime_fields and lhs_type == rhs_type ): return TemporalSubtraction(self.lhs, self.rhs).resolve_expression( query, allow_joins, reuse, summarize, for_save, ) c = self.copy() c.is_summary = summarize c.lhs = lhs c.rhs = rhs return c class DurationExpression(CombinedExpression): def compile(self, side, compiler, connection): try: output = side.output_field except FieldError: pass else: if output.get_internal_type() == "DurationField": sql, params = compiler.compile(side) return connection.ops.format_for_duration_arithmetic(sql), params return compiler.compile(side) def as_sql(self, compiler, connection): if connection.features.has_native_duration_field: return super().as_sql(compiler, connection) connection.ops.check_expression_support(self) expressions = [] expression_params = [] sql, params = self.compile(self.lhs, compiler, connection) expressions.append(sql) expression_params.extend(params) sql, params = self.compile(self.rhs, compiler, connection) expressions.append(sql) expression_params.extend(params) # order of precedence expression_wrapper = "(%s)" sql = connection.ops.combine_duration_expression(self.connector, expressions) return expression_wrapper % sql, expression_params def as_sqlite(self, compiler, connection, **extra_context): sql, params = self.as_sql(compiler, connection, **extra_context) if self.connector in {Combinable.MUL, Combinable.DIV}: try: lhs_type = self.lhs.output_field.get_internal_type() rhs_type = self.rhs.output_field.get_internal_type() except (AttributeError, FieldError): pass else: allowed_fields = { "DecimalField", "DurationField", "FloatField", "IntegerField", } if lhs_type not in allowed_fields or rhs_type not in allowed_fields: raise DatabaseError( f"Invalid arguments for operator {self.connector}." ) return sql, params class TemporalSubtraction(CombinedExpression): output_field = fields.DurationField() def __init__(self, lhs, rhs): super().__init__(lhs, self.SUB, rhs) def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) lhs = compiler.compile(self.lhs) rhs = compiler.compile(self.rhs) return connection.ops.subtract_temporals( self.lhs.output_field.get_internal_type(), lhs, rhs ) @deconstructible(path="django.db.models.F") class F(Combinable): """An object capable of resolving references to existing query objects.""" def __init__(self, name): """ Arguments: * name: the name of the field this expression references """ self.name = name def __repr__(self): return "{}({})".format(self.__class__.__name__, self.name) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): return query.resolve_ref(self.name, allow_joins, reuse, summarize) def replace_expressions(self, replacements): return replacements.get(self, self) def asc(self, **kwargs): return OrderBy(self, **kwargs) def desc(self, **kwargs): return OrderBy(self, descending=True, **kwargs) def __eq__(self, other): return self.__class__ == other.__class__ and self.name == other.name def __hash__(self): return hash(self.name) def copy(self): return copy.copy(self) class ResolvedOuterRef(F): """ An object that contains a reference to an outer query. In this case, the reference to the outer query has been resolved because the inner query has been used as a subquery. """ contains_aggregate = False contains_over_clause = False def as_sql(self, *args, **kwargs): raise ValueError( "This queryset contains a reference to an outer query and may " "only be used in a subquery." ) def resolve_expression(self, *args, **kwargs): col = super().resolve_expression(*args, **kwargs) # FIXME: Rename possibly_multivalued to multivalued and fix detection # for non-multivalued JOINs (e.g. foreign key fields). This should take # into account only many-to-many and one-to-many relationships. col.possibly_multivalued = LOOKUP_SEP in self.name return col def relabeled_clone(self, relabels): return self def get_group_by_cols(self): return [] class OuterRef(F): contains_aggregate = False def resolve_expression(self, *args, **kwargs): if isinstance(self.name, self.__class__): return self.name return ResolvedOuterRef(self.name) def relabeled_clone(self, relabels): return self @deconstructible(path="django.db.models.Func") class Func(SQLiteNumericMixin, Expression): """An SQL function call.""" function = None template = "%(function)s(%(expressions)s)" arg_joiner = ", " arity = None # The number of arguments the function accepts. def __init__(self, *expressions, output_field=None, **extra): if self.arity is not None and len(expressions) != self.arity: raise TypeError( "'%s' takes exactly %s %s (%s given)" % ( self.__class__.__name__, self.arity, "argument" if self.arity == 1 else "arguments", len(expressions), ) ) super().__init__(output_field=output_field) self.source_expressions = self._parse_expressions(*expressions) self.extra = extra def __repr__(self): args = self.arg_joiner.join(str(arg) for arg in self.source_expressions) extra = {**self.extra, **self._get_repr_options()} if extra: extra = ", ".join( str(key) + "=" + str(val) for key, val in sorted(extra.items()) ) return "{}({}, {})".format(self.__class__.__name__, args, extra) return "{}({})".format(self.__class__.__name__, args) def _get_repr_options(self): """Return a dict of extra __init__() options to include in the repr.""" return {} def get_source_expressions(self): return self.source_expressions def set_source_expressions(self, exprs): self.source_expressions = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize for pos, arg in enumerate(c.source_expressions): c.source_expressions[pos] = arg.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def as_sql( self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context, ): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: try: arg_sql, arg_params = compiler.compile(arg) except EmptyResultSet: empty_result_set_value = getattr( arg, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: raise arg_sql, arg_params = compiler.compile(Value(empty_result_set_value)) except FullResultSet: arg_sql, arg_params = compiler.compile(Value(True)) sql_parts.append(arg_sql) params.extend(arg_params) data = {**self.extra, **extra_context} # Use the first supplied value in this order: the parameter to this # method, a value supplied in __init__()'s **extra (the value in # `data`), or the value defined on the class. if function is not None: data["function"] = function else: data.setdefault("function", self.function) template = template or data.get("template", self.template) arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner) data["expressions"] = data["field"] = arg_joiner.join(sql_parts) return template % data, params def copy(self): copy = super().copy() copy.source_expressions = self.source_expressions[:] copy.extra = self.extra.copy() return copy @deconstructible(path="django.db.models.Value") class Value(SQLiteNumericMixin, Expression): """Represent a wrapped value as a node within an expression.""" # Provide a default value for `for_save` in order to allow unresolved # instances to be compiled until a decision is taken in #25425. for_save = False def __init__(self, value, output_field=None): """ Arguments: * value: the value this expression represents. The value will be added into the sql parameter list and properly quoted. * output_field: an instance of the model field type that this expression will return, such as IntegerField() or CharField(). """ super().__init__(output_field=output_field) self.value = value def __repr__(self): return f"{self.__class__.__name__}({self.value!r})" def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) val = self.value output_field = self._output_field_or_none if output_field is not None: if self.for_save: val = output_field.get_db_prep_save(val, connection=connection) else: val = output_field.get_db_prep_value(val, connection=connection) if hasattr(output_field, "get_placeholder"): return output_field.get_placeholder(val, compiler, connection), [val] if val is None: # cx_Oracle does not always convert None to the appropriate # NULL type (like in case expressions using numbers), so we # use a literal SQL NULL return "NULL", [] return "%s", [val] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) c.for_save = for_save return c def get_group_by_cols(self): return [] def _resolve_output_field(self): if isinstance(self.value, str): return fields.CharField() if isinstance(self.value, bool): return fields.BooleanField() if isinstance(self.value, int): return fields.IntegerField() if isinstance(self.value, float): return fields.FloatField() if isinstance(self.value, datetime.datetime): return fields.DateTimeField() if isinstance(self.value, datetime.date): return fields.DateField() if isinstance(self.value, datetime.time): return fields.TimeField() if isinstance(self.value, datetime.timedelta): return fields.DurationField() if isinstance(self.value, Decimal): return fields.DecimalField() if isinstance(self.value, bytes): return fields.BinaryField() if isinstance(self.value, UUID): return fields.UUIDField() @property def empty_result_set_value(self): return self.value class RawSQL(Expression): def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super().__init__(output_field=output_field) def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params) def as_sql(self, compiler, connection): return "(%s)" % self.sql, self.params def get_group_by_cols(self): return [self] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # Resolve parents fields used in raw SQL. if query.model: for parent in query.model._meta.get_parent_list(): for parent_field in parent._meta.local_fields: _, column_name = parent_field.get_attname_column() if column_name.lower() in self.sql.lower(): query.resolve_ref( parent_field.name, allow_joins, reuse, summarize ) break return super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) class Star(Expression): def __repr__(self): return "'*'" def as_sql(self, compiler, connection): return "*", [] class Col(Expression): contains_column_references = True possibly_multivalued = False def __init__(self, alias, target, output_field=None): if output_field is None: output_field = target super().__init__(output_field=output_field) self.alias, self.target = alias, target def __repr__(self): alias, target = self.alias, self.target identifiers = (alias, str(target)) if alias else (str(target),) return "{}({})".format(self.__class__.__name__, ", ".join(identifiers)) def as_sql(self, compiler, connection): alias, column = self.alias, self.target.column identifiers = (alias, column) if alias else (column,) sql = ".".join(map(compiler.quote_name_unless_alias, identifiers)) return sql, [] def relabeled_clone(self, relabels): if self.alias is None: return self return self.__class__( relabels.get(self.alias, self.alias), self.target, self.output_field ) def get_group_by_cols(self): return [self] def get_db_converters(self, connection): if self.target == self.output_field: return self.output_field.get_db_converters(connection) return self.output_field.get_db_converters( connection ) + self.target.get_db_converters(connection) class Ref(Expression): """ Reference to column alias of the query. For example, Ref('sum_cost') in qs.annotate(sum_cost=Sum('cost')) query. """ def __init__(self, refs, source): super().__init__() self.refs, self.source = refs, source def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source) def get_source_expressions(self): return [self.source] def set_source_expressions(self, exprs): (self.source,) = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # The sub-expression `source` has already been resolved, as this is # just a reference to the name of `source`. return self def get_refs(self): return {self.refs} def relabeled_clone(self, relabels): return self def as_sql(self, compiler, connection): return connection.ops.quote_name(self.refs), [] def get_group_by_cols(self): return [self] class ExpressionList(Func): """ An expression containing multiple expressions. Can be used to provide a list of expressions as an argument to another expression, like a partition clause. """ template = "%(expressions)s" def __init__(self, *expressions, **extra): if not expressions: raise ValueError( "%s requires at least one expression." % self.__class__.__name__ ) super().__init__(*expressions, **extra) def __str__(self): return self.arg_joiner.join(str(arg) for arg in self.source_expressions) def as_sqlite(self, compiler, connection, **extra_context): # Casting to numeric is unnecessary. return self.as_sql(compiler, connection, **extra_context) class OrderByList(Func): template = "ORDER BY %(expressions)s" def __init__(self, *expressions, **extra): expressions = ( ( OrderBy(F(expr[1:]), descending=True) if isinstance(expr, str) and expr[0] == "-" else expr ) for expr in expressions ) super().__init__(*expressions, **extra) def as_sql(self, *args, **kwargs): if not self.source_expressions: return "", () return super().as_sql(*args, **kwargs) def get_group_by_cols(self): group_by_cols = [] for order_by in self.get_source_expressions(): group_by_cols.extend(order_by.get_group_by_cols()) return group_by_cols @deconstructible(path="django.db.models.ExpressionWrapper") class ExpressionWrapper(SQLiteNumericMixin, Expression): """ An expression that can wrap another expression so that it can provide extra context to the inner expression, such as the output_field. """ def __init__(self, expression, output_field): super().__init__(output_field=output_field) self.expression = expression def set_source_expressions(self, exprs): self.expression = exprs[0] def get_source_expressions(self): return [self.expression] def get_group_by_cols(self): if isinstance(self.expression, Expression): expression = self.expression.copy() expression.output_field = self.output_field return expression.get_group_by_cols() # For non-expressions e.g. an SQL WHERE clause, the entire # `expression` must be included in the GROUP BY clause. return super().get_group_by_cols() def as_sql(self, compiler, connection): return compiler.compile(self.expression) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.expression) class NegatedExpression(ExpressionWrapper): """The logical negation of a conditional expression.""" def __init__(self, expression): super().__init__(expression, output_field=fields.BooleanField()) def __invert__(self): return self.expression.copy() def as_sql(self, compiler, connection): try: sql, params = super().as_sql(compiler, connection) except EmptyResultSet: features = compiler.connection.features if not features.supports_boolean_expr_in_select_clause: return "1=1", () return compiler.compile(Value(True)) ops = compiler.connection.ops # Some database backends (e.g. Oracle) don't allow EXISTS() and filters # to be compared to another expression unless they're wrapped in a CASE # WHEN. if not ops.conditional_expression_supported_in_where_clause(self.expression): return f"CASE WHEN {sql} = 0 THEN 1 ELSE 0 END", params return f"NOT {sql}", params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): resolved = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) if not getattr(resolved.expression, "conditional", False): raise TypeError("Cannot negate non-conditional expressions.") return resolved def select_format(self, compiler, sql, params): # Wrap boolean expressions with a CASE WHEN expression if a database # backend (e.g. Oracle) doesn't support boolean expression in SELECT or # GROUP BY list. expression_supported_in_where_clause = ( compiler.connection.ops.conditional_expression_supported_in_where_clause ) if ( not compiler.connection.features.supports_boolean_expr_in_select_clause # Avoid double wrapping. and expression_supported_in_where_clause(self.expression) ): sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql) return sql, params @deconstructible(path="django.db.models.When") class When(Expression): template = "WHEN %(condition)s THEN %(result)s" # This isn't a complete conditional expression, must be used in Case(). conditional = False def __init__(self, condition=None, then=None, **lookups): if lookups: if condition is None: condition, lookups = Q(**lookups), None elif getattr(condition, "conditional", False): condition, lookups = Q(condition, **lookups), None if condition is None or not getattr(condition, "conditional", False) or lookups: raise TypeError( "When() supports a Q object, a boolean expression, or lookups " "as a condition." ) if isinstance(condition, Q) and not condition: raise ValueError("An empty Q() can't be used as a When() condition.") super().__init__(output_field=None) self.condition = condition self.result = self._parse_expressions(then)[0] def __str__(self): return "WHEN %r THEN %r" % (self.condition, self.result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_source_expressions(self): return [self.condition, self.result] def set_source_expressions(self, exprs): self.condition, self.result = exprs def get_source_fields(self): # We're only interested in the fields of the result expressions. return [self.result._output_field_or_none] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize if hasattr(c.condition, "resolve_expression"): c.condition = c.condition.resolve_expression( query, allow_joins, reuse, summarize, False ) c.result = c.result.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def as_sql(self, compiler, connection, template=None, **extra_context): connection.ops.check_expression_support(self) template_params = extra_context sql_params = [] condition_sql, condition_params = compiler.compile(self.condition) template_params["condition"] = condition_sql result_sql, result_params = compiler.compile(self.result) template_params["result"] = result_sql template = template or self.template return template % template_params, ( *sql_params, *condition_params, *result_params, ) def get_group_by_cols(self): # This is not a complete expression and cannot be used in GROUP BY. cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols @deconstructible(path="django.db.models.Case") class Case(SQLiteNumericMixin, Expression): """ An SQL searched CASE expression: CASE WHEN n > 0 THEN 'positive' WHEN n < 0 THEN 'negative' ELSE 'zero' END """ template = "CASE %(cases)s ELSE %(default)s END" case_joiner = " " def __init__(self, *cases, default=None, output_field=None, **extra): if not all(isinstance(case, When) for case in cases): raise TypeError("Positional arguments must all be When objects.") super().__init__(output_field) self.cases = list(cases) self.default = self._parse_expressions(default)[0] self.extra = extra def __str__(self): return "CASE %s, ELSE %r" % ( ", ".join(str(c) for c in self.cases), self.default, ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_source_expressions(self): return self.cases + [self.default] def set_source_expressions(self, exprs): *self.cases, self.default = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize for pos, case in enumerate(c.cases): c.cases[pos] = case.resolve_expression( query, allow_joins, reuse, summarize, for_save ) c.default = c.default.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def copy(self): c = super().copy() c.cases = c.cases[:] return c def as_sql( self, compiler, connection, template=None, case_joiner=None, **extra_context ): connection.ops.check_expression_support(self) if not self.cases: return compiler.compile(self.default) template_params = {**self.extra, **extra_context} case_parts = [] sql_params = [] default_sql, default_params = compiler.compile(self.default) for case in self.cases: try: case_sql, case_params = compiler.compile(case) except EmptyResultSet: continue except FullResultSet: default_sql, default_params = compiler.compile(case.result) break case_parts.append(case_sql) sql_params.extend(case_params) if not case_parts: return default_sql, default_params case_joiner = case_joiner or self.case_joiner template_params["cases"] = case_joiner.join(case_parts) template_params["default"] = default_sql sql_params.extend(default_params) template = template or template_params.get("template", self.template) sql = template % template_params if self._output_field_or_none is not None: sql = connection.ops.unification_cast_sql(self.output_field) % sql return sql, sql_params def get_group_by_cols(self): if not self.cases: return self.default.get_group_by_cols() return super().get_group_by_cols() class Subquery(BaseExpression, Combinable): """ An explicit subquery. It may contain OuterRef() references to the outer query which will be resolved when it is applied to that query. """ template = "(%(subquery)s)" contains_aggregate = False empty_result_set_value = None def __init__(self, queryset, output_field=None, **extra): # Allow the usage of both QuerySet and sql.Query objects. self.query = getattr(queryset, "query", queryset).clone() self.query.subquery = True self.extra = extra super().__init__(output_field) def get_source_expressions(self): return [self.query] def set_source_expressions(self, exprs): self.query = exprs[0] def _resolve_output_field(self): return self.query.output_field def copy(self): clone = super().copy() clone.query = clone.query.clone() return clone @property def external_aliases(self): return self.query.external_aliases def get_external_cols(self): return self.query.get_external_cols() def as_sql(self, compiler, connection, template=None, **extra_context): connection.ops.check_expression_support(self) template_params = {**self.extra, **extra_context} subquery_sql, sql_params = self.query.as_sql(compiler, connection) template_params["subquery"] = subquery_sql[1:-1] template = template or template_params.get("template", self.template) sql = template % template_params return sql, sql_params def get_group_by_cols(self): return self.query.get_group_by_cols(wrapper=self) class Exists(Subquery): template = "EXISTS(%(subquery)s)" output_field = fields.BooleanField() def __init__(self, queryset, **kwargs): super().__init__(queryset, **kwargs) self.query = self.query.exists() def select_format(self, compiler, sql, params): # Wrap EXISTS() with a CASE WHEN expression if a database backend # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP # BY list. if not compiler.connection.features.supports_boolean_expr_in_select_clause: sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql) return sql, params @deconstructible(path="django.db.models.OrderBy") class OrderBy(Expression): template = "%(expression)s %(ordering)s" conditional = False def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None): if nulls_first and nulls_last: raise ValueError("nulls_first and nulls_last are mutually exclusive") if nulls_first is False or nulls_last is False: raise ValueError("nulls_first and nulls_last values must be True or None.") self.nulls_first = nulls_first self.nulls_last = nulls_last self.descending = descending if not hasattr(expression, "resolve_expression"): raise ValueError("expression must be an expression type") self.expression = expression def __repr__(self): return "{}({}, descending={})".format( self.__class__.__name__, self.expression, self.descending ) def set_source_expressions(self, exprs): self.expression = exprs[0] def get_source_expressions(self): return [self.expression] def as_sql(self, compiler, connection, template=None, **extra_context): template = template or self.template if connection.features.supports_order_by_nulls_modifier: if self.nulls_last: template = "%s NULLS LAST" % template elif self.nulls_first: template = "%s NULLS FIRST" % template else: if self.nulls_last and not ( self.descending and connection.features.order_by_nulls_first ): template = "%%(expression)s IS NULL, %s" % template elif self.nulls_first and not ( not self.descending and connection.features.order_by_nulls_first ): template = "%%(expression)s IS NOT NULL, %s" % template connection.ops.check_expression_support(self) expression_sql, params = compiler.compile(self.expression) placeholders = { "expression": expression_sql, "ordering": "DESC" if self.descending else "ASC", **extra_context, } params *= template.count("%(expression)s") return (template % placeholders).rstrip(), params def as_oracle(self, compiler, connection): # Oracle doesn't allow ORDER BY EXISTS() or filters unless it's wrapped # in a CASE WHEN. if connection.ops.conditional_expression_supported_in_where_clause( self.expression ): copy = self.copy() copy.expression = Case( When(self.expression, then=True), default=False, ) return copy.as_sql(compiler, connection) return self.as_sql(compiler, connection) def get_group_by_cols(self): cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def reverse_ordering(self): self.descending = not self.descending if self.nulls_first: self.nulls_last = True self.nulls_first = None elif self.nulls_last: self.nulls_first = True self.nulls_last = None return self def asc(self): self.descending = False def desc(self): self.descending = True class Window(SQLiteNumericMixin, Expression): template = "%(expression)s OVER (%(window)s)" # Although the main expression may either be an aggregate or an # expression with an aggregate function, the GROUP BY that will # be introduced in the query as a result is not desired. contains_aggregate = False contains_over_clause = True def __init__( self, expression, partition_by=None, order_by=None, frame=None, output_field=None, ): self.partition_by = partition_by self.order_by = order_by self.frame = frame if not getattr(expression, "window_compatible", False): raise ValueError( "Expression '%s' isn't compatible with OVER clauses." % expression.__class__.__name__ ) if self.partition_by is not None: if not isinstance(self.partition_by, (tuple, list)): self.partition_by = (self.partition_by,) self.partition_by = ExpressionList(*self.partition_by) if self.order_by is not None: if isinstance(self.order_by, (list, tuple)): self.order_by = OrderByList(*self.order_by) elif isinstance(self.order_by, (BaseExpression, str)): self.order_by = OrderByList(self.order_by) else: raise ValueError( "Window.order_by must be either a string reference to a " "field, an expression, or a list or tuple of them." ) super().__init__(output_field=output_field) self.source_expression = self._parse_expressions(expression)[0] def _resolve_output_field(self): return self.source_expression.output_field def get_source_expressions(self): return [self.source_expression, self.partition_by, self.order_by, self.frame] def set_source_expressions(self, exprs): self.source_expression, self.partition_by, self.order_by, self.frame = exprs def as_sql(self, compiler, connection, template=None): connection.ops.check_expression_support(self) if not connection.features.supports_over_clause: raise NotSupportedError("This backend does not support window expressions.") expr_sql, params = compiler.compile(self.source_expression) window_sql, window_params = [], () if self.partition_by is not None: sql_expr, sql_params = self.partition_by.as_sql( compiler=compiler, connection=connection, template="PARTITION BY %(expressions)s", ) window_sql.append(sql_expr) window_params += tuple(sql_params) if self.order_by is not None: order_sql, order_params = compiler.compile(self.order_by) window_sql.append(order_sql) window_params += tuple(order_params) if self.frame: frame_sql, frame_params = compiler.compile(self.frame) window_sql.append(frame_sql) window_params += tuple(frame_params) template = template or self.template return ( template % {"expression": expr_sql, "window": " ".join(window_sql).strip()}, (*params, *window_params), ) def as_sqlite(self, compiler, connection): if isinstance(self.output_field, fields.DecimalField): # Casting to numeric must be outside of the window expression. copy = self.copy() source_expressions = copy.get_source_expressions() source_expressions[0].output_field = fields.FloatField() copy.set_source_expressions(source_expressions) return super(Window, copy).as_sqlite(compiler, connection) return self.as_sql(compiler, connection) def __str__(self): return "{} OVER ({}{}{})".format( str(self.source_expression), "PARTITION BY " + str(self.partition_by) if self.partition_by else "", str(self.order_by or ""), str(self.frame or ""), ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_group_by_cols(self): group_by_cols = [] if self.partition_by: group_by_cols.extend(self.partition_by.get_group_by_cols()) if self.order_by is not None: group_by_cols.extend(self.order_by.get_group_by_cols()) return group_by_cols class WindowFrame(Expression): """ Model the frame clause in window expressions. There are two types of frame clauses which are subclasses, however, all processing and validation (by no means intended to be complete) is done here. Thus, providing an end for a frame is optional (the default is UNBOUNDED FOLLOWING, which is the last row in the frame). """ template = "%(frame_type)s BETWEEN %(start)s AND %(end)s" def __init__(self, start=None, end=None): self.start = Value(start) self.end = Value(end) def set_source_expressions(self, exprs): self.start, self.end = exprs def get_source_expressions(self): return [self.start, self.end] def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) start, end = self.window_frame_start_end( connection, self.start.value, self.end.value ) return ( self.template % { "frame_type": self.frame_type, "start": start, "end": end, }, [], ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_group_by_cols(self): return [] def __str__(self): if self.start.value is not None and self.start.value < 0: start = "%d %s" % (abs(self.start.value), connection.ops.PRECEDING) elif self.start.value is not None and self.start.value == 0: start = connection.ops.CURRENT_ROW else: start = connection.ops.UNBOUNDED_PRECEDING if self.end.value is not None and self.end.value > 0: end = "%d %s" % (self.end.value, connection.ops.FOLLOWING) elif self.end.value is not None and self.end.value == 0: end = connection.ops.CURRENT_ROW else: end = connection.ops.UNBOUNDED_FOLLOWING return self.template % { "frame_type": self.frame_type, "start": start, "end": end, } def window_frame_start_end(self, connection, start, end): raise NotImplementedError("Subclasses must implement window_frame_start_end().") class RowRange(WindowFrame): frame_type = "ROWS" def window_frame_start_end(self, connection, start, end): return connection.ops.window_frame_rows_start_end(start, end) class ValueRange(WindowFrame): frame_type = "RANGE" def window_frame_start_end(self, connection, start, end): return connection.ops.window_frame_range_start_end(start, end)
3e348d22fc656fa4a426dd02f4e0dce78a43063da47e91d248a82a342a5e384b
from enum import Enum from types import NoneType from django.core.exceptions import FieldError, ValidationError from django.db import connections from django.db.models.expressions import Exists, ExpressionList, F from django.db.models.indexes import IndexExpression from django.db.models.lookups import Exact from django.db.models.query_utils import Q from django.db.models.sql.query import Query from django.db.utils import DEFAULT_DB_ALIAS from django.utils.translation import gettext_lazy as _ __all__ = ["BaseConstraint", "CheckConstraint", "Deferrable", "UniqueConstraint"] class BaseConstraint: default_violation_error_message = _("Constraint “%(name)s” is violated.") violation_error_message = None def __init__(self, name, violation_error_message=None): self.name = name if violation_error_message is not None: self.violation_error_message = violation_error_message else: self.violation_error_message = self.default_violation_error_message @property def contains_expressions(self): return False def constraint_sql(self, model, schema_editor): raise NotImplementedError("This method must be implemented by a subclass.") def create_sql(self, model, schema_editor): raise NotImplementedError("This method must be implemented by a subclass.") def remove_sql(self, model, schema_editor): raise NotImplementedError("This method must be implemented by a subclass.") def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): raise NotImplementedError("This method must be implemented by a subclass.") def get_violation_error_message(self): return self.violation_error_message % {"name": self.name} def deconstruct(self): path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) path = path.replace("django.db.models.constraints", "django.db.models") kwargs = {"name": self.name} if ( self.violation_error_message is not None and self.violation_error_message != self.default_violation_error_message ): kwargs["violation_error_message"] = self.violation_error_message return (path, (), kwargs) def clone(self): _, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) class CheckConstraint(BaseConstraint): def __init__(self, *, check, name, violation_error_message=None): self.check = check if not getattr(check, "conditional", False): raise TypeError( "CheckConstraint.check must be a Q instance or boolean expression." ) super().__init__(name, violation_error_message=violation_error_message) def _get_check_sql(self, model, schema_editor): query = Query(model=model, alias_cols=False) where = query.build_where(self.check) compiler = query.get_compiler(connection=schema_editor.connection) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params) def constraint_sql(self, model, schema_editor): check = self._get_check_sql(model, schema_editor) return schema_editor._check_sql(self.name, check) def create_sql(self, model, schema_editor): check = self._get_check_sql(model, schema_editor) return schema_editor._create_check_sql(model, self.name, check) def remove_sql(self, model, schema_editor): return schema_editor._delete_check_sql(model, self.name) def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): against = instance._get_field_value_map(meta=model._meta, exclude=exclude) try: if not Q(self.check).check(against, using=using): raise ValidationError(self.get_violation_error_message()) except FieldError: pass def __repr__(self): return "<%s: check=%s name=%s>" % ( self.__class__.__qualname__, self.check, repr(self.name), ) def __eq__(self, other): if isinstance(other, CheckConstraint): return ( self.name == other.name and self.check == other.check and self.violation_error_message == other.violation_error_message ) return super().__eq__(other) def deconstruct(self): path, args, kwargs = super().deconstruct() kwargs["check"] = self.check return path, args, kwargs class Deferrable(Enum): DEFERRED = "deferred" IMMEDIATE = "immediate" # A similar format was proposed for Python 3.10. def __repr__(self): return f"{self.__class__.__qualname__}.{self._name_}" class UniqueConstraint(BaseConstraint): def __init__( self, *expressions, fields=(), name=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None, ): if not name: raise ValueError("A unique constraint must be named.") if not expressions and not fields: raise ValueError( "At least one field or expression is required to define a " "unique constraint." ) if expressions and fields: raise ValueError( "UniqueConstraint.fields and expressions are mutually exclusive." ) if not isinstance(condition, (NoneType, Q)): raise ValueError("UniqueConstraint.condition must be a Q instance.") if condition and deferrable: raise ValueError("UniqueConstraint with conditions cannot be deferred.") if include and deferrable: raise ValueError("UniqueConstraint with include fields cannot be deferred.") if opclasses and deferrable: raise ValueError("UniqueConstraint with opclasses cannot be deferred.") if expressions and deferrable: raise ValueError("UniqueConstraint with expressions cannot be deferred.") if expressions and opclasses: raise ValueError( "UniqueConstraint.opclasses cannot be used with expressions. " "Use django.contrib.postgres.indexes.OpClass() instead." ) if not isinstance(deferrable, (NoneType, Deferrable)): raise ValueError( "UniqueConstraint.deferrable must be a Deferrable instance." ) if not isinstance(include, (NoneType, list, tuple)): raise ValueError("UniqueConstraint.include must be a list or tuple.") if not isinstance(opclasses, (list, tuple)): raise ValueError("UniqueConstraint.opclasses must be a list or tuple.") if opclasses and len(fields) != len(opclasses): raise ValueError( "UniqueConstraint.fields and UniqueConstraint.opclasses must " "have the same number of elements." ) self.fields = tuple(fields) self.condition = condition self.deferrable = deferrable self.include = tuple(include) if include else () self.opclasses = opclasses self.expressions = tuple( F(expression) if isinstance(expression, str) else expression for expression in expressions ) super().__init__(name, violation_error_message=violation_error_message) @property def contains_expressions(self): return bool(self.expressions) def _get_condition_sql(self, model, schema_editor): if self.condition is None: return None query = Query(model=model, alias_cols=False) where = query.build_where(self.condition) compiler = query.get_compiler(connection=schema_editor.connection) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params) def _get_index_expressions(self, model, schema_editor): if not self.expressions: return None index_expressions = [] for expression in self.expressions: index_expression = IndexExpression(expression) index_expression.set_wrapper_classes(schema_editor.connection) index_expressions.append(index_expression) return ExpressionList(*index_expressions).resolve_expression( Query(model, alias_cols=False), ) def constraint_sql(self, model, schema_editor): fields = [model._meta.get_field(field_name) for field_name in self.fields] include = [ model._meta.get_field(field_name).column for field_name in self.include ] condition = self._get_condition_sql(model, schema_editor) expressions = self._get_index_expressions(model, schema_editor) return schema_editor._unique_sql( model, fields, self.name, condition=condition, deferrable=self.deferrable, include=include, opclasses=self.opclasses, expressions=expressions, ) def create_sql(self, model, schema_editor): fields = [model._meta.get_field(field_name) for field_name in self.fields] include = [ model._meta.get_field(field_name).column for field_name in self.include ] condition = self._get_condition_sql(model, schema_editor) expressions = self._get_index_expressions(model, schema_editor) return schema_editor._create_unique_sql( model, fields, self.name, condition=condition, deferrable=self.deferrable, include=include, opclasses=self.opclasses, expressions=expressions, ) def remove_sql(self, model, schema_editor): condition = self._get_condition_sql(model, schema_editor) include = [ model._meta.get_field(field_name).column for field_name in self.include ] expressions = self._get_index_expressions(model, schema_editor) return schema_editor._delete_unique_sql( model, self.name, condition=condition, deferrable=self.deferrable, include=include, opclasses=self.opclasses, expressions=expressions, ) def __repr__(self): return "<%s:%s%s%s%s%s%s%s>" % ( self.__class__.__qualname__, "" if not self.fields else " fields=%s" % repr(self.fields), "" if not self.expressions else " expressions=%s" % repr(self.expressions), " name=%s" % repr(self.name), "" if self.condition is None else " condition=%s" % self.condition, "" if self.deferrable is None else " deferrable=%r" % self.deferrable, "" if not self.include else " include=%s" % repr(self.include), "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), ) def __eq__(self, other): if isinstance(other, UniqueConstraint): return ( self.name == other.name and self.fields == other.fields and self.condition == other.condition and self.deferrable == other.deferrable and self.include == other.include and self.opclasses == other.opclasses and self.expressions == other.expressions and self.violation_error_message == other.violation_error_message ) return super().__eq__(other) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fields: kwargs["fields"] = self.fields if self.condition: kwargs["condition"] = self.condition if self.deferrable: kwargs["deferrable"] = self.deferrable if self.include: kwargs["include"] = self.include if self.opclasses: kwargs["opclasses"] = self.opclasses return path, self.expressions, kwargs def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): queryset = model._default_manager.using(using) if self.fields: lookup_kwargs = {} for field_name in self.fields: if exclude and field_name in exclude: return field = model._meta.get_field(field_name) lookup_value = getattr(instance, field.attname) if lookup_value is None or ( lookup_value == "" and connections[using].features.interprets_empty_strings_as_nulls ): # A composite constraint containing NULL value cannot cause # a violation since NULL != NULL in SQL. return lookup_kwargs[field.name] = lookup_value queryset = queryset.filter(**lookup_kwargs) else: # Ignore constraints with excluded fields. if exclude: for expression in self.expressions: if hasattr(expression, "flatten"): for expr in expression.flatten(): if isinstance(expr, F) and expr.name in exclude: return elif isinstance(expression, F) and expression.name in exclude: return replacements = { F(field): value for field, value in instance._get_field_value_map( meta=model._meta, exclude=exclude ).items() } expressions = [ Exact(expr, expr.replace_expressions(replacements)) for expr in self.expressions ] queryset = queryset.filter(*expressions) model_class_pk = instance._get_pk_val(model._meta) if not instance._state.adding and model_class_pk is not None: queryset = queryset.exclude(pk=model_class_pk) if not self.condition: if queryset.exists(): if self.expressions: raise ValidationError(self.get_violation_error_message()) # When fields are defined, use the unique_error_message() for # backward compatibility. for model, constraints in instance.get_constraints(): for constraint in constraints: if constraint is self: raise ValidationError( instance.unique_error_message(model, self.fields) ) else: against = instance._get_field_value_map(meta=model._meta, exclude=exclude) try: if (self.condition & Exists(queryset.filter(self.condition))).check( against, using=using ): raise ValidationError(self.get_violation_error_message()) except FieldError: pass
f5853e34826951d715aaf822ad92f3223d629f71330f2dab990a823ce5f5f88c
import datetime import decimal import functools import logging import time from contextlib import contextmanager from hashlib import md5 from django.db import NotSupportedError from django.utils.dateparse import parse_time logger = logging.getLogger("django.db.backends") class CursorWrapper: def __init__(self, cursor, db): self.cursor = cursor self.db = db WRAP_ERROR_ATTRS = frozenset(["fetchone", "fetchmany", "fetchall", "nextset"]) def __getattr__(self, attr): cursor_attr = getattr(self.cursor, attr) if attr in CursorWrapper.WRAP_ERROR_ATTRS: return self.db.wrap_database_errors(cursor_attr) else: return cursor_attr def __iter__(self): with self.db.wrap_database_errors: yield from self.cursor def __enter__(self): return self def __exit__(self, type, value, traceback): # Close instead of passing through to avoid backend-specific behavior # (#17671). Catch errors liberally because errors in cleanup code # aren't useful. try: self.close() except self.db.Database.Error: pass # The following methods cannot be implemented in __getattr__, because the # code must run when the method is invoked, not just when it is accessed. def callproc(self, procname, params=None, kparams=None): # Keyword parameters for callproc aren't supported in PEP 249, but the # database driver may support them (e.g. cx_Oracle). if kparams is not None and not self.db.features.supports_callproc_kwargs: raise NotSupportedError( "Keyword parameters for callproc are not supported on this " "database backend." ) self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None and kparams is None: return self.cursor.callproc(procname) elif kparams is None: return self.cursor.callproc(procname, params) else: params = params or () return self.cursor.callproc(procname, params, kparams) def execute(self, sql, params=None): return self._execute_with_wrappers( sql, params, many=False, executor=self._execute ) def executemany(self, sql, param_list): return self._execute_with_wrappers( sql, param_list, many=True, executor=self._executemany ) def _execute_with_wrappers(self, sql, params, many, executor): context = {"connection": self.db, "cursor": self} for wrapper in reversed(self.db.execute_wrappers): executor = functools.partial(wrapper, executor) return executor(sql, params, many, context) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: # params default might be backend specific. return self.cursor.execute(sql) else: return self.cursor.execute(sql, params) def _executemany(self, sql, param_list, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: return self.cursor.executemany(sql, param_list) class CursorDebugWrapper(CursorWrapper): # XXX callproc isn't instrumented at this time. def execute(self, sql, params=None): with self.debug_sql(sql, params, use_last_executed_query=True): return super().execute(sql, params) def executemany(self, sql, param_list): with self.debug_sql(sql, param_list, many=True): return super().executemany(sql, param_list) @contextmanager def debug_sql( self, sql=None, params=None, use_last_executed_query=False, many=False ): start = time.monotonic() try: yield finally: stop = time.monotonic() duration = stop - start if use_last_executed_query: sql = self.db.ops.last_executed_query(self.cursor, sql, params) try: times = len(params) if many else "" except TypeError: # params could be an iterator. times = "?" self.db.queries_log.append( { "sql": "%s times: %s" % (times, sql) if many else sql, "time": "%.3f" % duration, } ) logger.debug( "(%.3f) %s; args=%s; alias=%s", duration, sql, params, self.db.alias, extra={ "duration": duration, "sql": sql, "params": params, "alias": self.db.alias, }, ) @contextmanager def debug_transaction(connection, sql): start = time.monotonic() try: yield finally: if connection.queries_logged: stop = time.monotonic() duration = stop - start connection.queries_log.append( { "sql": "%s" % sql, "time": "%.3f" % duration, } ) logger.debug( "(%.3f) %s; args=%s; alias=%s", duration, sql, None, connection.alias, extra={ "duration": duration, "sql": sql, "alias": connection.alias, }, ) def split_tzname_delta(tzname): """ Split a time zone name into a 3-tuple of (name, sign, offset). """ for sign in ["+", "-"]: if sign in tzname: name, offset = tzname.rsplit(sign, 1) if offset and parse_time(offset): return name, sign, offset return tzname, None, None ############################################### # Converters from database (string) to Python # ############################################### def typecast_date(s): return ( datetime.date(*map(int, s.split("-"))) if s else None ) # return None if s is null def typecast_time(s): # does NOT store time zone information if not s: return None hour, minutes, seconds = s.split(":") if "." in seconds: # check whether seconds have a fractional part seconds, microseconds = seconds.split(".") else: microseconds = "0" return datetime.time( int(hour), int(minutes), int(seconds), int((microseconds + "000000")[:6]) ) def typecast_timestamp(s): # does NOT store time zone information # "2005-07-29 15:48:00.590358-05" # "2005-07-29 09:56:00-05" if not s: return None if " " not in s: return typecast_date(s) d, t = s.split() # Remove timezone information. if "-" in t: t, _ = t.split("-", 1) elif "+" in t: t, _ = t.split("+", 1) dates = d.split("-") times = t.split(":") seconds = times[2] if "." in seconds: # check whether seconds have a fractional part seconds, microseconds = seconds.split(".") else: microseconds = "0" return datetime.datetime( int(dates[0]), int(dates[1]), int(dates[2]), int(times[0]), int(times[1]), int(seconds), int((microseconds + "000000")[:6]), ) ############################################### # Converters from Python to database (string) # ############################################### def split_identifier(identifier): """ Split an SQL identifier into a two element tuple of (namespace, name). The identifier could be a table, column, or sequence name might be prefixed by a namespace. """ try: namespace, name = identifier.split('"."') except ValueError: namespace, name = "", identifier return namespace.strip('"'), name.strip('"') def truncate_name(identifier, length=None, hash_len=4): """ Shorten an SQL identifier to a repeatable mangled version with the given length. If a quote stripped name contains a namespace, e.g. USERNAME"."TABLE, truncate the table portion only. """ namespace, name = split_identifier(identifier) if length is None or len(name) <= length: return identifier digest = names_digest(name, length=hash_len) return "%s%s%s" % ( '%s"."' % namespace if namespace else "", name[: length - hash_len], digest, ) def names_digest(*args, length): """ Generate a 32-bit digest of a set of arguments that can be used to shorten identifying names. """ h = md5(usedforsecurity=False) for arg in args: h.update(arg.encode()) return h.hexdigest()[:length] def format_number(value, max_digits, decimal_places): """ Format a number into a string with the requisite number of digits and decimal places. """ if value is None: return None context = decimal.getcontext().copy() if max_digits is not None: context.prec = max_digits if decimal_places is not None: value = value.quantize( decimal.Decimal(1).scaleb(-decimal_places), context=context ) else: context.traps[decimal.Rounded] = 1 value = context.create_decimal(value) return "{:f}".format(value) def strip_quotes(table_name): """ Strip quotes off of quoted table names to make them safe for use in index names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming scheme) becomes 'USER"."TABLE'. """ has_quotes = table_name.startswith('"') and table_name.endswith('"') return table_name[1:-1] if has_quotes else table_name
25c259c4a8e2c9ee68a06a7974fd7758ea054291f9d2a7b7511d31e769fc4aad
import functools import inspect from functools import partial from django import forms from django.apps import apps from django.conf import SettingsReference, settings from django.core import checks, exceptions from django.db import connection, router from django.db.backends import utils from django.db.models import Q from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL from django.db.models.query_utils import PathInfo from django.db.models.utils import make_model_tuple from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from . import Field from .mixins import FieldCacheMixin from .related_descriptors import ( ForeignKeyDeferredAttribute, ForwardManyToOneDescriptor, ForwardOneToOneDescriptor, ManyToManyDescriptor, ReverseManyToOneDescriptor, ReverseOneToOneDescriptor, ) from .related_lookups import ( RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn, RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual, ) from .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel RECURSIVE_RELATIONSHIP_CONSTANT = "self" def resolve_relation(scope_model, relation): """ Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model. The relation argument can be: * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case the model argument will be returned. * A bare model name without an app_label, in which case scope_model's app_label will be prepended. * An "app_label.ModelName" string. * A model class, which will be returned unchanged. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: relation = scope_model # Look for an "app.Model" relation if isinstance(relation, str): if "." not in relation: relation = "%s.%s" % (scope_model._meta.app_label, relation) return relation def lazy_related_operation(function, model, *related_models, **kwargs): """ Schedule `function` to be called once `model` and all `related_models` have been imported and registered with the app registry. `function` will be called with the newly-loaded model classes as its positional arguments, plus any optional keyword arguments. The `model` argument must be a model class. Each subsequent positional argument is another model, or a reference to another model - see `resolve_relation()` for the various forms these may take. Any relative references will be resolved relative to `model`. This is a convenience wrapper for `Apps.lazy_model_operation` - the app registry model used is the one found in `model._meta.apps`. """ models = [model] + [resolve_relation(model, rel) for rel in related_models] model_keys = (make_model_tuple(m) for m in models) apps = model._meta.apps return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) class RelatedField(FieldCacheMixin, Field): """Base class that all relational fields inherit from.""" # Field flags one_to_many = False one_to_one = False many_to_many = False many_to_one = False def __init__( self, related_name=None, related_query_name=None, limit_choices_to=None, **kwargs, ): self._related_name = related_name self._related_query_name = related_query_name self._limit_choices_to = limit_choices_to super().__init__(**kwargs) @cached_property def related_model(self): # Can't cache this property until all the models are loaded. apps.check_models_ready() return self.remote_field.model def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_related_name_is_valid(), *self._check_related_query_name_is_valid(), *self._check_relation_model_exists(), *self._check_referencing_to_swapped_model(), *self._check_clashes(), ] def _check_related_name_is_valid(self): import keyword related_name = self.remote_field.related_name if related_name is None: return [] is_valid_id = ( not keyword.iskeyword(related_name) and related_name.isidentifier() ) if not (is_valid_id or related_name.endswith("+")): return [ checks.Error( "The name '%s' is invalid related_name for field %s.%s" % ( self.remote_field.related_name, self.model._meta.object_name, self.name, ), hint=( "Related name must be a valid Python identifier or end with a " "'+'" ), obj=self, id="fields.E306", ) ] return [] def _check_related_query_name_is_valid(self): if self.remote_field.is_hidden(): return [] rel_query_name = self.related_query_name() errors = [] if rel_query_name.endswith("_"): errors.append( checks.Error( "Reverse query name '%s' must not end with an underscore." % rel_query_name, hint=( "Add or change a related_name or related_query_name " "argument for this field." ), obj=self, id="fields.E308", ) ) if LOOKUP_SEP in rel_query_name: errors.append( checks.Error( "Reverse query name '%s' must not contain '%s'." % (rel_query_name, LOOKUP_SEP), hint=( "Add or change a related_name or related_query_name " "argument for this field." ), obj=self, id="fields.E309", ) ) return errors def _check_relation_model_exists(self): rel_is_missing = self.remote_field.model not in self.opts.apps.get_models() rel_is_string = isinstance(self.remote_field.model, str) model_name = ( self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name ) if rel_is_missing and ( rel_is_string or not self.remote_field.model._meta.swapped ): return [ checks.Error( "Field defines a relation with model '%s', which is either " "not installed, or is abstract." % model_name, obj=self, id="fields.E300", ) ] return [] def _check_referencing_to_swapped_model(self): if ( self.remote_field.model not in self.opts.apps.get_models() and not isinstance(self.remote_field.model, str) and self.remote_field.model._meta.swapped ): return [ checks.Error( "Field defines a relation with the model '%s', which has " "been swapped out." % self.remote_field.model._meta.label, hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable, obj=self, id="fields.E301", ) ] return [] def _check_clashes(self): """Check accessor and reverse query name clashes.""" from django.db.models.base import ModelBase errors = [] opts = self.model._meta # f.remote_field.model may be a string instead of a model. Skip if # model name is not resolved. if not isinstance(self.remote_field.model, ModelBase): return [] # Consider that we are checking field `Model.foreign` and the models # are: # # class Target(models.Model): # model = models.IntegerField() # model_set = models.IntegerField() # # class Model(models.Model): # foreign = models.ForeignKey(Target) # m2m = models.ManyToManyField(Target) # rel_opts.object_name == "Target" rel_opts = self.remote_field.model._meta # If the field doesn't install a backward relation on the target model # (so `is_hidden` returns True), then there are no clashes to check # and we can skip these fields. rel_is_hidden = self.remote_field.is_hidden() rel_name = self.remote_field.get_accessor_name() # i. e. "model_set" rel_query_name = self.related_query_name() # i. e. "model" # i.e. "app_label.Model.field". field_name = "%s.%s" % (opts.label, self.name) # Check clashes between accessor or reverse query name of `field` # and any other field name -- i.e. accessor for Model.foreign is # model_set and it clashes with Target.model_set. potential_clashes = rel_opts.fields + rel_opts.many_to_many for clash_field in potential_clashes: # i.e. "app_label.Target.model_set". clash_name = "%s.%s" % (rel_opts.label, clash_field.name) if not rel_is_hidden and clash_field.name == rel_name: errors.append( checks.Error( f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " f"for '{field_name}' clashes with field name " f"'{clash_name}'.", hint=( "Rename field '%s', or add/change a related_name " "argument to the definition for field '%s'." ) % (clash_name, field_name), obj=self, id="fields.E302", ) ) if clash_field.name == rel_query_name: errors.append( checks.Error( "Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name), hint=( "Rename field '%s', or add/change a related_name " "argument to the definition for field '%s'." ) % (clash_name, field_name), obj=self, id="fields.E303", ) ) # Check clashes between accessors/reverse query names of `field` and # any other field accessor -- i. e. Model.foreign accessor clashes with # Model.m2m accessor. potential_clashes = (r for r in rel_opts.related_objects if r.field is not self) for clash_field in potential_clashes: # i.e. "app_label.Model.m2m". clash_name = "%s.%s" % ( clash_field.related_model._meta.label, clash_field.field.name, ) if not rel_is_hidden and clash_field.get_accessor_name() == rel_name: errors.append( checks.Error( f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " f"for '{field_name}' clashes with reverse accessor for " f"'{clash_name}'.", hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." ) % (field_name, clash_name), obj=self, id="fields.E304", ) ) if clash_field.get_accessor_name() == rel_query_name: errors.append( checks.Error( "Reverse query name for '%s' clashes with reverse query name " "for '%s'." % (field_name, clash_name), hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." ) % (field_name, clash_name), obj=self, id="fields.E305", ) ) return errors def db_type(self, connection): # By default related field will not have a column as it relates to # columns from another table. return None def contribute_to_class(self, cls, name, private_only=False, **kwargs): super().contribute_to_class(cls, name, private_only=private_only, **kwargs) self.opts = cls._meta if not cls._meta.abstract: if self.remote_field.related_name: related_name = self.remote_field.related_name else: related_name = self.opts.default_related_name if related_name: related_name %= { "class": cls.__name__.lower(), "model_name": cls._meta.model_name.lower(), "app_label": cls._meta.app_label.lower(), } self.remote_field.related_name = related_name if self.remote_field.related_query_name: related_query_name = self.remote_field.related_query_name % { "class": cls.__name__.lower(), "app_label": cls._meta.app_label.lower(), } self.remote_field.related_query_name = related_query_name def resolve_related_class(model, related, field): field.remote_field.model = related field.do_related_class(related, model) lazy_related_operation( resolve_related_class, cls, self.remote_field.model, field=self ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self._limit_choices_to: kwargs["limit_choices_to"] = self._limit_choices_to if self._related_name is not None: kwargs["related_name"] = self._related_name if self._related_query_name is not None: kwargs["related_query_name"] = self._related_query_name return name, path, args, kwargs def get_forward_related_filter(self, obj): """ Return the keyword arguments that when supplied to self.model.object.filter(), would select all instances related through this field to the remote obj. This is used to build the querysets returned by related descriptors. obj is an instance of self.related_field.model. """ return { "%s__%s" % (self.name, rh_field.name): getattr(obj, rh_field.attname) for _, rh_field in self.related_fields } def get_reverse_related_filter(self, obj): """ Complement to get_forward_related_filter(). Return the keyword arguments that when passed to self.related_field.model.object.filter() select all instances of self.related_field.model related through this field to obj. obj is an instance of self.model. """ base_q = Q.create( [ (rh_field.attname, getattr(obj, lh_field.attname)) for lh_field, rh_field in self.related_fields ] ) descriptor_filter = self.get_extra_descriptor_filter(obj) if isinstance(descriptor_filter, dict): return base_q & Q(**descriptor_filter) elif descriptor_filter: return base_q & descriptor_filter return base_q @property def swappable_setting(self): """ Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False. """ if self.swappable: # Work out string form of "to" if isinstance(self.remote_field.model, str): to_string = self.remote_field.model else: to_string = self.remote_field.model._meta.label return apps.get_swappable_settings_name(to_string) return None def set_attributes_from_rel(self): self.name = self.name or ( self.remote_field.model._meta.model_name + "_" + self.remote_field.model._meta.pk.name ) if self.verbose_name is None: self.verbose_name = self.remote_field.model._meta.verbose_name self.remote_field.set_field_name() def do_related_class(self, other, cls): self.set_attributes_from_rel() self.contribute_to_related_class(other, self.remote_field) def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this model field. If it is a callable, it will be invoked and the result will be returned. """ if callable(self.remote_field.limit_choices_to): return self.remote_field.limit_choices_to() return self.remote_field.limit_choices_to def formfield(self, **kwargs): """ Pass ``limit_choices_to`` to the field being constructed. Only passes it if there is a type that supports related fields. This is a similar strategy used to pass the ``queryset`` to the field being constructed. """ defaults = {} if hasattr(self.remote_field, "get_related_field"): # If this is a callable, do not invoke it here. Just pass # it in the defaults for when the form class will later be # instantiated. limit_choices_to = self.remote_field.limit_choices_to defaults.update( { "limit_choices_to": limit_choices_to, } ) defaults.update(kwargs) return super().formfield(**defaults) def related_query_name(self): """ Define the name that can be used to identify this related object in a table-spanning query. """ return ( self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name ) @property def target_field(self): """ When filtering against this relation, return the field on the remote model against which the filtering should happen. """ target_fields = self.path_infos[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError( "The relation has multiple target fields, but only single target field " "was asked for" ) return target_fields[0] def get_cache_name(self): return self.name class ForeignObject(RelatedField): """ Abstraction of the ForeignKey relation to support multi-column relations. """ # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False requires_unique_target = True related_accessor_class = ReverseManyToOneDescriptor forward_related_accessor_class = ForwardManyToOneDescriptor rel_class = ForeignObjectRel def __init__( self, to, on_delete, from_fields, to_fields, rel=None, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, swappable=True, **kwargs, ): if rel is None: rel = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) super().__init__( rel=rel, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.from_fields = from_fields self.to_fields = to_fields self.swappable = swappable def __copy__(self): obj = super().__copy__() # Remove any cached PathInfo values. obj.__dict__.pop("path_infos", None) obj.__dict__.pop("reverse_path_infos", None) return obj def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_to_fields_exist(), *self._check_unique_target(), ] def _check_to_fields_exist(self): # Skip nonexistent models. if isinstance(self.remote_field.model, str): return [] errors = [] for to_field in self.to_fields: if to_field: try: self.remote_field.model._meta.get_field(to_field) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The to_field '%s' doesn't exist on the related " "model '%s'." % (to_field, self.remote_field.model._meta.label), obj=self, id="fields.E312", ) ) return errors def _check_unique_target(self): rel_is_string = isinstance(self.remote_field.model, str) if rel_is_string or not self.requires_unique_target: return [] try: self.foreign_related_fields except exceptions.FieldDoesNotExist: return [] if not self.foreign_related_fields: return [] unique_foreign_fields = { frozenset([f.name]) for f in self.remote_field.model._meta.get_fields() if getattr(f, "unique", False) } unique_foreign_fields.update( {frozenset(ut) for ut in self.remote_field.model._meta.unique_together} ) unique_foreign_fields.update( { frozenset(uc.fields) for uc in self.remote_field.model._meta.total_unique_constraints } ) foreign_fields = {f.name for f in self.foreign_related_fields} has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields) if not has_unique_constraint and len(self.foreign_related_fields) > 1: field_combination = ", ".join( "'%s'" % rel_field.name for rel_field in self.foreign_related_fields ) model_name = self.remote_field.model.__name__ return [ checks.Error( "No subset of the fields %s on model '%s' is unique." % (field_combination, model_name), hint=( "Mark a single field as unique=True or add a set of " "fields to a unique constraint (via unique_together " "or a UniqueConstraint (without condition) in the " "model Meta.constraints)." ), obj=self, id="fields.E310", ) ] elif not has_unique_constraint: field_name = self.foreign_related_fields[0].name model_name = self.remote_field.model.__name__ return [ checks.Error( "'%s.%s' must be unique because it is referenced by " "a foreign key." % (model_name, field_name), hint=( "Add unique=True to this field or add a " "UniqueConstraint (without condition) in the model " "Meta.constraints." ), obj=self, id="fields.E311", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs["on_delete"] = self.remote_field.on_delete kwargs["from_fields"] = self.from_fields kwargs["to_fields"] = self.to_fields if self.remote_field.parent_link: kwargs["parent_link"] = self.remote_field.parent_link if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ForeignKey pointing to a model " "that is swapped in place of more than one model (%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) # Set it kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def resolve_related_fields(self): if not self.from_fields or len(self.from_fields) != len(self.to_fields): raise ValueError( "Foreign Object from and to fields must be the same non-zero length" ) if isinstance(self.remote_field.model, str): raise ValueError( "Related model %r cannot be resolved" % self.remote_field.model ) related_fields = [] for index in range(len(self.from_fields)): from_field_name = self.from_fields[index] to_field_name = self.to_fields[index] from_field = ( self if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT else self.opts.get_field(from_field_name) ) to_field = ( self.remote_field.model._meta.pk if to_field_name is None else self.remote_field.model._meta.get_field(to_field_name) ) related_fields.append((from_field, to_field)) return related_fields @cached_property def related_fields(self): return self.resolve_related_fields() @cached_property def reverse_related_fields(self): return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields] @cached_property def local_related_fields(self): return tuple(lhs_field for lhs_field, rhs_field in self.related_fields) @cached_property def foreign_related_fields(self): return tuple( rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field ) def get_local_related_value(self, instance): return self.get_instance_value_for_fields(instance, self.local_related_fields) def get_foreign_related_value(self, instance): return self.get_instance_value_for_fields(instance, self.foreign_related_fields) @staticmethod def get_instance_value_for_fields(instance, fields): ret = [] opts = instance._meta for field in fields: # Gotcha: in some cases (like fixture loading) a model can have # different values in parent_ptr_id and parent's id. So, use # instance.pk (that is, parent_ptr_id) when asked for instance.id. if field.primary_key: possible_parent_link = opts.get_ancestor_link(field.model) if ( not possible_parent_link or possible_parent_link.primary_key or possible_parent_link.model._meta.abstract ): ret.append(instance.pk) continue ret.append(getattr(instance, field.attname)) return tuple(ret) def get_attname_column(self): attname, column = super().get_attname_column() return attname, None def get_joining_columns(self, reverse_join=False): source = self.reverse_related_fields if reverse_join else self.related_fields return tuple( (lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source ) def get_reverse_joining_columns(self): return self.get_joining_columns(reverse_join=True) def get_extra_descriptor_filter(self, instance): """ Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field. The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed together with the relation's joining columns. A parallel method is get_extra_restriction() which is used in JOIN and subquery conditions. """ return {} def get_extra_restriction(self, alias, related_alias): """ Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown. A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching. """ return None def get_path_info(self, filtered_relation=None): """Get path from this field to the related model.""" opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=self.foreign_related_fields, join_field=self, m2m=False, direct=True, filtered_relation=filtered_relation, ) ] @cached_property def path_infos(self): return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): """Get path from the related model to this field's model.""" opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(opts.pk,), join_field=self.remote_field, m2m=not self.unique, direct=False, filtered_relation=filtered_relation, ) ] @cached_property def reverse_path_infos(self): return self.get_reverse_path_info() @classmethod @functools.cache def get_class_lookups(cls): bases = inspect.getmro(cls) bases = bases[: bases.index(ForeignObject) + 1] class_lookups = [parent.__dict__.get("class_lookups", {}) for parent in bases] return cls.merge_dicts(class_lookups) def contribute_to_class(self, cls, name, private_only=False, **kwargs): super().contribute_to_class(cls, name, private_only=private_only, **kwargs) setattr(cls, self.name, self.forward_related_accessor_class(self)) def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. if ( not self.remote_field.is_hidden() and not related.related_model._meta.swapped ): setattr( cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related), ) # While 'limit_choices_to' might be a callable, simply pass # it along for later - this is too early because it's still # model load time. if self.remote_field.limit_choices_to: cls._meta.related_fkey_lookups.append( self.remote_field.limit_choices_to ) ForeignObject.register_lookup(RelatedIn) ForeignObject.register_lookup(RelatedExact) ForeignObject.register_lookup(RelatedLessThan) ForeignObject.register_lookup(RelatedGreaterThan) ForeignObject.register_lookup(RelatedGreaterThanOrEqual) ForeignObject.register_lookup(RelatedLessThanOrEqual) ForeignObject.register_lookup(RelatedIsNull) class ForeignKey(ForeignObject): """ Provide a many-to-one relation by adding a column to the local model to hold the remote value. By default ForeignKey will target the pk of the remote model but this behavior can be changed by using the ``to_field`` argument. """ descriptor_class = ForeignKeyDeferredAttribute # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False rel_class = ManyToOneRel empty_strings_allowed = False default_error_messages = { "invalid": _("%(model)s instance with %(field)s %(value)r does not exist.") } description = _("Foreign Key (type determined by related field)") def __init__( self, to, on_delete, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs, ): try: to._meta.model_name except AttributeError: if not isinstance(to, str): raise TypeError( "%s(%r) is invalid. First parameter to ForeignKey must be " "either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) else: # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) if not callable(on_delete): raise TypeError("on_delete must be callable.") kwargs["rel"] = self.rel_class( self, to, to_field, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) kwargs.setdefault("db_index", True) super().__init__( to, on_delete, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, from_fields=[RECURSIVE_RELATIONSHIP_CONSTANT], to_fields=[to_field], **kwargs, ) self.db_constraint = db_constraint def __class_getitem__(cls, *args, **kwargs): return cls def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_on_delete(), *self._check_unique(), ] def _check_on_delete(self): on_delete = getattr(self.remote_field, "on_delete", None) if on_delete == SET_NULL and not self.null: return [ checks.Error( "Field specifies on_delete=SET_NULL, but cannot be null.", hint=( "Set null=True argument on the field, or change the on_delete " "rule." ), obj=self, id="fields.E320", ) ] elif on_delete == SET_DEFAULT and not self.has_default(): return [ checks.Error( "Field specifies on_delete=SET_DEFAULT, but has no default value.", hint="Set a default value, or change the on_delete rule.", obj=self, id="fields.E321", ) ] else: return [] def _check_unique(self, **kwargs): return ( [ checks.Warning( "Setting unique=True on a ForeignKey has the same effect as using " "a OneToOneField.", hint=( "ForeignKey(unique=True) is usually better served by a " "OneToOneField." ), obj=self, id="fields.W342", ) ] if self.unique else [] ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["to_fields"] del kwargs["from_fields"] # Handle the simpler arguments if self.db_index: del kwargs["db_index"] else: kwargs["db_index"] = False if self.db_constraint is not True: kwargs["db_constraint"] = self.db_constraint # Rel needs more work. to_meta = getattr(self.remote_field.model, "_meta", None) if self.remote_field.field_name and ( not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name) ): kwargs["to_field"] = self.remote_field.field_name return name, path, args, kwargs def to_python(self, value): return self.target_field.to_python(value) @property def target_field(self): return self.foreign_related_fields[0] def validate(self, value, model_instance): if self.remote_field.parent_link: return super().validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._base_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={ "model": self.remote_field.model._meta.verbose_name, "pk": value, "field": self.remote_field.field_name, "value": value, }, # 'pk' is included for backwards compatibility ) def resolve_related_fields(self): related_fields = super().resolve_related_fields() for from_field, to_field in related_fields: if ( to_field and to_field.model != self.remote_field.model._meta.concrete_model ): raise exceptions.FieldError( "'%s.%s' refers to field '%s' which is not local to model " "'%s'." % ( self.model._meta.label, self.name, to_field.name, self.remote_field.model._meta.concrete_model._meta.label, ) ) return related_fields def get_attname(self): return "%s_id" % self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_default(self): """Return the to_field if the default value is an object.""" field_default = super().get_default() if isinstance(field_default, self.remote_field.model): return getattr(field_default, self.target_field.attname) return field_default def get_db_prep_save(self, value, connection): if value is None or ( value == "" and ( not self.target_field.empty_strings_allowed or connection.features.interprets_empty_strings_as_nulls ) ): return None else: return self.target_field.get_db_prep_save(value, connection=connection) def get_db_prep_value(self, value, connection, prepared=False): return self.target_field.get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): return self.target_field.get_prep_value(value) def contribute_to_related_class(self, cls, related): super().contribute_to_related_class(cls, related) if self.remote_field.field_name is None: self.remote_field.field_name = cls._meta.pk.name def formfield(self, *, using=None, **kwargs): if isinstance(self.remote_field.model, str): raise ValueError( "Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.remote_field.model) ) return super().formfield( **{ "form_class": forms.ModelChoiceField, "queryset": self.remote_field.model._default_manager.using(using), "to_field_name": self.remote_field.field_name, **kwargs, "blank": self.blank, } ) def db_check(self, connection): return None def db_type(self, connection): return self.target_field.rel_db_type(connection=connection) def db_parameters(self, connection): target_db_parameters = self.target_field.db_parameters(connection) return { "type": self.db_type(connection), "check": self.db_check(connection), "collation": target_db_parameters.get("collation"), } def convert_empty_strings(self, value, expression, connection): if (not value) and isinstance(value, str): return None return value def get_db_converters(self, connection): converters = super().get_db_converters(connection) if connection.features.interprets_empty_strings_as_nulls: converters += [self.convert_empty_strings] return converters def get_col(self, alias, output_field=None): if output_field is None: output_field = self.target_field while isinstance(output_field, ForeignKey): output_field = output_field.target_field if output_field is self: raise ValueError("Cannot resolve output_field.") return super().get_col(alias, output_field) class OneToOneField(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that it always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ # Field flags many_to_many = False many_to_one = False one_to_many = False one_to_one = True related_accessor_class = ReverseOneToOneDescriptor forward_related_accessor_class = ForwardOneToOneDescriptor rel_class = OneToOneRel description = _("One-to-one relationship") def __init__(self, to, on_delete, to_field=None, **kwargs): kwargs["unique"] = True super().__init__(to, on_delete, to_field=to_field, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if "unique" in kwargs: del kwargs["unique"] return name, path, args, kwargs def formfield(self, **kwargs): if self.remote_field.parent_link: return None return super().formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.remote_field.model): setattr(instance, self.name, data) else: setattr(instance, self.attname, data) # Remote field object must be cleared otherwise Model.save() # will reassign attname using the related object pk. if data is None: setattr(instance, self.name, data) def _check_unique(self, **kwargs): # Override ForeignKey since check isn't applicable here. return [] def create_many_to_many_intermediary_model(field, klass): from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = "%s_%s" % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = "to_%s" % to from_ = "from_%s" % from_ meta = type( "Meta", (), { "db_table": field._get_m2m_db_table(klass._meta), "auto_created": klass, "app_label": klass._meta.app_label, "db_tablespace": klass._meta.db_tablespace, "unique_together": (from_, to), "verbose_name": _("%(from)s-%(to)s relationship") % {"from": from_, "to": to}, "verbose_name_plural": _("%(from)s-%(to)s relationships") % {"from": from_, "to": to}, "apps": field.model._meta.apps, }, ) # Construct and return the new class. return type( name, (models.Model,), { "Meta": meta, "__module__": klass.__module__, from_: models.ForeignKey( klass, related_name="%s+" % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name="%s+" % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), }, ) class ManyToManyField(RelatedField): """ Provide a many-to-many relation by using an intermediary model that holds two ForeignKey fields pointed at the two sides of the relation. Unless a ``through`` model was provided, ManyToManyField will use the create_many_to_many_intermediary_model factory to automatically generate the intermediary model. """ # Field flags many_to_many = True many_to_one = False one_to_many = False one_to_one = False rel_class = ManyToManyRel description = _("Many-to-many relationship") def __init__( self, to, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=None, through=None, through_fields=None, db_constraint=True, db_table=None, swappable=True, **kwargs, ): try: to._meta except AttributeError: if not isinstance(to, str): raise TypeError( "%s(%r) is invalid. First parameter to ManyToManyField " "must be either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) if symmetrical is None: symmetrical = to == RECURSIVE_RELATIONSHIP_CONSTANT if through is not None and db_table is not None: raise ValueError( "Cannot specify a db_table if an intermediary model is used." ) kwargs["rel"] = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, symmetrical=symmetrical, through=through, through_fields=through_fields, db_constraint=db_constraint, ) self.has_null_arg = "null" in kwargs super().__init__( related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.db_table = db_table self.swappable = swappable def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_unique(**kwargs), *self._check_relationship_model(**kwargs), *self._check_ignored_options(**kwargs), *self._check_table_uniqueness(**kwargs), ] def _check_unique(self, **kwargs): if self.unique: return [ checks.Error( "ManyToManyFields cannot be unique.", obj=self, id="fields.E330", ) ] return [] def _check_ignored_options(self, **kwargs): warnings = [] if self.has_null_arg: warnings.append( checks.Warning( "null has no effect on ManyToManyField.", obj=self, id="fields.W340", ) ) if self._validators: warnings.append( checks.Warning( "ManyToManyField does not support validators.", obj=self, id="fields.W341", ) ) if self.remote_field.symmetrical and self._related_name: warnings.append( checks.Warning( "related_name has no effect on ManyToManyField " 'with a symmetrical relationship, e.g. to "self".', obj=self, id="fields.W345", ) ) if self.db_comment: warnings.append( checks.Warning( "db_comment has no effect on ManyToManyField.", obj=self, id="fields.W346", ) ) return warnings def _check_relationship_model(self, from_model=None, **kwargs): if hasattr(self.remote_field.through, "_meta"): qualified_model_name = "%s.%s" % ( self.remote_field.through._meta.app_label, self.remote_field.through.__name__, ) else: qualified_model_name = self.remote_field.through errors = [] if self.remote_field.through not in self.opts.apps.get_models( include_auto_created=True ): # The relationship model is not installed. errors.append( checks.Error( "Field specifies a many-to-many relation through model " "'%s', which has not been installed." % qualified_model_name, obj=self, id="fields.E331", ) ) else: assert from_model is not None, ( "ManyToManyField with intermediate " "tables cannot be checked if you don't pass the model " "where the field is attached to." ) # Set some useful local variables to_model = resolve_relation(from_model, self.remote_field.model) from_model_name = from_model._meta.object_name if isinstance(to_model, str): to_model_name = to_model else: to_model_name = to_model._meta.object_name relationship_model_name = self.remote_field.through._meta.object_name self_referential = from_model == to_model # Count foreign keys in intermediate model if self_referential: seen_self = sum( from_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) if seen_self > 2 and not self.remote_field.through_fields: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it has more than two foreign keys " "to '%s', which is ambiguous. You must specify " "which two foreign keys Django should use via the " "through_fields keyword argument." % (self, from_model_name), hint=( "Use through_fields to specify which two foreign keys " "Django should use." ), obj=self.remote_field.through, id="fields.E333", ) ) else: # Count foreign keys in relationship model seen_from = sum( from_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) seen_to = sum( to_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) if seen_from > 1 and not self.remote_field.through_fields: errors.append( checks.Error( ( "The model is used as an intermediate model by " "'%s', but it has more than one foreign key " "from '%s', which is ambiguous. You must specify " "which foreign key Django should use via the " "through_fields keyword argument." ) % (self, from_model_name), hint=( "If you want to create a recursive relationship, " 'use ManyToManyField("%s", through="%s").' ) % ( RECURSIVE_RELATIONSHIP_CONSTANT, relationship_model_name, ), obj=self, id="fields.E334", ) ) if seen_to > 1 and not self.remote_field.through_fields: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it has more than one foreign key " "to '%s', which is ambiguous. You must specify " "which foreign key Django should use via the " "through_fields keyword argument." % (self, to_model_name), hint=( "If you want to create a recursive relationship, " 'use ManyToManyField("%s", through="%s").' ) % ( RECURSIVE_RELATIONSHIP_CONSTANT, relationship_model_name, ), obj=self, id="fields.E335", ) ) if seen_from == 0 or seen_to == 0: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it does not have a foreign key to '%s' or '%s'." % (self, from_model_name, to_model_name), obj=self.remote_field.through, id="fields.E336", ) ) # Validate `through_fields`. if self.remote_field.through_fields is not None: # Validate that we're given an iterable of at least two items # and that none of them is "falsy". if not ( len(self.remote_field.through_fields) >= 2 and self.remote_field.through_fields[0] and self.remote_field.through_fields[1] ): errors.append( checks.Error( "Field specifies 'through_fields' but does not provide " "the names of the two link fields that should be used " "for the relation through model '%s'." % qualified_model_name, hint=( "Make sure you specify 'through_fields' as " "through_fields=('field1', 'field2')" ), obj=self, id="fields.E337", ) ) # Validate the given through fields -- they should be actual # fields on the through model, and also be foreign keys to the # expected models. else: assert from_model is not None, ( "ManyToManyField with intermediate " "tables cannot be checked if you don't pass the model " "where the field is attached to." ) source, through, target = ( from_model, self.remote_field.through, self.remote_field.model, ) source_field_name, target_field_name = self.remote_field.through_fields[ :2 ] for field_name, related_model in ( (source_field_name, source), (target_field_name, target), ): possible_field_names = [] for f in through._meta.fields: if ( hasattr(f, "remote_field") and getattr(f.remote_field, "model", None) == related_model ): possible_field_names.append(f.name) if possible_field_names: hint = ( "Did you mean one of the following foreign keys to '%s': " "%s?" % ( related_model._meta.object_name, ", ".join(possible_field_names), ) ) else: hint = None try: field = through._meta.get_field(field_name) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The intermediary model '%s' has no field '%s'." % (qualified_model_name, field_name), hint=hint, obj=self, id="fields.E338", ) ) else: if not ( hasattr(field, "remote_field") and getattr(field.remote_field, "model", None) == related_model ): errors.append( checks.Error( "'%s.%s' is not a foreign key to '%s'." % ( through._meta.object_name, field_name, related_model._meta.object_name, ), hint=hint, obj=self, id="fields.E339", ) ) return errors def _check_table_uniqueness(self, **kwargs): if ( isinstance(self.remote_field.through, str) or not self.remote_field.through._meta.managed ): return [] registered_tables = { model._meta.db_table: model for model in self.opts.apps.get_models(include_auto_created=True) if model != self.remote_field.through and model._meta.managed } m2m_db_table = self.m2m_db_table() model = registered_tables.get(m2m_db_table) # The second condition allows multiple m2m relations on a model if # some point to a through model that proxies another through model. if ( model and model._meta.concrete_model != self.remote_field.through._meta.concrete_model ): if model._meta.auto_created: def _get_field_name(model): for field in model._meta.auto_created._meta.many_to_many: if field.remote_field.through is model: return field.name opts = model._meta.auto_created._meta clashing_obj = "%s.%s" % (opts.label, _get_field_name(model)) else: clashing_obj = model._meta.label if settings.DATABASE_ROUTERS: error_class, error_id = checks.Warning, "fields.W344" error_hint = ( "You have configured settings.DATABASE_ROUTERS. Verify " "that the table of %r is correctly routed to a separate " "database." % clashing_obj ) else: error_class, error_id = checks.Error, "fields.E340" error_hint = None return [ error_class( "The field's intermediary table '%s' clashes with the " "table name of '%s'." % (m2m_db_table, clashing_obj), obj=self, hint=error_hint, id=error_id, ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Handle the simpler arguments. if self.db_table is not None: kwargs["db_table"] = self.db_table if self.remote_field.db_constraint is not True: kwargs["db_constraint"] = self.remote_field.db_constraint # Lowercase model names as they should be treated as case-insensitive. if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower if getattr(self.remote_field, "through", None) is not None: if isinstance(self.remote_field.through, str): kwargs["through"] = self.remote_field.through elif not self.remote_field.through._meta.auto_created: kwargs["through"] = self.remote_field.through._meta.label # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error. if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ManyToManyField pointing to a " "model that is swapped in place of more than one model " "(%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def _get_path_info(self, direct=False, filtered_relation=None): """Called by both direct and indirect m2m traversal.""" int_model = self.remote_field.through linkfield1 = int_model._meta.get_field(self.m2m_field_name()) linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name()) if direct: join1infos = linkfield1.reverse_path_infos if filtered_relation: join2infos = linkfield2.get_path_info(filtered_relation) else: join2infos = linkfield2.path_infos else: join1infos = linkfield2.reverse_path_infos if filtered_relation: join2infos = linkfield1.get_path_info(filtered_relation) else: join2infos = linkfield1.path_infos # Get join infos between the last model of join 1 and the first model # of join 2. Assume the only reason these may differ is due to model # inheritance. join1_final = join1infos[-1].to_opts join2_initial = join2infos[0].from_opts if join1_final is join2_initial: intermediate_infos = [] elif issubclass(join1_final.model, join2_initial.model): intermediate_infos = join1_final.get_path_to_parent(join2_initial.model) else: intermediate_infos = join2_initial.get_path_from_parent(join1_final.model) return [*join1infos, *intermediate_infos, *join2infos] def get_path_info(self, filtered_relation=None): return self._get_path_info(direct=True, filtered_relation=filtered_relation) @cached_property def path_infos(self): return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): return self._get_path_info(direct=False, filtered_relation=filtered_relation) @cached_property def reverse_path_infos(self): return self.get_reverse_path_info() def _get_m2m_db_table(self, opts): """ Function that can be curried to provide the m2m table name for this relation. """ if self.remote_field.through is not None: return self.remote_field.through._meta.db_table elif self.db_table: return self.db_table else: m2m_table_name = "%s_%s" % (utils.strip_quotes(opts.db_table), self.name) return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): """ Function that can be curried to provide the source accessor or DB column name for the m2m table. """ cache_attr = "_m2m_%s_cache" % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) if self.remote_field.through_fields is not None: link_field_name = self.remote_field.through_fields[0] else: link_field_name = None for f in self.remote_field.through._meta.fields: if ( f.is_relation and f.remote_field.model == related.related_model and (link_field_name is None or link_field_name == f.name) ): setattr(self, cache_attr, getattr(f, attr)) return getattr(self, cache_attr) def _get_m2m_reverse_attr(self, related, attr): """ Function that can be curried to provide the related accessor or DB column name for the m2m table. """ cache_attr = "_m2m_reverse_%s_cache" % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False if self.remote_field.through_fields is not None: link_field_name = self.remote_field.through_fields[1] else: link_field_name = None for f in self.remote_field.through._meta.fields: if f.is_relation and f.remote_field.model == related.model: if link_field_name is None and related.related_model == related.model: # If this is an m2m-intermediate to self, # the first foreign key you find will be # the source column. Keep searching for # the second foreign key. if found: setattr(self, cache_attr, getattr(f, attr)) break else: found = True elif link_field_name is None or link_field_name == f.name: setattr(self, cache_attr, getattr(f, attr)) break return getattr(self, cache_attr) def contribute_to_class(self, cls, name, **kwargs): # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.remote_field.symmetrical and ( self.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT or self.remote_field.model == cls._meta.object_name ): self.remote_field.related_name = "%s_rel_+" % name elif self.remote_field.is_hidden(): # If the backwards relation is disabled, replace the original # related_name with one generated from the m2m field name. Django # still uses backwards relations internally and we need to avoid # clashes between multiple m2m fields with related_name == '+'. self.remote_field.related_name = "_%s_%s_%s_+" % ( cls._meta.app_label, cls.__name__.lower(), name, ) super().contribute_to_class(cls, name, **kwargs) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. # 3) The class owning the m2m field has been swapped out. if not cls._meta.abstract: if self.remote_field.through: def resolve_through_model(_, model, field): field.remote_field.through = model lazy_related_operation( resolve_through_model, cls, self.remote_field.through, field=self ) elif not cls._meta.swapped: self.remote_field.through = create_many_to_many_intermediary_model( self, cls ) # Add the descriptor for the m2m relation. setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False)) # Set up the accessor for the m2m table name for the relation. self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta) def contribute_to_related_class(self, cls, related): # Internal M2Ms (i.e., those with a related name ending with '+') # and swapped models don't get a related descriptor. if ( not self.remote_field.is_hidden() and not related.related_model._meta.swapped ): setattr( cls, related.get_accessor_name(), ManyToManyDescriptor(self.remote_field, reverse=True), ) # Set up the accessors for the column names on the m2m table. self.m2m_column_name = partial(self._get_m2m_attr, related, "column") self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, "column") self.m2m_field_name = partial(self._get_m2m_attr, related, "name") self.m2m_reverse_field_name = partial( self._get_m2m_reverse_attr, related, "name" ) get_m2m_rel = partial(self._get_m2m_attr, related, "remote_field") self.m2m_target_field_name = lambda: get_m2m_rel().field_name get_m2m_reverse_rel = partial( self._get_m2m_reverse_attr, related, "remote_field" ) self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name def set_attributes_from_rel(self): pass def value_from_object(self, obj): return [] if obj.pk is None else list(getattr(obj, self.attname).all()) def save_form_data(self, instance, data): getattr(instance, self.attname).set(data) def formfield(self, *, using=None, **kwargs): defaults = { "form_class": forms.ModelMultipleChoiceField, "queryset": self.remote_field.model._default_manager.using(using), **kwargs, } # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get("initial") is not None: initial = defaults["initial"] if callable(initial): initial = initial() defaults["initial"] = [i.pk for i in initial] return super().formfield(**defaults) def db_check(self, connection): return None def db_type(self, connection): # A ManyToManyField is not represented by a single column, # so return None. return None def db_parameters(self, connection): return {"type": None, "check": None}
1cb27b34906936be709525afb73463df68f88ad5cdec2c241f434be19cbb5b87
import collections import json import re from functools import partial from itertools import chain from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value from django.db.models.functions import Cast, Random from django.db.models.lookups import Lookup from django.db.models.query_utils import select_related_descend from django.db.models.sql.constants import ( CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE, ) from django.db.models.sql.query import Query, get_order_dir from django.db.models.sql.where import AND from django.db.transaction import TransactionManagementError from django.utils.functional import cached_property from django.utils.hashable import make_hashable from django.utils.regex_helper import _lazy_re_compile class SQLCompiler: # Multiline ordering SQL clause may appear from RawSQL. ordering_parts = _lazy_re_compile( r"^(.*)\s(?:ASC|DESC).*", re.MULTILINE | re.DOTALL, ) def __init__(self, query, connection, using, elide_empty=True): self.query = query self.connection = connection self.using = using # Some queries, e.g. coalesced aggregation, need to be executed even if # they would return an empty result set. self.elide_empty = elide_empty self.quote_cache = {"*": "*"} # The select, klass_info, and annotations are needed by QuerySet.iterator() # these are set as a side-effect of executing the query. Note that we calculate # separately a list of extra select columns needed for grammatical correctness # of the query, but these columns are not included in self.select. self.select = None self.annotation_col_map = None self.klass_info = None self._meta_ordering = None def __repr__(self): return ( f"<{self.__class__.__qualname__} " f"model={self.query.model.__qualname__} " f"connection={self.connection!r} using={self.using!r}>" ) def setup_query(self, with_col_aliases=False): if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map): self.query.get_initial_alias() self.select, self.klass_info, self.annotation_col_map = self.get_select( with_col_aliases=with_col_aliases, ) self.col_count = len(self.select) def pre_sql_setup(self, with_col_aliases=False): """ Do any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ self.setup_query(with_col_aliases=with_col_aliases) order_by = self.get_order_by() self.where, self.having, self.qualify = self.query.where.split_having_qualify( must_group_by=self.query.group_by is not None ) extra_select = self.get_extra_select(order_by, self.select) self.has_extra_select = bool(extra_select) group_by = self.get_group_by(self.select + extra_select, order_by) return extra_select, order_by, group_by def get_group_by(self, select, order_by): """ Return a list of 2-tuples of form (sql, params). The logic of what exactly the GROUP BY clause contains is hard to describe in other words than "if it passes the test suite, then it is correct". """ # Some examples: # SomeModel.objects.annotate(Count('somecol')) # GROUP BY: all fields of the model # # SomeModel.objects.values('name').annotate(Count('somecol')) # GROUP BY: name # # SomeModel.objects.annotate(Count('somecol')).values('name') # GROUP BY: all cols of the model # # SomeModel.objects.values('name', 'pk') # .annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # In fact, the self.query.group_by is the minimal set to GROUP BY. It # can't be ever restricted to a smaller set, but additional columns in # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately # the end result is that it is impossible to force the query to have # a chosen GROUP BY clause - you can almost do this by using the form: # .values(*wanted_cols).annotate(AnAggregate()) # but any later annotations, extra selects, values calls that # refer some column outside of the wanted_cols, order_by, or even # filter calls can alter the GROUP BY clause. # The query.group_by is either None (no GROUP BY at all), True # (group by select fields), or a list of expressions to be added # to the group by. if self.query.group_by is None: return [] expressions = [] group_by_refs = set() if self.query.group_by is not True: # If the group by is set to a list (by .values() call most likely), # then we need to add everything in it to the GROUP BY clause. # Backwards compatibility hack for setting query.group_by. Remove # when we have public API way of forcing the GROUP BY clause. # Converts string references to expressions. for expr in self.query.group_by: if not hasattr(expr, "as_sql"): expr = self.query.resolve_ref(expr) if isinstance(expr, Ref): if expr.refs not in group_by_refs: group_by_refs.add(expr.refs) expressions.append(expr.source) else: expressions.append(expr) # Note that even if the group_by is set, it is only the minimal # set to group by. So, we need to add cols in select, order_by, and # having into the select in any case. selected_expr_indices = {} for index, (expr, _, alias) in enumerate(select, start=1): if alias: selected_expr_indices[expr] = index # Skip members of the select clause that are already explicitly # grouped against. if alias in group_by_refs: continue expressions.extend(expr.get_group_by_cols()) if not self._meta_ordering: for expr, (sql, params, is_ref) in order_by: # Skip references to the SELECT clause, as all expressions in # the SELECT clause are already part of the GROUP BY. if not is_ref: expressions.extend(expr.get_group_by_cols()) having_group_by = self.having.get_group_by_cols() if self.having else () for expr in having_group_by: expressions.append(expr) result = [] seen = set() expressions = self.collapse_group_by(expressions, having_group_by) allows_group_by_select_index = ( self.connection.features.allows_group_by_select_index ) for expr in expressions: try: sql, params = self.compile(expr) except (EmptyResultSet, FullResultSet): continue if ( allows_group_by_select_index and (select_index := selected_expr_indices.get(expr)) is not None ): sql, params = str(select_index), () else: sql, params = expr.select_format(self, sql, params) params_hash = make_hashable(params) if (sql, params_hash) not in seen: result.append((sql, params)) seen.add((sql, params_hash)) return result def collapse_group_by(self, expressions, having): # If the database supports group by functional dependence reduction, # then the expressions can be reduced to the set of selected table # primary keys as all other columns are functionally dependent on them. if self.connection.features.allows_group_by_selected_pks: # Filter out all expressions associated with a table's primary key # present in the grouped columns. This is done by identifying all # tables that have their primary key included in the grouped # columns and removing non-primary key columns referring to them. # Unmanaged models are excluded because they could be representing # database views on which the optimization might not be allowed. pks = { expr for expr in expressions if ( hasattr(expr, "target") and expr.target.primary_key and self.connection.features.allows_group_by_selected_pks_on_model( expr.target.model ) ) } aliases = {expr.alias for expr in pks} expressions = [ expr for expr in expressions if expr in pks or expr in having or getattr(expr, "alias", None) not in aliases ] return expressions def get_select(self, with_col_aliases=False): """ Return three values: - a list of 3-tuples of (expression, (sql, params), alias) - a klass_info structure, - a dictionary of annotations The (sql, params) is what the expression will produce, and alias is the "AS alias" for the column (possibly None). The klass_info structure contains the following information: - The base model of the query. - Which columns for that model are present in the query (by position of the select clause). - related_klass_infos: [f, klass_info] to descent into The annotations is a dictionary of {'attname': column position} values. """ select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items(): annotations[alias] = select_idx select.append((RawSQL(sql, params), alias)) select_idx += 1 assert not (self.query.select and self.query.default_cols) select_mask = self.query.get_select_mask() if self.query.default_cols: cols = self.get_default_columns(select_mask) else: # self.query.select is a special case. These columns never go to # any model. cols = self.query.select if cols: select_list = [] for col in cols: select_list.append(select_idx) select.append((col, None)) select_idx += 1 klass_info = { "model": self.query.model, "select_fields": select_list, } for alias, annotation in self.query.annotation_select.items(): annotations[alias] = select_idx select.append((annotation, alias)) select_idx += 1 if self.query.select_related: related_klass_infos = self.get_related_selections(select, select_mask) klass_info["related_klass_infos"] = related_klass_infos def get_select_from_parent(klass_info): for ki in klass_info["related_klass_infos"]: if ki["from_parent"]: ki["select_fields"] = ( klass_info["select_fields"] + ki["select_fields"] ) get_select_from_parent(ki) get_select_from_parent(klass_info) ret = [] col_idx = 1 for col, alias in select: try: sql, params = self.compile(col) except EmptyResultSet: empty_result_set_value = getattr( col, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: # Select a predicate that's always False. sql, params = "0", () else: sql, params = self.compile(Value(empty_result_set_value)) except FullResultSet: sql, params = self.compile(Value(True)) else: sql, params = col.select_format(self, sql, params) if alias is None and with_col_aliases: alias = f"col{col_idx}" col_idx += 1 ret.append((col, (sql, params), alias)) return ret, klass_info, annotations def _order_by_pairs(self): if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by elif self.query.order_by: ordering = self.query.order_by elif (meta := self.query.get_meta()) and meta.ordering: ordering = meta.ordering self._meta_ordering = ordering else: ordering = [] if self.query.standard_ordering: default_order, _ = ORDER_DIR["ASC"] else: default_order, _ = ORDER_DIR["DESC"] for field in ordering: if hasattr(field, "resolve_expression"): if isinstance(field, Value): # output_field must be resolved for constants. field = Cast(field, field.output_field) if not isinstance(field, OrderBy): field = field.asc() if not self.query.standard_ordering: field = field.copy() field.reverse_ordering() if isinstance(field.expression, F) and ( annotation := self.query.annotation_select.get( field.expression.name ) ): field.expression = Ref(field.expression.name, annotation) yield field, isinstance(field.expression, Ref) continue if field == "?": # random yield OrderBy(Random()), False continue col, order = get_order_dir(field, default_order) descending = order == "DESC" if col in self.query.annotation_select: # Reference to expression in SELECT clause yield ( OrderBy( Ref(col, self.query.annotation_select[col]), descending=descending, ), True, ) continue if col in self.query.annotations: # References to an expression which is masked out of the SELECT # clause. if self.query.combinator and self.select: # Don't use the resolved annotation because other # combinated queries might define it differently. expr = F(col) else: expr = self.query.annotations[col] if isinstance(expr, Value): # output_field must be resolved for constants. expr = Cast(expr, expr.output_field) yield OrderBy(expr, descending=descending), False continue if "." in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split(".", 1) yield ( OrderBy( RawSQL( "%s.%s" % (self.quote_name_unless_alias(table), col), [] ), descending=descending, ), False, ) continue if self.query.extra and col in self.query.extra: if col in self.query.extra_select: yield ( OrderBy( Ref(col, RawSQL(*self.query.extra[col])), descending=descending, ), True, ) else: yield ( OrderBy(RawSQL(*self.query.extra[col]), descending=descending), False, ) else: if self.query.combinator and self.select: # Don't use the first model's field because other # combinated queries might define it differently. yield OrderBy(F(col), descending=descending), False else: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. yield from self.find_ordering_name( field, self.query.get_meta(), default_order=default_order, ) def get_order_by(self): """ Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for the ORDER BY clause. The order_by clause can alter the select clause (for example it can add aliases to clauses that do not yet have one, or it can add totally new select clauses). """ result = [] seen = set() for expr, is_ref in self._order_by_pairs(): resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None) if not is_ref and self.query.combinator and self.select: src = resolved.expression expr_src = expr.expression for sel_expr, _, col_alias in self.select: if src == sel_expr: # When values() is used the exact alias must be used to # reference annotations. if ( self.query.has_select_fields and col_alias in self.query.annotation_select and not ( isinstance(expr_src, F) and col_alias == expr_src.name ) ): continue resolved.set_source_expressions( [Ref(col_alias if col_alias else src.target.column, src)] ) break else: # Add column used in ORDER BY clause to the selected # columns and to each combined query. order_by_idx = len(self.query.select) + 1 col_alias = f"__orderbycol{order_by_idx}" for q in self.query.combined_queries: # If fields were explicitly selected through values() # combined queries cannot be augmented. if q.has_select_fields: raise DatabaseError( "ORDER BY term does not match any column in " "the result set." ) q.add_annotation(expr_src, col_alias) self.query.add_select_col(resolved, col_alias) resolved.set_source_expressions([Ref(col_alias, src)]) sql, params = self.compile(resolved) # Don't add the same column twice, but the order direction is # not taken into account so we strip it. When this entire method # is refactored into expressions, then we can check each part as we # generate it. without_ordering = self.ordering_parts.search(sql)[1] params_hash = make_hashable(params) if (without_ordering, params_hash) in seen: continue seen.add((without_ordering, params_hash)) result.append((resolved, (sql, params, is_ref))) return result def get_extra_select(self, order_by, select): extra_select = [] if self.query.distinct and not self.query.distinct_fields: select_sql = [t[1] for t in select] for expr, (sql, params, is_ref) in order_by: without_ordering = self.ordering_parts.search(sql)[1] if not is_ref and (without_ordering, params) not in select_sql: extra_select.append((expr, (without_ordering, params), None)) return extra_select def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ( (name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select or ( self.query.external_aliases.get(name) and name not in self.query.table_map ) ): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def compile(self, node): vendor_impl = getattr(node, "as_" + self.connection.vendor, None) if vendor_impl: sql, params = vendor_impl(self, self.connection) else: sql, params = node.as_sql(self, self.connection) return sql, params def get_combinator_sql(self, combinator, all): features = self.connection.features compilers = [ query.get_compiler(self.using, self.connection, self.elide_empty) for query in self.query.combined_queries ] if not features.supports_slicing_ordering_in_compound: for compiler in compilers: if compiler.query.is_sliced: raise DatabaseError( "LIMIT/OFFSET not allowed in subqueries of compound statements." ) if compiler.get_order_by(): raise DatabaseError( "ORDER BY not allowed in subqueries of compound statements." ) elif self.query.is_sliced and combinator == "union": limit = (self.query.low_mark, self.query.high_mark) for compiler in compilers: # A sliced union cannot have its parts elided as some of them # might be sliced as well and in the event where only a single # part produces a non-empty resultset it might be impossible to # generate valid SQL. compiler.elide_empty = False if not compiler.query.is_sliced: compiler.query.set_limits(*limit) parts = () for compiler in compilers: try: # If the columns list is limited, then all combined queries # must have the same columns list. Set the selects defined on # the query on all combined queries, if not already set. if not compiler.query.values_select and self.query.values_select: compiler.query = compiler.query.clone() compiler.query.set_values( ( *self.query.extra_select, *self.query.values_select, *self.query.annotation_select, ) ) part_sql, part_args = compiler.as_sql(with_col_aliases=True) if compiler.query.combinator: # Wrap in a subquery if wrapping in parentheses isn't # supported. if not features.supports_parentheses_in_compound: part_sql = "SELECT * FROM ({})".format(part_sql) # Add parentheses when combining with compound query if not # already added for all compound queries. elif ( self.query.subquery or not features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) elif ( self.query.subquery and features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) parts += ((part_sql, part_args),) except EmptyResultSet: # Omit the empty queryset with UNION and with DIFFERENCE if the # first queryset is nonempty. if combinator == "union" or (combinator == "difference" and parts): continue raise if not parts: raise EmptyResultSet combinator_sql = self.connection.ops.set_operators[combinator] if all and combinator == "union": combinator_sql += " ALL" braces = "{}" if not self.query.subquery and features.supports_slicing_ordering_in_compound: braces = "({})" sql_parts, args_parts = zip( *((braces.format(sql), args) for sql, args in parts) ) result = [" {} ".format(combinator_sql).join(sql_parts)] params = [] for part in args_parts: params.extend(part) return result, params def get_qualify_sql(self): where_parts = [] if self.where: where_parts.append(self.where) if self.having: where_parts.append(self.having) inner_query = self.query.clone() inner_query.subquery = True inner_query.where = inner_query.where.__class__(where_parts) # Augment the inner query with any window function references that # might have been masked via values() and alias(). If any masked # aliases are added they'll be masked again to avoid fetching # the data in the `if qual_aliases` branch below. select = { expr: alias for expr, _, alias in self.get_select(with_col_aliases=True)[0] } select_aliases = set(select.values()) qual_aliases = set() replacements = {} def collect_replacements(expressions): while expressions: expr = expressions.pop() if expr in replacements: continue elif select_alias := select.get(expr): replacements[expr] = select_alias elif isinstance(expr, Lookup): expressions.extend(expr.get_source_expressions()) elif isinstance(expr, Ref): if expr.refs not in select_aliases: expressions.extend(expr.get_source_expressions()) else: num_qual_alias = len(qual_aliases) select_alias = f"qual{num_qual_alias}" qual_aliases.add(select_alias) inner_query.add_annotation(expr, select_alias) replacements[expr] = select_alias collect_replacements(list(self.qualify.leaves())) self.qualify = self.qualify.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) order_by = [] for order_by_expr, *_ in self.get_order_by(): collect_replacements(order_by_expr.get_source_expressions()) order_by.append( order_by_expr.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) ) inner_query_compiler = inner_query.get_compiler( self.using, elide_empty=self.elide_empty ) inner_sql, inner_params = inner_query_compiler.as_sql( # The limits must be applied to the outer query to avoid pruning # results too eagerly. with_limits=False, # Force unique aliasing of selected columns to avoid collisions # and make rhs predicates referencing easier. with_col_aliases=True, ) qualify_sql, qualify_params = self.compile(self.qualify) result = [ "SELECT * FROM (", inner_sql, ")", self.connection.ops.quote_name("qualify"), "WHERE", qualify_sql, ] if qual_aliases: # If some select aliases were unmasked for filtering purposes they # must be masked back. cols = [self.connection.ops.quote_name(alias) for alias in select.values()] result = [ "SELECT", ", ".join(cols), "FROM (", *result, ")", self.connection.ops.quote_name("qualify_mask"), ] params = list(inner_params) + qualify_params # As the SQL spec is unclear on whether or not derived tables # ordering must propagate it has to be explicitly repeated on the # outer-most query to ensure it's preserved. if order_by: ordering_sqls = [] for ordering in order_by: ordering_sql, ordering_params = self.compile(ordering) ordering_sqls.append(ordering_sql) params.extend(ordering_params) result.extend(["ORDER BY", ", ".join(ordering_sqls)]) return result, params def as_sql(self, with_limits=True, with_col_aliases=False): """ Create the SQL for this query. Return the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ refcounts_before = self.query.alias_refcount.copy() try: combinator = self.query.combinator extra_select, order_by, group_by = self.pre_sql_setup( with_col_aliases=with_col_aliases or bool(combinator), ) for_update_part = None # Is a LIMIT/OFFSET clause needed? with_limit_offset = with_limits and self.query.is_sliced combinator = self.query.combinator features = self.connection.features if combinator: if not getattr(features, "supports_select_{}".format(combinator)): raise NotSupportedError( "{} is not supported on this database backend.".format( combinator ) ) result, params = self.get_combinator_sql( combinator, self.query.combinator_all ) elif self.qualify: result, params = self.get_qualify_sql() order_by = None else: distinct_fields, distinct_params = self.get_distinct() # This must come after 'select', 'ordering', and 'distinct' # (see docstring of get_from_clause() for details). from_, f_params = self.get_from_clause() try: where, w_params = ( self.compile(self.where) if self.where is not None else ("", []) ) except EmptyResultSet: if self.elide_empty: raise # Use a predicate that's always False. where, w_params = "0 = 1", [] except FullResultSet: where, w_params = "", [] try: having, h_params = ( self.compile(self.having) if self.having is not None else ("", []) ) except FullResultSet: having, h_params = "", [] result = ["SELECT"] params = [] if self.query.distinct: distinct_result, distinct_params = self.connection.ops.distinct_sql( distinct_fields, distinct_params, ) result += distinct_result params += distinct_params out_cols = [] for _, (s_sql, s_params), alias in self.select + extra_select: if alias: s_sql = "%s AS %s" % ( s_sql, self.connection.ops.quote_name(alias), ) params.extend(s_params) out_cols.append(s_sql) result += [", ".join(out_cols)] if from_: result += ["FROM", *from_] elif self.connection.features.bare_select_suffix: result += [self.connection.features.bare_select_suffix] params.extend(f_params) if self.query.select_for_update and features.has_select_for_update: if ( self.connection.get_autocommit() # Don't raise an exception when database doesn't # support transactions, as it's a noop. and features.supports_transactions ): raise TransactionManagementError( "select_for_update cannot be used outside of a transaction." ) if ( with_limit_offset and not features.supports_select_for_update_with_limit ): raise NotSupportedError( "LIMIT/OFFSET is not supported with " "select_for_update on this database backend." ) nowait = self.query.select_for_update_nowait skip_locked = self.query.select_for_update_skip_locked of = self.query.select_for_update_of no_key = self.query.select_for_no_key_update # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the # backend doesn't support it, raise NotSupportedError to # prevent a possible deadlock. if nowait and not features.has_select_for_update_nowait: raise NotSupportedError( "NOWAIT is not supported on this database backend." ) elif skip_locked and not features.has_select_for_update_skip_locked: raise NotSupportedError( "SKIP LOCKED is not supported on this database backend." ) elif of and not features.has_select_for_update_of: raise NotSupportedError( "FOR UPDATE OF is not supported on this database backend." ) elif no_key and not features.has_select_for_no_key_update: raise NotSupportedError( "FOR NO KEY UPDATE is not supported on this " "database backend." ) for_update_part = self.connection.ops.for_update_sql( nowait=nowait, skip_locked=skip_locked, of=self.get_select_for_update_of_arguments(), no_key=no_key, ) if for_update_part and features.for_update_after_from: result.append(for_update_part) if where: result.append("WHERE %s" % where) params.extend(w_params) grouping = [] for g_sql, g_params in group_by: grouping.append(g_sql) params.extend(g_params) if grouping: if distinct_fields: raise NotImplementedError( "annotate() + distinct(fields) is not implemented." ) order_by = order_by or self.connection.ops.force_no_ordering() result.append("GROUP BY %s" % ", ".join(grouping)) if self._meta_ordering: order_by = None if having: result.append("HAVING %s" % having) params.extend(h_params) if self.query.explain_info: result.insert( 0, self.connection.ops.explain_query_prefix( self.query.explain_info.format, **self.query.explain_info.options, ), ) if order_by: ordering = [] for _, (o_sql, o_params, _) in order_by: ordering.append(o_sql) params.extend(o_params) order_by_sql = "ORDER BY %s" % ", ".join(ordering) if combinator and features.requires_compound_order_by_subquery: result = ["SELECT * FROM (", *result, ")", order_by_sql] else: result.append(order_by_sql) if with_limit_offset: result.append( self.connection.ops.limit_offset_sql( self.query.low_mark, self.query.high_mark ) ) if for_update_part and not features.for_update_after_from: result.append(for_update_part) if self.query.subquery and extra_select: # If the query is used as a subquery, the extra selects would # result in more columns than the left-hand side expression is # expecting. This can happen when a subquery uses a combination # of order_by() and distinct(), forcing the ordering expressions # to be selected as well. Wrap the query in another subquery # to exclude extraneous selects. sub_selects = [] sub_params = [] for index, (select, _, alias) in enumerate(self.select, start=1): if alias: sub_selects.append( "%s.%s" % ( self.connection.ops.quote_name("subquery"), self.connection.ops.quote_name(alias), ) ) else: select_clone = select.relabeled_clone( {select.alias: "subquery"} ) subselect, subparams = select_clone.as_sql( self, self.connection ) sub_selects.append(subselect) sub_params.extend(subparams) return "SELECT %s FROM (%s) subquery" % ( ", ".join(sub_selects), " ".join(result), ), tuple(sub_params + params) return " ".join(result), tuple(params) finally: # Finally do cleanup - get rid of the joins we created above. self.query.reset_refcounts(refcounts_before) def get_default_columns( self, select_mask, start_alias=None, opts=None, from_parent=None ): """ Compute the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Return a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, return a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: if (opts := self.query.get_meta()) is None: return result start_alias = start_alias or self.query.get_initial_alias() # The 'seen_models' is used to optimize checking the needed parent # alias for a given field. This also includes None -> start_alias to # be used by local fields. seen_models = {None: start_alias} for field in opts.concrete_fields: model = field.model._meta.concrete_model # A proxy model will have a different model and concrete_model. We # will assign None if the field belongs to this model. if model == opts.model: model = None if ( from_parent and model is not None and issubclass( from_parent._meta.concrete_model, model._meta.concrete_model ) ): # Avoid loading data for already loaded parents. # We end up here in the case select_related() resolution # proceeds from parent model to child model. In that case the # parent model data is already present in the SELECT clause, # and we want to avoid reloading the same data again. continue if select_mask and field not in select_mask: continue alias = self.query.join_parent_model(opts, model, start_alias, seen_models) column = field.get_col(alias) result.append(column) return result def get_distinct(self): """ Return a quoted list of fields to use in DISTINCT ON part of the query. This method can alter the tables in the query, and thus it must be called before get_from_clause(). """ result = [] params = [] opts = self.query.get_meta() for name in self.query.distinct_fields: parts = name.split(LOOKUP_SEP) _, targets, alias, joins, path, _, transform_function = self._setup_joins( parts, opts, None ) targets, alias, _ = self.query.trim_joins(targets, joins, path) for target in targets: if name in self.query.annotation_select: result.append(self.connection.ops.quote_name(name)) else: r, p = self.compile(transform_function(target, alias)) result.append(r) params.append(p) return result, params def find_ordering_name( self, name, opts, alias=None, default_order="ASC", already_seen=None ): """ Return the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) descending = order == "DESC" pieces = name.split(LOOKUP_SEP) ( field, targets, alias, joins, path, opts, transform_function, ) = self._setup_joins(pieces, opts, alias) # If we get to this point and the field is a relation to another model, # append the default ordering for that model unless it is the pk # shortcut or the attribute name of the field that is specified or # there are transforms to process. if ( field.is_relation and opts.ordering and getattr(field, "attname", None) != pieces[-1] and name != "pk" and not getattr(transform_function, "has_transforms", False) ): # Firstly, avoid infinite loops. already_seen = already_seen or set() join_tuple = tuple( getattr(self.query.alias_map[j], "join_cols", None) for j in joins ) if join_tuple in already_seen: raise FieldError("Infinite loop caused by ordering.") already_seen.add(join_tuple) results = [] for item in opts.ordering: if hasattr(item, "resolve_expression") and not isinstance( item, OrderBy ): item = item.desc() if descending else item.asc() if isinstance(item, OrderBy): results.append( (item.prefix_references(f"{name}{LOOKUP_SEP}"), False) ) continue results.extend( (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref) for expr, is_ref in self.find_ordering_name( item, opts, alias, order, already_seen ) ) return results targets, alias, _ = self.query.trim_joins(targets, joins, path) return [ (OrderBy(transform_function(t, alias), descending=descending), False) for t in targets ] def _setup_joins(self, pieces, opts, alias): """ Helper method for get_order_by() and get_distinct(). get_ordering() and get_distinct() must produce same target columns on same input, as the prefixes of get_ordering() and get_distinct() must match. Executing SQL where this is not true is an error. """ alias = alias or self.query.get_initial_alias() field, targets, opts, joins, path, transform_function = self.query.setup_joins( pieces, opts, alias ) alias = joins[-1] return field, targets, alias, joins, path, opts, transform_function def get_from_clause(self): """ Return a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Subclasses, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables that are needed. This means the select columns, ordering, and distinct must be done first. """ result = [] params = [] for alias in tuple(self.query.alias_map): if not self.query.alias_refcount[alias]: continue try: from_clause = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue clause_sql, clause_params = self.compile(from_clause) result.append(clause_sql) params.extend(clause_params) for t in self.query.extra_tables: alias, _ = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # call increments the refcount, so an alias refcount of one means # this is the only reference). if ( alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1 ): result.append(", %s" % self.quote_name_unless_alias(alias)) return result, params def get_related_selections( self, select, select_mask, opts=None, root_alias=None, cur_depth=1, requested=None, restricted=None, ): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ def _get_field_choices(): direct_choices = (f.name for f in opts.fields if f.is_relation) reverse_choices = ( f.field.related_query_name() for f in opts.related_objects if f.field.unique ) return chain( direct_choices, reverse_choices, self.query._filtered_relations ) related_klass_infos = [] if not restricted and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return related_klass_infos if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() # Setup for the case when only particular related fields should be # included in the related selection. fields_found = set() if requested is None: restricted = isinstance(self.query.select_related, dict) if restricted: requested = self.query.select_related def get_related_klass_infos(klass_info, related_klass_infos): klass_info["related_klass_infos"] = related_klass_infos for f in opts.fields: fields_found.add(f.name) if restricted: next = requested.get(f.name, {}) if not f.is_relation: # If a non-related field is used like a relation, # or if a single non-relational field is given. if next or f.name in requested: raise FieldError( "Non-relational field given in select_related: '%s'. " "Choices are: %s" % ( f.name, ", ".join(_get_field_choices()) or "(none)", ) ) else: next = False if not select_related_descend(f, restricted, requested, select_mask): continue related_select_mask = select_mask.get(f) or {} klass_info = { "model": f.remote_field.model, "field": f, "reverse": False, "local_setter": f.set_cached_value, "remote_setter": f.remote_field.set_cached_value if f.unique else lambda x, y: None, "from_parent": False, } related_klass_infos.append(klass_info) select_fields = [] _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias) alias = joins[-1] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=f.remote_field.model._meta ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_klass_infos = self.get_related_selections( select, related_select_mask, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) if restricted: related_fields = [ (o.field, o.related_model) for o in opts.related_objects if o.field.unique and not o.many_to_many ] for related_field, model in related_fields: related_select_mask = select_mask.get(related_field) or {} if not select_related_descend( related_field, restricted, requested, related_select_mask, reverse=True, ): continue related_field_name = related_field.related_query_name() fields_found.add(related_field_name) join_info = self.query.setup_joins( [related_field_name], opts, root_alias ) alias = join_info.joins[-1] from_parent = issubclass(model, opts.model) and model is not opts.model klass_info = { "model": model, "field": related_field, "reverse": True, "local_setter": related_field.remote_field.set_cached_value, "remote_setter": related_field.set_cached_value, "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next = requested.get(related_field.related_query_name(), {}) next_klass_infos = self.get_related_selections( select, related_select_mask, model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) def local_setter(final_field, obj, from_obj): # Set a reverse fk object when relation is non-empty. if from_obj: final_field.remote_field.set_cached_value(from_obj, obj) def remote_setter(name, obj, from_obj): setattr(from_obj, name, obj) for name in list(requested): # Filtered relations work only on the topmost level. if cur_depth > 1: break if name in self.query._filtered_relations: fields_found.add(name) final_field, _, join_opts, joins, _, _ = self.query.setup_joins( [name], opts, root_alias ) model = join_opts.model alias = joins[-1] from_parent = ( issubclass(model, opts.model) and model is not opts.model ) klass_info = { "model": model, "field": final_field, "reverse": True, "local_setter": partial(local_setter, final_field), "remote_setter": partial(remote_setter, name), "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] field_select_mask = select_mask.get((name, final_field)) or {} columns = self.get_default_columns( field_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_requested = requested.get(name, {}) next_klass_infos = self.get_related_selections( select, field_select_mask, opts=model._meta, root_alias=alias, cur_depth=cur_depth + 1, requested=next_requested, restricted=restricted, ) get_related_klass_infos(klass_info, next_klass_infos) fields_not_found = set(requested).difference(fields_found) if fields_not_found: invalid_fields = ("'%s'" % s for s in fields_not_found) raise FieldError( "Invalid field name(s) given in select_related: %s. " "Choices are: %s" % ( ", ".join(invalid_fields), ", ".join(_get_field_choices()) or "(none)", ) ) return related_klass_infos def get_select_for_update_of_arguments(self): """ Return a quoted list of arguments for the SELECT FOR UPDATE OF part of the query. """ def _get_parent_klass_info(klass_info): concrete_model = klass_info["model"]._meta.concrete_model for parent_model, parent_link in concrete_model._meta.parents.items(): parent_list = parent_model._meta.get_parent_list() yield { "model": parent_model, "field": parent_link, "reverse": False, "select_fields": [ select_index for select_index in klass_info["select_fields"] # Selected columns from a model or its parents. if ( self.select[select_index][0].target.model == parent_model or self.select[select_index][0].target.model in parent_list ) ], } def _get_first_selected_col_from_model(klass_info): """ Find the first selected column from a model. If it doesn't exist, don't lock a model. select_fields is filled recursively, so it also contains fields from the parent models. """ concrete_model = klass_info["model"]._meta.concrete_model for select_index in klass_info["select_fields"]: if self.select[select_index][0].target.model == concrete_model: return self.select[select_index][0] def _get_field_choices(): """Yield all allowed field paths in breadth-first search order.""" queue = collections.deque([(None, self.klass_info)]) while queue: parent_path, klass_info = queue.popleft() if parent_path is None: path = [] yield "self" else: field = klass_info["field"] if klass_info["reverse"]: field = field.remote_field path = parent_path + [field.name] yield LOOKUP_SEP.join(path) queue.extend( (path, klass_info) for klass_info in _get_parent_klass_info(klass_info) ) queue.extend( (path, klass_info) for klass_info in klass_info.get("related_klass_infos", []) ) if not self.klass_info: return [] result = [] invalid_names = [] for name in self.query.select_for_update_of: klass_info = self.klass_info if name == "self": col = _get_first_selected_col_from_model(klass_info) else: for part in name.split(LOOKUP_SEP): klass_infos = ( *klass_info.get("related_klass_infos", []), *_get_parent_klass_info(klass_info), ) for related_klass_info in klass_infos: field = related_klass_info["field"] if related_klass_info["reverse"]: field = field.remote_field if field.name == part: klass_info = related_klass_info break else: klass_info = None break if klass_info is None: invalid_names.append(name) continue col = _get_first_selected_col_from_model(klass_info) if col is not None: if self.connection.features.select_for_update_of_column: result.append(self.compile(col)[0]) else: result.append(self.quote_name_unless_alias(col.alias)) if invalid_names: raise FieldError( "Invalid field name(s) given in select_for_update(of=(...)): %s. " "Only relational fields followed in the query are allowed. " "Choices are: %s." % ( ", ".join(invalid_names), ", ".join(_get_field_choices()), ) ) return result def get_converters(self, expressions): converters = {} for i, expression in enumerate(expressions): if expression: backend_converters = self.connection.ops.get_db_converters(expression) field_converters = expression.get_db_converters(self.connection) if backend_converters or field_converters: converters[i] = (backend_converters + field_converters, expression) return converters def apply_converters(self, rows, converters): connection = self.connection converters = list(converters.items()) for row in map(list, rows): for pos, (convs, expression) in converters: value = row[pos] for converter in convs: value = converter(value, expression, connection) row[pos] = value yield row def results_iter( self, results=None, tuple_expected=False, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE, ): """Return an iterator over the results from executing this query.""" if results is None: results = self.execute_sql( MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size ) fields = [s[0] for s in self.select[0 : self.col_count]] converters = self.get_converters(fields) rows = chain.from_iterable(results) if converters: rows = self.apply_converters(rows, converters) if tuple_expected: rows = map(tuple, rows) return rows def has_results(self): """ Backends (e.g. NoSQL) can override this in order to use optimized versions of "query has any results." """ return bool(self.execute_sql(SINGLE)) def execute_sql( self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): """ Run the query against the database and return the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ result_type = result_type or NO_RESULTS try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return iter([]) else: return if chunked_fetch: cursor = self.connection.chunked_cursor() else: cursor = self.connection.cursor() try: cursor.execute(sql, params) except Exception: # Might fail for server-side cursors (e.g. connection closed) cursor.close() raise if result_type == CURSOR: # Give the caller the cursor to process and close. return cursor if result_type == SINGLE: try: val = cursor.fetchone() if val: return val[0 : self.col_count] return val finally: # done with the cursor cursor.close() if result_type == NO_RESULTS: cursor.close() return result = cursor_iter( cursor, self.connection.features.empty_fetchmany_value, self.col_count if self.has_extra_select else None, chunk_size, ) if not chunked_fetch or not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. Use chunked_fetch if requested, # unless the database doesn't support it. return list(result) return result def as_subquery_condition(self, alias, columns, compiler): qn = compiler.quote_name_unless_alias qn2 = self.connection.ops.quote_name for index, select_col in enumerate(self.query.select): lhs_sql, lhs_params = self.compile(select_col) rhs = "%s.%s" % (qn(alias), qn2(columns[index])) self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND) sql, params = self.as_sql() return "EXISTS (%s)" % sql, params def explain_query(self): result = list(self.execute_sql()) # Some backends return 1 item tuples with strings, and others return # tuples with integers and strings. Flatten them out into strings. format_ = self.query.explain_info.format output_formatter = json.dumps if format_ and format_.lower() == "json" else str for row in result[0]: if not isinstance(row, str): yield " ".join(output_formatter(c) for c in row) else: yield row class SQLInsertCompiler(SQLCompiler): returning_fields = None returning_params = () def field_as_sql(self, field, val): """ Take a field and a value intended to be saved on that field, and return placeholder SQL and accompanying params. Check for raw values, expressions, and fields with get_placeholder() defined in that order. When field is None, consider the value raw and use it as the placeholder, with no corresponding parameters returned. """ if field is None: # A field value of None means the value is raw. sql, params = val, [] elif hasattr(val, "as_sql"): # This is an expression, let's compile it. sql, params = self.compile(val) elif hasattr(field, "get_placeholder"): # Some fields (e.g. geo fields) need special munging before # they can be inserted. sql, params = field.get_placeholder(val, self, self.connection), [val] else: # Return the common case for the placeholder sql, params = "%s", [val] # The following hook is only used by Oracle Spatial, which sometimes # needs to yield 'NULL' and [] as its placeholder and params instead # of '%s' and [None]. The 'NULL' placeholder is produced earlier by # OracleOperations.get_geom_placeholder(). The following line removes # the corresponding None parameter. See ticket #10888. params = self.connection.ops.modify_insert_params(sql, params) return sql, params def prepare_value(self, field, value): """ Prepare a value to be used in a query by resolving it if it is an expression and otherwise calling the field's get_db_prep_save(). """ if hasattr(value, "resolve_expression"): value = value.resolve_expression( self.query, allow_joins=False, for_save=True ) # Don't allow values containing Col expressions. They refer to # existing columns on a row, but in the case of insert the row # doesn't exist yet. if value.contains_column_references: raise ValueError( 'Failed to insert expression "%s" on %s. F() expressions ' "can only be used to update, not to insert." % (value, field) ) if value.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, value) ) if value.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query (%s=%r)." % (field.name, value) ) return field.get_db_prep_save(value, connection=self.connection) def pre_save_val(self, field, obj): """ Get the given field's value off the given obj. pre_save() is used for things like auto_now on DateTimeField. Skip it if this is a raw query. """ if self.query.raw: return getattr(obj, field.attname) return field.pre_save(obj, add=True) def assemble_as_sql(self, fields, value_rows): """ Take a sequence of N fields and a sequence of M rows of values, and generate placeholder SQL and parameters for each field and value. Return a pair containing: * a sequence of M rows of N SQL placeholder strings, and * a sequence of M rows of corresponding parameter values. Each placeholder string may contain any number of '%s' interpolation strings, and each parameter row will contain exactly as many params as the total number of '%s's in the corresponding placeholder row. """ if not value_rows: return [], [] # list of (sql, [params]) tuples for each object to be saved # Shape: [n_objs][n_fields][2] rows_of_fields_as_sql = ( (self.field_as_sql(field, v) for field, v in zip(fields, row)) for row in value_rows ) # tuple like ([sqls], [[params]s]) for each object to be saved # Shape: [n_objs][2][n_fields] sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql) # Extract separate lists for placeholders and params. # Each of these has shape [n_objs][n_fields] placeholder_rows, param_rows = zip(*sql_and_param_pair_rows) # Params for each field are still lists, and need to be flattened. param_rows = [[p for ps in row for p in ps] for row in param_rows] return placeholder_rows, param_rows def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.get_meta() insert_statement = self.connection.ops.insert_statement( on_conflict=self.query.on_conflict, ) result = ["%s %s" % (insert_statement, qn(opts.db_table))] fields = self.query.fields or [opts.pk] result.append("(%s)" % ", ".join(qn(f.column) for f in fields)) if self.query.fields: value_rows = [ [ self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields ] for obj in self.query.objs ] else: # An empty object. value_rows = [ [self.connection.ops.pk_default_value()] for _ in self.query.objs ] fields = [None] # Currently the backends just accept values when generating bulk # queries and generate their own placeholders. Doing that isn't # necessary and it should be possible to use placeholders and # expressions in bulk inserts too. can_bulk = ( not self.returning_fields and self.connection.features.has_bulk_insert ) placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows) on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql( fields, self.query.on_conflict, (f.column for f in self.query.update_fields), (f.column for f in self.query.unique_fields), ) if ( self.returning_fields and self.connection.features.can_return_columns_from_insert ): if self.connection.features.can_return_rows_from_bulk_insert: result.append( self.connection.ops.bulk_insert_sql(fields, placeholder_rows) ) params = param_rows else: result.append("VALUES (%s)" % ", ".join(placeholder_rows[0])) params = [param_rows[0]] if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) # Skip empty r_sql to allow subclasses to customize behavior for # 3rd party backends. Refs #19096. r_sql, self.returning_params = self.connection.ops.return_insert_columns( self.returning_fields ) if r_sql: result.append(r_sql) params += [self.returning_params] return [(" ".join(result), tuple(chain.from_iterable(params)))] if can_bulk: result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows)) if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [(" ".join(result), tuple(p for ps in param_rows for p in ps))] else: if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [ (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals) for p, vals in zip(placeholder_rows, param_rows) ] def execute_sql(self, returning_fields=None): assert not ( returning_fields and len(self.query.objs) != 1 and not self.connection.features.can_return_rows_from_bulk_insert ) opts = self.query.get_meta() self.returning_fields = returning_fields with self.connection.cursor() as cursor: for sql, params in self.as_sql(): cursor.execute(sql, params) if not self.returning_fields: return [] if ( self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1 ): rows = self.connection.ops.fetch_returned_insert_rows(cursor) elif self.connection.features.can_return_columns_from_insert: assert len(self.query.objs) == 1 rows = [ self.connection.ops.fetch_returned_insert_columns( cursor, self.returning_params, ) ] else: rows = [ ( self.connection.ops.last_insert_id( cursor, opts.db_table, opts.pk.column, ), ) ] cols = [field.get_col(opts.db_table) for field in self.returning_fields] converters = self.get_converters(cols) if converters: rows = list(self.apply_converters(rows, converters)) return rows class SQLDeleteCompiler(SQLCompiler): @cached_property def single_alias(self): # Ensure base table is in aliases. self.query.get_initial_alias() return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1 @classmethod def _expr_refs_base_model(cls, expr, base_model): if isinstance(expr, Query): return expr.model == base_model if not hasattr(expr, "get_source_expressions"): return False return any( cls._expr_refs_base_model(source_expr, base_model) for source_expr in expr.get_source_expressions() ) @cached_property def contains_self_reference_subquery(self): return any( self._expr_refs_base_model(expr, self.query.model) for expr in chain( self.query.annotations.values(), self.query.where.children ) ) def _as_sql(self, query): delete = "DELETE FROM %s" % self.quote_name_unless_alias(query.base_table) try: where, params = self.compile(query.where) except FullResultSet: return delete, () return f"{delete} WHERE {where}", tuple(params) def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ if self.single_alias and not self.contains_self_reference_subquery: return self._as_sql(self.query) innerq = self.query.clone() innerq.__class__ = Query innerq.clear_select_clause() pk = self.query.model._meta.pk innerq.select = [pk.get_col(self.query.get_initial_alias())] outerq = Query(self.query.model) if not self.connection.features.update_can_self_select: # Force the materialization of the inner query to allow reference # to the target table on MySQL. sql, params = innerq.get_compiler(connection=self.connection).as_sql() innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params) outerq.add_filter("pk__in", innerq) return self._as_sql(outerq) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ self.pre_sql_setup() if not self.query.values: return "", () qn = self.quote_name_unless_alias values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, "resolve_expression"): val = val.resolve_expression( self.query, allow_joins=False, for_save=True ) if val.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, val) ) if val.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query " "(%s=%r)." % (field.name, val) ) elif hasattr(val, "prepare_database_save"): if field.remote_field: val = val.prepare_database_save(field) else: raise TypeError( "Tried to update field %s with a model instance, %r. " "Use a value compatible with %s." % (field, val, field.__class__.__name__) ) val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, "get_placeholder"): placeholder = field.get_placeholder(val, self, self.connection) else: placeholder = "%s" name = field.column if hasattr(val, "as_sql"): sql, params = self.compile(val) values.append("%s = %s" % (qn(name), placeholder % sql)) update_params.extend(params) elif val is not None: values.append("%s = %s" % (qn(name), placeholder)) update_params.append(val) else: values.append("%s = NULL" % qn(name)) table = self.query.base_table result = [ "UPDATE %s SET" % qn(table), ", ".join(values), ] try: where, params = self.compile(self.query.where) except FullResultSet: params = [] else: result.append("WHERE %s" % where) return " ".join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, munge the "where" conditions to match the format required for (portable) SQL updates. If multiple updates are required, pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ refcounts_before = self.query.alias_refcount.copy() # Ensure base table is in the query self.query.get_initial_alias() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return query = self.query.chain(klass=Query) query.select_related = False query.clear_ordering(force=True) query.extra = {} query.select = [] meta = query.get_meta() fields = [meta.pk.name] related_ids_index = [] for related in self.query.related_updates: if all( path.join_field.primary_key for path in meta.get_path_to_parent(related) ): # If a primary key chain exists to the targeted related update, # then the meta.pk value can be used for it. related_ids_index.append((related, 0)) else: # This branch will only be reached when updating a field of an # ancestor that is not part of the primary key chain of a MTI # tree. related_ids_index.append((related, len(fields))) fields.append(related._meta.pk.name) query.add_fields(fields) super().pre_sql_setup() must_pre_select = ( count > 1 and not self.connection.features.update_can_self_select ) # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.clear_where() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] related_ids = collections.defaultdict(list) for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend(r[0] for r in rows) for parent, index in related_ids_index: related_ids[parent].extend(r[index] for r in rows) self.query.add_filter("pk__in", idents) self.query.related_ids = related_ids else: # The fast path. Filters and updates in one query. self.query.add_filter("pk__in", query) self.query.reset_refcounts(refcounts_before) class SQLAggregateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ sql, params = [], [] for annotation in self.query.annotation_select.values(): ann_sql, ann_params = self.compile(annotation) ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params) sql.append(ann_sql) params.extend(ann_params) self.col_count = len(self.query.annotation_select) sql = ", ".join(sql) params = tuple(params) inner_query_sql, inner_query_params = self.query.inner_query.get_compiler( self.using, elide_empty=self.elide_empty, ).as_sql(with_col_aliases=True) sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql) params += inner_query_params return sql, params def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close()
b9b6f48f0667ed658e62c467cf824e3f94d08db0c9c89344c55633d13afb789d
""" PostgreSQL database backend for Django. Requires psycopg2 >= 2.8.4 or psycopg >= 3.1.8 """ import asyncio import threading import warnings from contextlib import contextmanager from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import DatabaseError as WrappedDatabaseError from django.db import connections from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.utils import CursorDebugWrapper as BaseCursorDebugWrapper from django.utils.asyncio import async_unsafe from django.utils.functional import cached_property from django.utils.safestring import SafeString from django.utils.version import get_version_tuple try: try: import psycopg as Database except ImportError: import psycopg2 as Database except ImportError: raise ImproperlyConfigured("Error loading psycopg2 or psycopg module") def psycopg_version(): version = Database.__version__.split(" ", 1)[0] return get_version_tuple(version) if psycopg_version() < (2, 8, 4): raise ImproperlyConfigured( f"psycopg2 version 2.8.4 or newer is required; you have {Database.__version__}" ) if (3,) <= psycopg_version() < (3, 1, 8): raise ImproperlyConfigured( f"psycopg version 3.1.8 or newer is required; you have {Database.__version__}" ) from .psycopg_any import IsolationLevel, is_psycopg3 # NOQA isort:skip if is_psycopg3: from psycopg import adapters, sql from psycopg.pq import Format from .psycopg_any import get_adapters_template, register_tzloader TIMESTAMPTZ_OID = adapters.types["timestamptz"].oid else: import psycopg2.extensions import psycopg2.extras psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString) psycopg2.extras.register_uuid() # Register support for inet[] manually so we don't have to handle the Inet() # object on load all the time. INETARRAY_OID = 1041 INETARRAY = psycopg2.extensions.new_array_type( (INETARRAY_OID,), "INETARRAY", psycopg2.extensions.UNICODE, ) psycopg2.extensions.register_type(INETARRAY) # Some of these import psycopg, so import them after checking if it's installed. from .client import DatabaseClient # NOQA isort:skip from .creation import DatabaseCreation # NOQA isort:skip from .features import DatabaseFeatures # NOQA isort:skip from .introspection import DatabaseIntrospection # NOQA isort:skip from .operations import DatabaseOperations # NOQA isort:skip from .schema import DatabaseSchemaEditor # NOQA isort:skip def _get_varchar_column(data): if data["max_length"] is None: return "varchar" return "varchar(%(max_length)s)" % data class DatabaseWrapper(BaseDatabaseWrapper): vendor = "postgresql" display_name = "PostgreSQL" # This dictionary maps Field objects to their associated PostgreSQL column # types, as strings. Column-type strings can contain format strings; they'll # be interpolated against the values of Field.__dict__ before being output. # If a column type is set to None, it won't be included in the output. data_types = { "AutoField": "integer", "BigAutoField": "bigint", "BinaryField": "bytea", "BooleanField": "boolean", "CharField": _get_varchar_column, "DateField": "date", "DateTimeField": "timestamp with time zone", "DecimalField": "numeric(%(max_digits)s, %(decimal_places)s)", "DurationField": "interval", "FileField": "varchar(%(max_length)s)", "FilePathField": "varchar(%(max_length)s)", "FloatField": "double precision", "IntegerField": "integer", "BigIntegerField": "bigint", "IPAddressField": "inet", "GenericIPAddressField": "inet", "JSONField": "jsonb", "OneToOneField": "integer", "PositiveBigIntegerField": "bigint", "PositiveIntegerField": "integer", "PositiveSmallIntegerField": "smallint", "SlugField": "varchar(%(max_length)s)", "SmallAutoField": "smallint", "SmallIntegerField": "smallint", "TextField": "text", "TimeField": "time", "UUIDField": "uuid", } data_type_check_constraints = { "PositiveBigIntegerField": '"%(column)s" >= 0', "PositiveIntegerField": '"%(column)s" >= 0', "PositiveSmallIntegerField": '"%(column)s" >= 0', } data_types_suffix = { "AutoField": "GENERATED BY DEFAULT AS IDENTITY", "BigAutoField": "GENERATED BY DEFAULT AS IDENTITY", "SmallAutoField": "GENERATED BY DEFAULT AS IDENTITY", } operators = { "exact": "= %s", "iexact": "= UPPER(%s)", "contains": "LIKE %s", "icontains": "LIKE UPPER(%s)", "regex": "~ %s", "iregex": "~* %s", "gt": "> %s", "gte": ">= %s", "lt": "< %s", "lte": "<= %s", "startswith": "LIKE %s", "endswith": "LIKE %s", "istartswith": "LIKE UPPER(%s)", "iendswith": "LIKE UPPER(%s)", } # The patterns below are used to generate SQL pattern lookup clauses when # the right-hand side of the lookup isn't a raw string (it might be an expression # or the result of a bilateral transformation). # In those cases, special characters for LIKE operators (e.g. \, *, _) should be # escaped on database side. # # Note: we use str.format() here for readability as '%' is used as a wildcard for # the LIKE operator. pattern_esc = ( r"REPLACE(REPLACE(REPLACE({}, E'\\', E'\\\\'), E'%%', E'\\%%'), E'_', E'\\_')" ) pattern_ops = { "contains": "LIKE '%%' || {} || '%%'", "icontains": "LIKE '%%' || UPPER({}) || '%%'", "startswith": "LIKE {} || '%%'", "istartswith": "LIKE UPPER({}) || '%%'", "endswith": "LIKE '%%' || {}", "iendswith": "LIKE '%%' || UPPER({})", } Database = Database SchemaEditorClass = DatabaseSchemaEditor # Classes instantiated in __init__(). client_class = DatabaseClient creation_class = DatabaseCreation features_class = DatabaseFeatures introspection_class = DatabaseIntrospection ops_class = DatabaseOperations # PostgreSQL backend-specific attributes. _named_cursor_idx = 0 def get_database_version(self): """ Return a tuple of the database's version. E.g. for pg_version 120004, return (12, 4). """ return divmod(self.pg_version, 10000) def get_connection_params(self): settings_dict = self.settings_dict # None may be used to connect to the default 'postgres' db if settings_dict["NAME"] == "" and not settings_dict.get("OPTIONS", {}).get( "service" ): raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME or OPTIONS['service'] value." ) if len(settings_dict["NAME"] or "") > self.ops.max_name_length(): raise ImproperlyConfigured( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %d characters. Supply a shorter NAME " "in settings.DATABASES." % ( settings_dict["NAME"], len(settings_dict["NAME"]), self.ops.max_name_length(), ) ) conn_params = {"client_encoding": "UTF8"} if settings_dict["NAME"]: conn_params = { "dbname": settings_dict["NAME"], **settings_dict["OPTIONS"], } elif settings_dict["NAME"] is None: # Connect to the default 'postgres' db. settings_dict.get("OPTIONS", {}).pop("service", None) conn_params = {"dbname": "postgres", **settings_dict["OPTIONS"]} else: conn_params = {**settings_dict["OPTIONS"]} conn_params.pop("assume_role", None) conn_params.pop("isolation_level", None) conn_params.pop("server_side_binding", None) if settings_dict["USER"]: conn_params["user"] = settings_dict["USER"] if settings_dict["PASSWORD"]: conn_params["password"] = settings_dict["PASSWORD"] if settings_dict["HOST"]: conn_params["host"] = settings_dict["HOST"] if settings_dict["PORT"]: conn_params["port"] = settings_dict["PORT"] if is_psycopg3: conn_params["context"] = get_adapters_template( settings.USE_TZ, self.timezone ) # Disable prepared statements by default to keep connection poolers # working. Can be reenabled via OPTIONS in the settings dict. conn_params["prepare_threshold"] = conn_params.pop( "prepare_threshold", None ) return conn_params @async_unsafe def get_new_connection(self, conn_params): # self.isolation_level must be set: # - after connecting to the database in order to obtain the database's # default when no value is explicitly specified in options. # - before calling _set_autocommit() because if autocommit is on, that # will set connection.isolation_level to ISOLATION_LEVEL_AUTOCOMMIT. options = self.settings_dict["OPTIONS"] set_isolation_level = False try: isolation_level_value = options["isolation_level"] except KeyError: self.isolation_level = IsolationLevel.READ_COMMITTED else: # Set the isolation level to the value from OPTIONS. try: self.isolation_level = IsolationLevel(isolation_level_value) set_isolation_level = True except ValueError: raise ImproperlyConfigured( f"Invalid transaction isolation level {isolation_level_value} " f"specified. Use one of the psycopg.IsolationLevel values." ) connection = self.Database.connect(**conn_params) if set_isolation_level: connection.isolation_level = self.isolation_level if is_psycopg3: connection.cursor_factory = ( ServerBindingCursor if options.get("server_side_binding") is True else Cursor ) else: # Register dummy loads() to avoid a round trip from psycopg2's # decode to json.dumps() to json.loads(), when using a custom # decoder in JSONField. psycopg2.extras.register_default_jsonb( conn_or_curs=connection, loads=lambda x: x ) connection.cursor_factory = Cursor return connection def ensure_timezone(self): if self.connection is None: return False conn_timezone_name = self.connection.info.parameter_status("TimeZone") timezone_name = self.timezone_name if timezone_name and conn_timezone_name != timezone_name: with self.connection.cursor() as cursor: cursor.execute(self.ops.set_time_zone_sql(), [timezone_name]) return True return False def ensure_role(self): if self.connection is None: return False if new_role := self.settings_dict.get("OPTIONS", {}).get("assume_role"): with self.connection.cursor() as cursor: sql = self.ops.compose_sql("SET ROLE %s", [new_role]) cursor.execute(sql) return True return False def init_connection_state(self): super().init_connection_state() # Commit after setting the time zone. commit_tz = self.ensure_timezone() # Set the role on the connection. This is useful if the credential used # to login is not the same as the role that owns database resources. As # can be the case when using temporary or ephemeral credentials. commit_role = self.ensure_role() if (commit_role or commit_tz) and not self.get_autocommit(): self.connection.commit() @async_unsafe def create_cursor(self, name=None): if name: # In autocommit mode, the cursor will be used outside of a # transaction, hence use a holdable cursor. cursor = self.connection.cursor( name, scrollable=False, withhold=self.connection.autocommit ) else: cursor = self.connection.cursor() if is_psycopg3: # Register the cursor timezone only if the connection disagrees, to # avoid copying the adapter map. tzloader = self.connection.adapters.get_loader(TIMESTAMPTZ_OID, Format.TEXT) if self.timezone != tzloader.timezone: register_tzloader(self.timezone, cursor) else: cursor.tzinfo_factory = self.tzinfo_factory if settings.USE_TZ else None return cursor def tzinfo_factory(self, offset): return self.timezone @async_unsafe def chunked_cursor(self): self._named_cursor_idx += 1 # Get the current async task # Note that right now this is behind @async_unsafe, so this is # unreachable, but in future we'll start loosening this restriction. # For now, it's here so that every use of "threading" is # also async-compatible. try: current_task = asyncio.current_task() except RuntimeError: current_task = None # Current task can be none even if the current_task call didn't error if current_task: task_ident = str(id(current_task)) else: task_ident = "sync" # Use that and the thread ident to get a unique name return self._cursor( name="_django_curs_%d_%s_%d" % ( # Avoid reusing name in other threads / tasks threading.current_thread().ident, task_ident, self._named_cursor_idx, ) ) def _set_autocommit(self, autocommit): with self.wrap_database_errors: self.connection.autocommit = autocommit def check_constraints(self, table_names=None): """ Check constraints by setting them to immediate. Return them to deferred afterward. """ with self.cursor() as cursor: cursor.execute("SET CONSTRAINTS ALL IMMEDIATE") cursor.execute("SET CONSTRAINTS ALL DEFERRED") def is_usable(self): try: # Use a psycopg cursor directly, bypassing Django's utilities. with self.connection.cursor() as cursor: cursor.execute("SELECT 1") except Database.Error: return False else: return True @contextmanager def _nodb_cursor(self): cursor = None try: with super()._nodb_cursor() as cursor: yield cursor except (Database.DatabaseError, WrappedDatabaseError): if cursor is not None: raise warnings.warn( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' database " "and will use the first PostgreSQL database instead.", RuntimeWarning, ) for connection in connections.all(): if ( connection.vendor == "postgresql" and connection.settings_dict["NAME"] != "postgres" ): conn = self.__class__( { **self.settings_dict, "NAME": connection.settings_dict["NAME"], }, alias=self.alias, ) try: with conn.cursor() as cursor: yield cursor finally: conn.close() break else: raise @cached_property def pg_version(self): with self.temporary_connection(): return self.connection.info.server_version def make_debug_cursor(self, cursor): return CursorDebugWrapper(cursor, self) if is_psycopg3: class CursorMixin: """ A subclass of psycopg cursor implementing callproc. """ def callproc(self, name, args=None): if not isinstance(name, sql.Identifier): name = sql.Identifier(name) qparts = [sql.SQL("SELECT * FROM "), name, sql.SQL("(")] if args: for item in args: qparts.append(sql.Literal(item)) qparts.append(sql.SQL(",")) del qparts[-1] qparts.append(sql.SQL(")")) stmt = sql.Composed(qparts) self.execute(stmt) return args class ServerBindingCursor(CursorMixin, Database.Cursor): pass class Cursor(CursorMixin, Database.ClientCursor): pass class CursorDebugWrapper(BaseCursorDebugWrapper): def copy(self, statement): with self.debug_sql(statement): return self.cursor.copy(statement) else: Cursor = psycopg2.extensions.cursor class CursorDebugWrapper(BaseCursorDebugWrapper): def copy_expert(self, sql, file, *args): with self.debug_sql(sql): return self.cursor.copy_expert(sql, file, *args) def copy_to(self, file, table, *args, **kwargs): with self.debug_sql(sql="COPY %s TO STDOUT" % table): return self.cursor.copy_to(file, table, *args, **kwargs)
8847d0326086a00d42962f22d596cd9f4524d8eb1ef08436da52c317905cbd76
""" HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21). Based on wsgiref.simple_server which is part of the standard library since 2.5. This is a simple server for use in testing or debugging Django apps. It hasn't been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE! """ import logging import socket import socketserver import sys from wsgiref import simple_server from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import LimitedStream from django.core.wsgi import get_wsgi_application from django.db import connections from django.utils.module_loading import import_string __all__ = ("WSGIServer", "WSGIRequestHandler") logger = logging.getLogger("django.server") def get_internal_wsgi_application(): """ Load and return the WSGI application as configured by the user in ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout, this will be the ``application`` object in ``projectname/wsgi.py``. This function, and the ``WSGI_APPLICATION`` setting itself, are only useful for Django's internal server (runserver); external WSGI servers should just be configured to point to the correct application object directly. If settings.WSGI_APPLICATION is not set (is ``None``), return whatever ``django.core.wsgi.get_wsgi_application`` returns. """ from django.conf import settings app_path = getattr(settings, "WSGI_APPLICATION") if app_path is None: return get_wsgi_application() try: return import_string(app_path) except ImportError as err: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "Error importing module." % app_path ) from err def is_broken_pipe_error(): exc_type, _, _ = sys.exc_info() return issubclass( exc_type, ( BrokenPipeError, ConnectionAbortedError, ConnectionResetError, ), ) class WSGIServer(simple_server.WSGIServer): """BaseHTTPServer that implements the Python WSGI protocol""" request_queue_size = 10 def __init__(self, *args, ipv6=False, allow_reuse_address=True, **kwargs): if ipv6: self.address_family = socket.AF_INET6 self.allow_reuse_address = allow_reuse_address super().__init__(*args, **kwargs) def handle_error(self, request, client_address): if is_broken_pipe_error(): logger.info("- Broken pipe from %s", client_address) else: super().handle_error(request, client_address) class ThreadedWSGIServer(socketserver.ThreadingMixIn, WSGIServer): """A threaded version of the WSGIServer""" daemon_threads = True def __init__(self, *args, connections_override=None, **kwargs): super().__init__(*args, **kwargs) self.connections_override = connections_override # socketserver.ThreadingMixIn.process_request() passes this method as # the target to a new Thread object. def process_request_thread(self, request, client_address): if self.connections_override: # Override this thread's database connections with the ones # provided by the parent thread. for alias, conn in self.connections_override.items(): connections[alias] = conn super().process_request_thread(request, client_address) def _close_connections(self): # Used for mocking in tests. connections.close_all() def close_request(self, request): self._close_connections() super().close_request(request) class ServerHandler(simple_server.ServerHandler): http_version = "1.1" def __init__(self, stdin, stdout, stderr, environ, **kwargs): """ Use a LimitedStream so that unread request data will be ignored at the end of the request. WSGIRequest uses a LimitedStream but it shouldn't discard the data since the upstream servers usually do this. This fix applies only for testserver/runserver. """ try: content_length = int(environ.get("CONTENT_LENGTH")) except (ValueError, TypeError): content_length = 0 super().__init__( LimitedStream(stdin, content_length), stdout, stderr, environ, **kwargs ) def cleanup_headers(self): super().cleanup_headers() # HTTP/1.1 requires support for persistent connections. Send 'close' if # the content length is unknown to prevent clients from reusing the # connection. if "Content-Length" not in self.headers: self.headers["Connection"] = "close" # Persistent connections require threading server. elif not isinstance(self.request_handler.server, socketserver.ThreadingMixIn): self.headers["Connection"] = "close" # Mark the connection for closing if it's set as such above or if the # application sent the header. if self.headers.get("Connection") == "close": self.request_handler.close_connection = True def close(self): self.get_stdin().read() super().close() class WSGIRequestHandler(simple_server.WSGIRequestHandler): protocol_version = "HTTP/1.1" def address_string(self): # Short-circuit parent method to not call socket.getfqdn return self.client_address[0] def log_message(self, format, *args): extra = { "request": self.request, "server_time": self.log_date_time_string(), } if args[1][0] == "4": # 0x16 = Handshake, 0x03 = SSL 3.0 or TLS 1.x if args[0].startswith("\x16\x03"): extra["status_code"] = 500 logger.error( "You're accessing the development server over HTTPS, but " "it only supports HTTP.", extra=extra, ) return if args[1].isdigit() and len(args[1]) == 3: status_code = int(args[1]) extra["status_code"] = status_code if status_code >= 500: level = logger.error elif status_code >= 400: level = logger.warning else: level = logger.info else: level = logger.info level(format, *args, extra=extra) def get_environ(self): # Strip all headers with underscores in the name before constructing # the WSGI environ. This prevents header-spoofing based on ambiguity # between underscores and dashes both normalized to underscores in WSGI # env vars. Nginx and Apache 2.4+ both do this as well. for k in self.headers: if "_" in k: del self.headers[k] return super().get_environ() def handle(self): self.close_connection = True self.handle_one_request() while not self.close_connection: self.handle_one_request() try: self.connection.shutdown(socket.SHUT_WR) except (AttributeError, OSError): pass def handle_one_request(self): """Copy of WSGIRequestHandler.handle() but with different ServerHandler""" self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) > 65536: self.requestline = "" self.request_version = "" self.command = "" self.send_error(414) return if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) handler.request_handler = self # backpointer for logging & connection closing handler.run(self.server.get_app()) def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer): server_address = (addr, port) if threading: httpd_cls = type("WSGIServer", (socketserver.ThreadingMixIn, server_cls), {}) else: httpd_cls = server_cls httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) if threading: # ThreadingMixIn.daemon_threads indicates how threads will behave on an # abrupt shutdown; like quitting the server by the user or restarting # by the auto-reloader. True means the server will not wait for thread # termination before it quits. This will make auto-reloader faster # and will prevent the need to kill the server manually if a thread # isn't terminating correctly. httpd.daemon_threads = True httpd.set_app(wsgi_handler) httpd.serve_forever()
105bbcef65f3414110b8ebd9b1ff429007fbe2fb9f91d298452342c48f4b57b1
import argparse import mimetypes import os import posixpath import shutil import stat import tempfile from importlib import import_module from urllib.request import build_opener import django from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import ( find_formatters, handle_extensions, run_formatters, ) from django.template import Context, Engine from django.utils import archive from django.utils.http import parse_header_parameters from django.utils.version import get_docs_version class TemplateCommand(BaseCommand): """ Copy either a Django application layout template or a Django project layout template into the specified directory. :param style: A color style object (see django.core.management.color). :param app_or_project: The string 'app' or 'project'. :param name: The name of the application or project. :param directory: The directory to which the template should be copied. :param options: The additional variables passed to project or app templates """ requires_system_checks = [] # The supported URL schemes url_schemes = ["http", "https", "ftp"] # Rewrite the following suffixes when determining the target filename. rewrite_template_suffixes = ( # Allow shipping invalid .py files without byte-compilation. (".py-tpl", ".py"), ) def add_arguments(self, parser): parser.add_argument("name", help="Name of the application or project.") parser.add_argument( "directory", nargs="?", help="Optional destination directory" ) parser.add_argument( "--template", help="The path or URL to load the template from." ) parser.add_argument( "--extension", "-e", dest="extensions", action="append", default=["py"], help='The file extension(s) to render (default: "py"). ' "Separate multiple extensions with commas, or use " "-e multiple times.", ) parser.add_argument( "--name", "-n", dest="files", action="append", default=[], help="The file name(s) to render. Separate multiple file names " "with commas, or use -n multiple times.", ) parser.add_argument( "--exclude", "-x", action="append", default=argparse.SUPPRESS, nargs="?", const="", help=( "The directory name(s) to exclude, in addition to .git and " "__pycache__. Can be used multiple times." ), ) def handle(self, app_or_project, name, target=None, **options): self.app_or_project = app_or_project self.a_or_an = "an" if app_or_project == "app" else "a" self.paths_to_remove = [] self.verbosity = options["verbosity"] self.validate_name(name) # if some directory is given, make sure it's nicely expanded if target is None: top_dir = os.path.join(os.getcwd(), name) try: os.makedirs(top_dir) except FileExistsError: raise CommandError("'%s' already exists" % top_dir) except OSError as e: raise CommandError(e) else: top_dir = os.path.abspath(os.path.expanduser(target)) if app_or_project == "app": self.validate_name(os.path.basename(top_dir), "directory") if not os.path.exists(top_dir): raise CommandError( "Destination directory '%s' does not " "exist, please create it first." % top_dir ) # Find formatters, which are external executables, before input # from the templates can sneak into the path. formatter_paths = find_formatters() extensions = tuple(handle_extensions(options["extensions"])) extra_files = [] excluded_directories = [".git", "__pycache__"] for file in options["files"]: extra_files.extend(map(lambda x: x.strip(), file.split(","))) if exclude := options.get("exclude"): for directory in exclude: excluded_directories.append(directory.strip()) if self.verbosity >= 2: self.stdout.write( "Rendering %s template files with extensions: %s" % (app_or_project, ", ".join(extensions)) ) self.stdout.write( "Rendering %s template files with filenames: %s" % (app_or_project, ", ".join(extra_files)) ) base_name = "%s_name" % app_or_project base_subdir = "%s_template" % app_or_project base_directory = "%s_directory" % app_or_project camel_case_name = "camel_case_%s_name" % app_or_project camel_case_value = "".join(x for x in name.title() if x != "_") context = Context( { **options, base_name: name, base_directory: top_dir, camel_case_name: camel_case_value, "docs_version": get_docs_version(), "django_version": django.__version__, }, autoescape=False, ) # Setup a stub settings environment for template rendering if not settings.configured: settings.configure() django.setup() template_dir = self.handle_template(options["template"], base_subdir) prefix_length = len(template_dir) + 1 for root, dirs, files in os.walk(template_dir): path_rest = root[prefix_length:] relative_dir = path_rest.replace(base_name, name) if relative_dir: target_dir = os.path.join(top_dir, relative_dir) os.makedirs(target_dir, exist_ok=True) for dirname in dirs[:]: if "exclude" not in options: if dirname.startswith(".") or dirname == "__pycache__": dirs.remove(dirname) elif dirname in excluded_directories: dirs.remove(dirname) for filename in files: if filename.endswith((".pyo", ".pyc", ".py.class")): # Ignore some files as they cause various breakages. continue old_path = os.path.join(root, filename) new_path = os.path.join( top_dir, relative_dir, filename.replace(base_name, name) ) for old_suffix, new_suffix in self.rewrite_template_suffixes: if new_path.endswith(old_suffix): new_path = new_path.removesuffix(old_suffix) + new_suffix break # Only rewrite once if os.path.exists(new_path): raise CommandError( "%s already exists. Overlaying %s %s into an existing " "directory won't replace conflicting files." % ( new_path, self.a_or_an, app_or_project, ) ) # Only render the Python files, as we don't want to # accidentally render Django templates files if new_path.endswith(extensions) or filename in extra_files: with open(old_path, encoding="utf-8") as template_file: content = template_file.read() template = Engine().from_string(content) content = template.render(context) with open(new_path, "w", encoding="utf-8") as new_file: new_file.write(content) else: shutil.copyfile(old_path, new_path) if self.verbosity >= 2: self.stdout.write("Creating %s" % new_path) try: self.apply_umask(old_path, new_path) self.make_writeable(new_path) except OSError: self.stderr.write( "Notice: Couldn't set permission bits on %s. You're " "probably using an uncommon filesystem setup. No " "problem." % new_path, self.style.NOTICE, ) if self.paths_to_remove: if self.verbosity >= 2: self.stdout.write("Cleaning up temporary files.") for path_to_remove in self.paths_to_remove: if os.path.isfile(path_to_remove): os.remove(path_to_remove) else: shutil.rmtree(path_to_remove) run_formatters([top_dir], **formatter_paths) def handle_template(self, template, subdir): """ Determine where the app or project templates are. Use django.__path__[0] as the default because the Django install directory isn't known. """ if template is None: return os.path.join(django.__path__[0], "conf", subdir) else: template = template.removeprefix("file://") expanded_template = os.path.expanduser(template) expanded_template = os.path.normpath(expanded_template) if os.path.isdir(expanded_template): return expanded_template if self.is_url(template): # downloads the file and returns the path absolute_path = self.download(template) else: absolute_path = os.path.abspath(expanded_template) if os.path.exists(absolute_path): return self.extract(absolute_path) raise CommandError( "couldn't handle %s template %s." % (self.app_or_project, template) ) def validate_name(self, name, name_or_dir="name"): if name is None: raise CommandError( "you must provide {an} {app} name".format( an=self.a_or_an, app=self.app_or_project, ) ) # Check it's a valid directory name. if not name.isidentifier(): raise CommandError( "'{name}' is not a valid {app} {type}. Please make sure the " "{type} is a valid identifier.".format( name=name, app=self.app_or_project, type=name_or_dir, ) ) # Check it cannot be imported. try: import_module(name) except ImportError: pass else: raise CommandError( "'{name}' conflicts with the name of an existing Python " "module and cannot be used as {an} {app} {type}. Please try " "another {type}.".format( name=name, an=self.a_or_an, app=self.app_or_project, type=name_or_dir, ) ) def download(self, url): """ Download the given URL and return the file name. """ def cleanup_url(url): tmp = url.rstrip("/") filename = tmp.split("/")[-1] if url.endswith("/"): display_url = tmp + "/" else: display_url = url return filename, display_url prefix = "django_%s_template_" % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_download") self.paths_to_remove.append(tempdir) filename, display_url = cleanup_url(url) if self.verbosity >= 2: self.stdout.write("Downloading %s" % display_url) the_path = os.path.join(tempdir, filename) opener = build_opener() opener.addheaders = [("User-Agent", f"Django/{django.__version__}")] try: with opener.open(url) as source, open(the_path, "wb") as target: headers = source.info() target.write(source.read()) except OSError as e: raise CommandError( "couldn't download URL %s to %s: %s" % (url, filename, e) ) used_name = the_path.split("/")[-1] # Trying to get better name from response headers content_disposition = headers["content-disposition"] if content_disposition: _, params = parse_header_parameters(content_disposition) guessed_filename = params.get("filename") or used_name else: guessed_filename = used_name # Falling back to content type guessing ext = self.splitext(guessed_filename)[1] content_type = headers["content-type"] if not ext and content_type: ext = mimetypes.guess_extension(content_type) if ext: guessed_filename += ext # Move the temporary file to a filename that has better # chances of being recognized by the archive utils if used_name != guessed_filename: guessed_path = os.path.join(tempdir, guessed_filename) shutil.move(the_path, guessed_path) return guessed_path # Giving up return the_path def splitext(self, the_path): """ Like os.path.splitext, but takes off .tar, too """ base, ext = posixpath.splitext(the_path) if base.lower().endswith(".tar"): ext = base[-4:] + ext base = base[:-4] return base, ext def extract(self, filename): """ Extract the given file to a temporary directory and return the path of the directory with the extracted content. """ prefix = "django_%s_template_" % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_extract") self.paths_to_remove.append(tempdir) if self.verbosity >= 2: self.stdout.write("Extracting %s" % filename) try: archive.extract(filename, tempdir) return tempdir except (archive.ArchiveException, OSError) as e: raise CommandError( "couldn't extract file %s to %s: %s" % (filename, tempdir, e) ) def is_url(self, template): """Return True if the name looks like a URL.""" if ":" not in template: return False scheme = template.split(":", 1)[0].lower() return scheme in self.url_schemes def apply_umask(self, old_path, new_path): current_umask = os.umask(0) os.umask(current_umask) current_mode = stat.S_IMODE(os.stat(old_path).st_mode) os.chmod(new_path, current_mode & ~current_umask) def make_writeable(self, filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
bddc9057ee0bdca1c2dd13c3b0f6f6494fc40294d0a250915e212b066a75c0be
import datetime from dataclasses import dataclass from functools import wraps from django.contrib.sites.shortcuts import get_current_site from django.core.paginator import EmptyPage, PageNotAnInteger from django.http import Http404 from django.template.response import TemplateResponse from django.urls import reverse from django.utils import timezone from django.utils.http import http_date @dataclass class SitemapIndexItem: location: str last_mod: bool = None def x_robots_tag(func): @wraps(func) def inner(request, *args, **kwargs): response = func(request, *args, **kwargs) response.headers["X-Robots-Tag"] = "noindex, noodp, noarchive" return response return inner def _get_latest_lastmod(current_lastmod, new_lastmod): """ Returns the latest `lastmod` where `lastmod` can be either a date or a datetime. """ if not isinstance(new_lastmod, datetime.datetime): new_lastmod = datetime.datetime.combine(new_lastmod, datetime.time.min) if timezone.is_naive(new_lastmod): new_lastmod = timezone.make_aware(new_lastmod, datetime.timezone.utc) return new_lastmod if current_lastmod is None else max(current_lastmod, new_lastmod) @x_robots_tag def index( request, sitemaps, template_name="sitemap_index.xml", content_type="application/xml", sitemap_url_name="django.contrib.sitemaps.views.sitemap", ): req_protocol = request.scheme req_site = get_current_site(request) sites = [] # all sections' sitemap URLs all_indexes_lastmod = True latest_lastmod = None for section, site in sitemaps.items(): # For each section label, add links of all pages of its sitemap # (usually generated by the `sitemap` view). if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={"section": section}) absolute_url = "%s://%s%s" % (protocol, req_site.domain, sitemap_url) site_lastmod = site.get_latest_lastmod() if all_indexes_lastmod: if site_lastmod is not None: latest_lastmod = _get_latest_lastmod(latest_lastmod, site_lastmod) else: all_indexes_lastmod = False sites.append(SitemapIndexItem(absolute_url, site_lastmod)) # Add links to all pages of the sitemap. for page in range(2, site.paginator.num_pages + 1): sites.append( SitemapIndexItem("%s?p=%s" % (absolute_url, page), site_lastmod) ) # If lastmod is defined for all sites, set header so as # ConditionalGetMiddleware is able to send 304 NOT MODIFIED if all_indexes_lastmod and latest_lastmod: headers = {"Last-Modified": http_date(latest_lastmod.timestamp())} else: headers = None return TemplateResponse( request, template_name, {"sitemaps": sites}, content_type=content_type, headers=headers, ) @x_robots_tag def sitemap( request, sitemaps, section=None, template_name="sitemap.xml", content_type="application/xml", ): req_protocol = request.scheme req_site = get_current_site(request) if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps = [sitemaps[section]] else: maps = sitemaps.values() page = request.GET.get("p", 1) lastmod = None all_sites_lastmod = True urls = [] for site in maps: try: if callable(site): site = site() urls.extend(site.get_urls(page=page, site=req_site, protocol=req_protocol)) if all_sites_lastmod: site_lastmod = getattr(site, "latest_lastmod", None) if site_lastmod is not None: lastmod = _get_latest_lastmod(lastmod, site_lastmod) else: all_sites_lastmod = False except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) # If lastmod is defined for all sites, set header so as # ConditionalGetMiddleware is able to send 304 NOT MODIFIED if all_sites_lastmod: headers = {"Last-Modified": http_date(lastmod.timestamp())} if lastmod else None else: headers = None return TemplateResponse( request, template_name, {"urlset": urls}, content_type=content_type, headers=headers, )
ccf7aa9a8cb14a41d2f7eab2ce74c3672e54d6e4b84c9ec5faf51c332fbe1636
import copy import json import re from functools import partial, update_wrapper from urllib.parse import quote as urlquote from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import helpers, widgets from django.contrib.admin.checks import ( BaseModelAdminChecks, InlineModelAdminChecks, ModelAdminChecks, ) from django.contrib.admin.decorators import display from django.contrib.admin.exceptions import DisallowedModelAdminToField from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( NestedObjects, construct_change_message, flatten_fieldsets, get_deleted_objects, lookup_spawns_duplicates, model_format_dict, model_ngettext, quote, unquote, ) from django.contrib.admin.widgets import AutocompleteSelect, AutocompleteSelectMultiple from django.contrib.auth import get_permission_codename from django.core.exceptions import ( FieldDoesNotExist, FieldError, PermissionDenied, ValidationError, ) from django.core.paginator import Paginator from django.db import models, router, transaction from django.db.models.constants import LOOKUP_SEP from django.forms.formsets import DELETION_FIELD_NAME, all_valid from django.forms.models import ( BaseInlineFormSet, inlineformset_factory, modelform_defines_fields, modelform_factory, modelformset_factory, ) from django.forms.widgets import CheckboxSelectMultiple, SelectMultiple from django.http import HttpResponseRedirect from django.http.response import HttpResponseBase from django.template.response import SimpleTemplateResponse, TemplateResponse from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.html import format_html from django.utils.http import urlencode from django.utils.safestring import mark_safe from django.utils.text import ( capfirst, format_lazy, get_text_list, smart_split, unescape_string_literal, ) from django.utils.translation import gettext as _ from django.utils.translation import ngettext from django.views.decorators.csrf import csrf_protect from django.views.generic import RedirectView IS_POPUP_VAR = "_popup" TO_FIELD_VAR = "_to_field" HORIZONTAL, VERTICAL = 1, 2 def get_content_type_for_model(obj): # Since this module gets imported in the application's root package, # it cannot import models from other applications at the module level. from django.contrib.contenttypes.models import ContentType return ContentType.objects.get_for_model(obj, for_concrete_model=False) def get_ul_class(radio_style): return "radiolist" if radio_style == VERTICAL else "radiolist inline" class IncorrectLookupParameters(Exception): pass # Defaults for formfield_overrides. ModelAdmin subclasses can change this # by adding to ModelAdmin.formfield_overrides. FORMFIELD_FOR_DBFIELD_DEFAULTS = { models.DateTimeField: { "form_class": forms.SplitDateTimeField, "widget": widgets.AdminSplitDateTime, }, models.DateField: {"widget": widgets.AdminDateWidget}, models.TimeField: {"widget": widgets.AdminTimeWidget}, models.TextField: {"widget": widgets.AdminTextareaWidget}, models.URLField: {"widget": widgets.AdminURLFieldWidget}, models.IntegerField: {"widget": widgets.AdminIntegerFieldWidget}, models.BigIntegerField: {"widget": widgets.AdminBigIntegerFieldWidget}, models.CharField: {"widget": widgets.AdminTextInputWidget}, models.ImageField: {"widget": widgets.AdminFileWidget}, models.FileField: {"widget": widgets.AdminFileWidget}, models.EmailField: {"widget": widgets.AdminEmailInputWidget}, models.UUIDField: {"widget": widgets.AdminUUIDInputWidget}, } csrf_protect_m = method_decorator(csrf_protect) class BaseModelAdmin(metaclass=forms.MediaDefiningClass): """Functionality common to both ModelAdmin and InlineAdmin.""" autocomplete_fields = () raw_id_fields = () fields = None exclude = None fieldsets = None form = forms.ModelForm filter_vertical = () filter_horizontal = () radio_fields = {} prepopulated_fields = {} formfield_overrides = {} readonly_fields = () ordering = None sortable_by = None view_on_site = True show_full_result_count = True checks_class = BaseModelAdminChecks def check(self, **kwargs): return self.checks_class().check(self, **kwargs) def __init__(self): # Merge FORMFIELD_FOR_DBFIELD_DEFAULTS with the formfield_overrides # rather than simply overwriting. overrides = copy.deepcopy(FORMFIELD_FOR_DBFIELD_DEFAULTS) for k, v in self.formfield_overrides.items(): overrides.setdefault(k, {}).update(v) self.formfield_overrides = overrides def formfield_for_dbfield(self, db_field, request, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, they're passed to the form Field's constructor. """ # If the field specifies choices, we don't need to look for special # admin widgets - we just need to use a select widget of some kind. if db_field.choices: return self.formfield_for_choice_field(db_field, request, **kwargs) # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = {**self.formfield_overrides[db_field.__class__], **kwargs} # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: related_modeladmin = self.admin_site._registry.get( db_field.remote_field.model ) wrapper_kwargs = {} if related_modeladmin: wrapper_kwargs.update( can_add_related=related_modeladmin.has_add_permission(request), can_change_related=related_modeladmin.has_change_permission( request ), can_delete_related=related_modeladmin.has_delete_permission( request ), can_view_related=related_modeladmin.has_view_permission( request ), ) formfield.widget = widgets.RelatedFieldWidgetWrapper( formfield.widget, db_field.remote_field, self.admin_site, **wrapper_kwargs, ) return formfield # If we've got overrides for the formfield defined, use 'em. **kwargs # passed to formfield_for_dbfield override the defaults. for klass in db_field.__class__.mro(): if klass in self.formfield_overrides: kwargs = {**copy.deepcopy(self.formfield_overrides[klass]), **kwargs} return db_field.formfield(**kwargs) # For any other type of field, just call its formfield() method. return db_field.formfield(**kwargs) def formfield_for_choice_field(self, db_field, request, **kwargs): """ Get a form Field for a database Field that has declared choices. """ # If the field is named as a radio_field, use a RadioSelect if db_field.name in self.radio_fields: # Avoid stomping on custom widget/choices arguments. if "widget" not in kwargs: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) if "choices" not in kwargs: kwargs["choices"] = db_field.get_choices( include_blank=db_field.blank, blank_choice=[("", _("None"))] ) return db_field.formfield(**kwargs) def get_field_queryset(self, db, db_field, request): """ If the ModelAdmin specifies ordering, the queryset should respect that ordering. Otherwise don't specify the queryset, let the field decide (return None in that case). """ related_admin = self.admin_site._registry.get(db_field.remote_field.model) if related_admin is not None: ordering = related_admin.get_ordering(request) if ordering is not None and ordering != (): return db_field.remote_field.model._default_manager.using(db).order_by( *ordering ) return None def formfield_for_foreignkey(self, db_field, request, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get("using") if "widget" not in kwargs: if db_field.name in self.get_autocomplete_fields(request): kwargs["widget"] = AutocompleteSelect( db_field, self.admin_site, using=db ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ForeignKeyRawIdWidget( db_field.remote_field, self.admin_site, using=db ) elif db_field.name in self.radio_fields: kwargs["widget"] = widgets.AdminRadioSelect( attrs={ "class": get_ul_class(self.radio_fields[db_field.name]), } ) kwargs["empty_label"] = ( kwargs.get("empty_label", _("None")) if db_field.blank else None ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset return db_field.formfield(**kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): """ Get a form Field for a ManyToManyField. """ # If it uses an intermediary model that isn't auto created, don't show # a field in admin. if not db_field.remote_field.through._meta.auto_created: return None db = kwargs.get("using") if "widget" not in kwargs: autocomplete_fields = self.get_autocomplete_fields(request) if db_field.name in autocomplete_fields: kwargs["widget"] = AutocompleteSelectMultiple( db_field, self.admin_site, using=db, ) elif db_field.name in self.raw_id_fields: kwargs["widget"] = widgets.ManyToManyRawIdWidget( db_field.remote_field, self.admin_site, using=db, ) elif db_field.name in [*self.filter_vertical, *self.filter_horizontal]: kwargs["widget"] = widgets.FilteredSelectMultiple( db_field.verbose_name, db_field.name in self.filter_vertical ) if "queryset" not in kwargs: queryset = self.get_field_queryset(db, db_field, request) if queryset is not None: kwargs["queryset"] = queryset form_field = db_field.formfield(**kwargs) if ( isinstance(form_field.widget, SelectMultiple) and form_field.widget.allow_multiple_selected and not isinstance( form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple) ) ): msg = _( "Hold down “Control”, or “Command” on a Mac, to select more than one." ) help_text = form_field.help_text form_field.help_text = ( format_lazy("{} {}", help_text, msg) if help_text else msg ) return form_field def get_autocomplete_fields(self, request): """ Return a list of ForeignKey and/or ManyToMany fields which should use an autocomplete widget. """ return self.autocomplete_fields def get_view_on_site_url(self, obj=None): if obj is None or not self.view_on_site: return None if callable(self.view_on_site): return self.view_on_site(obj) elif hasattr(obj, "get_absolute_url"): # use the ContentType lookup if view_on_site is True return reverse( "admin:view_on_site", kwargs={ "content_type_id": get_content_type_for_model(obj).pk, "object_id": obj.pk, }, current_app=self.admin_site.name, ) def get_empty_value_display(self): """ Return the empty_value_display set on ModelAdmin or AdminSite. """ try: return mark_safe(self.empty_value_display) except AttributeError: return mark_safe(self.admin_site.empty_value_display) def get_exclude(self, request, obj=None): """ Hook for specifying exclude. """ return self.exclude def get_fields(self, request, obj=None): """ Hook for specifying fields. """ if self.fields: return self.fields # _get_form_for_get_fields() is implemented in subclasses. form = self._get_form_for_get_fields(request, obj) return [*form.base_fields, *self.get_readonly_fields(request, obj)] def get_fieldsets(self, request, obj=None): """ Hook for specifying fieldsets. """ if self.fieldsets: return self.fieldsets return [(None, {"fields": self.get_fields(request, obj)})] def get_inlines(self, request, obj): """Hook for specifying custom inlines.""" return self.inlines def get_ordering(self, request): """ Hook for specifying field ordering. """ return self.ordering or () # otherwise we might try to *None, which is bad ;) def get_readonly_fields(self, request, obj=None): """ Hook for specifying custom readonly fields. """ return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): """ Hook for specifying custom prepopulated fields. """ return self.prepopulated_fields def get_queryset(self, request): """ Return a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs def get_sortable_by(self, request): """Hook for specifying which fields can be sorted in the changelist.""" return ( self.sortable_by if self.sortable_by is not None else self.get_list_display(request) ) def lookup_allowed(self, lookup, value): from django.contrib.admin.filters import SimpleListFilter model = self.model # Check FKey lookups that are allowed, so that popups produced by # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to, # are allowed to work. for fk_lookup in model._meta.related_fkey_lookups: # As ``limit_choices_to`` can be a callable, invoke it here. if callable(fk_lookup): fk_lookup = fk_lookup() if (lookup, value) in widgets.url_params_from_lookup_dict( fk_lookup ).items(): return True relation_parts = [] prev_field = None for part in lookup.split(LOOKUP_SEP): try: field = model._meta.get_field(part) except FieldDoesNotExist: # Lookups on nonexistent fields are ok, since they're ignored # later. break # It is allowed to filter on values that would be found from local # model anyways. For example, if you filter on employee__department__id, # then the id value would be found already from employee__department_id. if not prev_field or ( prev_field.is_relation and field not in prev_field.path_infos[-1].target_fields ): relation_parts.append(part) if not getattr(field, "path_infos", None): # This is not a relational field, so further parts # must be transforms. break prev_field = field model = field.path_infos[-1].to_opts.model if len(relation_parts) <= 1: # Either a local field filter, or no fields at all. return True valid_lookups = {self.date_hierarchy} for filter_item in self.list_filter: if isinstance(filter_item, type) and issubclass( filter_item, SimpleListFilter ): valid_lookups.add(filter_item.parameter_name) elif isinstance(filter_item, (list, tuple)): valid_lookups.add(filter_item[0]) else: valid_lookups.add(filter_item) # Is it a valid relational lookup? return not { LOOKUP_SEP.join(relation_parts), LOOKUP_SEP.join(relation_parts + [part]), }.isdisjoint(valid_lookups) def to_field_allowed(self, request, to_field): """ Return True if the model associated with this admin should be allowed to be referenced by the specified field. """ try: field = self.opts.get_field(to_field) except FieldDoesNotExist: return False # Always allow referencing the primary key since it's already possible # to get this information from the change view URL. if field.primary_key: return True # Allow reverse relationships to models defining m2m fields if they # target the specified field. for many_to_many in self.opts.many_to_many: if many_to_many.m2m_target_field_name() == to_field: return True # Make sure at least one of the models registered for this site # references this field through a FK or a M2M relationship. registered_models = set() for model, admin in self.admin_site._registry.items(): registered_models.add(model) for inline in admin.inlines: registered_models.add(inline.model) related_objects = ( f for f in self.opts.get_fields(include_hidden=True) if (f.auto_created and not f.concrete) ) for related_object in related_objects: related_model = related_object.related_model remote_field = related_object.field.remote_field if ( any(issubclass(model, related_model) for model in registered_models) and hasattr(remote_field, "get_related_field") and remote_field.get_related_field() == field ): return True return False def has_add_permission(self, request): """ Return True if the given request has permission to add an object. Can be overridden by the user in subclasses. """ opts = self.opts codename = get_permission_codename("add", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_change_permission(self, request, obj=None): """ Return True if the given request has permission to change the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to change the `obj` model instance. If `obj` is None, this should return True if the given request has permission to change *any* object of the given type. """ opts = self.opts codename = get_permission_codename("change", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_delete_permission(self, request, obj=None): """ Return True if the given request has permission to delete the given Django model instance, the default implementation doesn't examine the `obj` parameter. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to delete the `obj` model instance. If `obj` is None, this should return True if the given request has permission to delete *any* object of the given type. """ opts = self.opts codename = get_permission_codename("delete", opts) return request.user.has_perm("%s.%s" % (opts.app_label, codename)) def has_view_permission(self, request, obj=None): """ Return True if the given request has permission to view the given Django model instance. The default implementation doesn't examine the `obj` parameter. If overridden by the user in subclasses, it should return True if the given request has permission to view the `obj` model instance. If `obj` is None, it should return True if the request has permission to view any object of the given type. """ opts = self.opts codename_view = get_permission_codename("view", opts) codename_change = get_permission_codename("change", opts) return request.user.has_perm( "%s.%s" % (opts.app_label, codename_view) ) or request.user.has_perm("%s.%s" % (opts.app_label, codename_change)) def has_view_or_change_permission(self, request, obj=None): return self.has_view_permission(request, obj) or self.has_change_permission( request, obj ) def has_module_permission(self, request): """ Return True if the given request has any permission in the given app label. Can be overridden by the user in subclasses. In such case it should return True if the given request has permission to view the module on the admin index page and access the module's index page. Overriding it does not restrict access to the add, change or delete views. Use `ModelAdmin.has_(add|change|delete)_permission` for that. """ return request.user.has_module_perms(self.opts.app_label) class ModelAdmin(BaseModelAdmin): """Encapsulate all admin options and functionality for a given model.""" list_display = ("__str__",) list_display_links = () list_filter = () list_select_related = False list_per_page = 100 list_max_show_all = 200 list_editable = () search_fields = () search_help_text = None date_hierarchy = None save_as = False save_as_continue = True save_on_top = False paginator = Paginator preserve_filters = True inlines = () # Custom templates (designed to be over-ridden in subclasses) add_form_template = None change_form_template = None change_list_template = None delete_confirmation_template = None delete_selected_confirmation_template = None object_history_template = None popup_response_template = None # Actions actions = () action_form = helpers.ActionForm actions_on_top = True actions_on_bottom = False actions_selection_counter = True checks_class = ModelAdminChecks def __init__(self, model, admin_site): self.model = model self.opts = model._meta self.admin_site = admin_site super().__init__() def __str__(self): return "%s.%s" % (self.opts.app_label, self.__class__.__name__) def __repr__(self): return ( f"<{self.__class__.__qualname__}: model={self.model.__qualname__} " f"site={self.admin_site!r}>" ) def get_inline_instances(self, request, obj=None): inline_instances = [] for inline_class in self.get_inlines(request, obj): inline = inline_class(self.model, self.admin_site) if request: if not ( inline.has_view_or_change_permission(request, obj) or inline.has_add_permission(request, obj) or inline.has_delete_permission(request, obj) ): continue if not inline.has_add_permission(request, obj): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_urls(self): from django.urls import path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) wrapper.model_admin = self return update_wrapper(wrapper, view) info = self.opts.app_label, self.opts.model_name return [ path("", wrap(self.changelist_view), name="%s_%s_changelist" % info), path("add/", wrap(self.add_view), name="%s_%s_add" % info), path( "<path:object_id>/history/", wrap(self.history_view), name="%s_%s_history" % info, ), path( "<path:object_id>/delete/", wrap(self.delete_view), name="%s_%s_delete" % info, ), path( "<path:object_id>/change/", wrap(self.change_view), name="%s_%s_change" % info, ), # For backwards compatibility (was the change url before 1.9) path( "<path:object_id>/", wrap( RedirectView.as_view( pattern_name="%s:%s_%s_change" % ((self.admin_site.name,) + info) ) ), ), ] @property def urls(self): return self.get_urls() @property def media(self): extra = "" if settings.DEBUG else ".min" js = [ "vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "core.js", "admin/RelatedObjectLookups.js", "actions.js", "urlify.js", "prepopulate.js", "vendor/xregexp/xregexp%s.js" % extra, ] return forms.Media(js=["admin/js/%s" % url for url in js]) def get_model_perms(self, request): """ Return a dict of all perms for this model. This dict has the keys ``add``, ``change``, ``delete``, and ``view`` mapping to the True/False for each of those actions. """ return { "add": self.has_add_permission(request), "change": self.has_change_permission(request), "delete": self.has_delete_permission(request), "view": self.has_view_permission(request), } def _get_form_for_get_fields(self, request, obj): return self.get_form(request, obj, fields=None) def get_form(self, request, obj=None, change=False, **kwargs): """ Return a Form class for use in the admin add view. This is used by add_view and change_view. """ if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) readonly_fields = self.get_readonly_fields(request, obj) exclude.extend(readonly_fields) # Exclude all fields if it's a change form and the user doesn't have # the change permission. if ( change and hasattr(request, "user") and not self.has_change_permission(request, obj) ): exclude.extend(fields) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # ModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # if exclude is an empty list we pass None to be consistent with the # default on modelform_factory exclude = exclude or None # Remove declared form fields which are in readonly_fields. new_attrs = dict.fromkeys( f for f in readonly_fields if f in self.form.declared_fields ) form = type(self.form.__name__, (self.form,), new_attrs) defaults = { "form": form, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS try: return modelform_factory(self.model, **defaults) except FieldError as e: raise FieldError( "%s. Check fields/fieldsets/exclude attributes of class %s." % (e, self.__class__.__name__) ) def get_changelist(self, request, **kwargs): """ Return the ChangeList class for use on the changelist page. """ from django.contrib.admin.views.main import ChangeList return ChangeList def get_changelist_instance(self, request): """ Return a `ChangeList` instance based on `request`. May raise `IncorrectLookupParameters`. """ list_display = self.get_list_display(request) list_display_links = self.get_list_display_links(request, list_display) # Add the action checkboxes if any actions are available. if self.get_actions(request): list_display = ["action_checkbox", *list_display] sortable_by = self.get_sortable_by(request) ChangeList = self.get_changelist(request) return ChangeList( request, self.model, list_display, list_display_links, self.get_list_filter(request), self.date_hierarchy, self.get_search_fields(request), self.get_list_select_related(request), self.list_per_page, self.list_max_show_all, self.list_editable, self, sortable_by, self.search_help_text, ) def get_object(self, request, object_id, from_field=None): """ Return an instance matching the field and value provided, the primary key is used if no field is provided. Return ``None`` if no match is found or the object_id fails validation. """ queryset = self.get_queryset(request) model = queryset.model field = ( model._meta.pk if from_field is None else model._meta.get_field(from_field) ) try: object_id = field.to_python(object_id) return queryset.get(**{field.name: object_id}) except (model.DoesNotExist, ValidationError, ValueError): return None def get_changelist_form(self, request, **kwargs): """ Return a Form class for use in the Formset on the changelist page. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } if defaults.get("fields") is None and not modelform_defines_fields( defaults.get("form") ): defaults["fields"] = forms.ALL_FIELDS return modelform_factory(self.model, **defaults) def get_changelist_formset(self, request, **kwargs): """ Return a FormSet class for use on the changelist page if list_editable is used. """ defaults = { "formfield_callback": partial(self.formfield_for_dbfield, request=request), **kwargs, } return modelformset_factory( self.model, self.get_changelist_form(request), extra=0, fields=self.list_editable, **defaults, ) def get_formsets_with_inlines(self, request, obj=None): """ Yield formsets and the corresponding inlines. """ for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj), inline def get_paginator( self, request, queryset, per_page, orphans=0, allow_empty_first_page=True ): return self.paginator(queryset, per_page, orphans, allow_empty_first_page) def log_addition(self, request, obj, message): """ Log that an object has been successfully added. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import ADDITION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=ADDITION, change_message=message, ) def log_change(self, request, obj, message): """ Log that an object has been successfully changed. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import CHANGE, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=str(obj), action_flag=CHANGE, change_message=message, ) def log_deletion(self, request, obj, object_repr): """ Log that an object will be deleted. Note that this method must be called before the deletion. The default implementation creates an admin LogEntry object. """ from django.contrib.admin.models import DELETION, LogEntry return LogEntry.objects.log_action( user_id=request.user.pk, content_type_id=get_content_type_for_model(obj).pk, object_id=obj.pk, object_repr=object_repr, action_flag=DELETION, ) @display(description=mark_safe('<input type="checkbox" id="action-toggle">')) def action_checkbox(self, obj): """ A list_display column containing a checkbox widget. """ return helpers.checkbox.render(helpers.ACTION_CHECKBOX_NAME, str(obj.pk)) @staticmethod def _get_action_description(func, name): return getattr(func, "short_description", capfirst(name.replace("_", " "))) def _get_base_actions(self): """Return the list of actions, prior to any request-based filtering.""" actions = [] base_actions = (self.get_action(action) for action in self.actions or []) # get_action might have returned None, so filter any of those out. base_actions = [action for action in base_actions if action] base_action_names = {name for _, name, _ in base_actions} # Gather actions from the admin site first for (name, func) in self.admin_site.actions: if name in base_action_names: continue description = self._get_action_description(func, name) actions.append((func, name, description)) # Add actions from this ModelAdmin. actions.extend(base_actions) return actions def _filter_actions_by_permissions(self, request, actions): """Filter out any actions that the user doesn't have access to.""" filtered_actions = [] for action in actions: callable = action[0] if not hasattr(callable, "allowed_permissions"): filtered_actions.append(action) continue permission_checks = ( getattr(self, "has_%s_permission" % permission) for permission in callable.allowed_permissions ) if any(has_permission(request) for has_permission in permission_checks): filtered_actions.append(action) return filtered_actions def get_actions(self, request): """ Return a dictionary mapping the names of all actions for this ModelAdmin to a tuple of (callable, name, description) for each action. """ # If self.actions is set to None that means actions are disabled on # this page. if self.actions is None or IS_POPUP_VAR in request.GET: return {} actions = self._filter_actions_by_permissions(request, self._get_base_actions()) return {name: (func, name, desc) for func, name, desc in actions} def get_action_choices(self, request, default_choices=models.BLANK_CHOICE_DASH): """ Return a list of choices for use in a form object. Each choice is a tuple (name, description). """ choices = [] + default_choices for func, name, description in self.get_actions(request).values(): choice = (name, description % model_format_dict(self.opts)) choices.append(choice) return choices def get_action(self, action): """ Return a given action from a parameter, which can either be a callable, or the name of a method on the ModelAdmin. Return is a tuple of (callable, name, description). """ # If the action is a callable, just use it. if callable(action): func = action action = action.__name__ # Next, look for a method. Grab it off self.__class__ to get an unbound # method instead of a bound one; this ensures that the calling # conventions are the same for functions and methods. elif hasattr(self.__class__, action): func = getattr(self.__class__, action) # Finally, look for a named method on the admin site else: try: func = self.admin_site.get_action(action) except KeyError: return None description = self._get_action_description(func, action) return func, action, description def get_list_display(self, request): """ Return a sequence containing the fields to be displayed on the changelist. """ return self.list_display def get_list_display_links(self, request, list_display): """ Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display(). """ if ( self.list_display_links or self.list_display_links is None or not list_display ): return self.list_display_links else: # Use only the first item in list_display as link return list(list_display)[:1] def get_list_filter(self, request): """ Return a sequence containing the fields to be displayed as filters in the right sidebar of the changelist page. """ return self.list_filter def get_list_select_related(self, request): """ Return a list of fields to add to the select_related() part of the changelist items query. """ return self.list_select_related def get_search_fields(self, request): """ Return a sequence containing the fields to be searched whenever somebody submits a search query. """ return self.search_fields def get_search_results(self, request, queryset, search_term): """ Return a tuple containing a queryset to implement the search and a boolean indicating if the results may contain duplicates. """ # Apply keyword searches. def construct_search(field_name): if field_name.startswith("^"): return "%s__istartswith" % field_name.removeprefix("^") elif field_name.startswith("="): return "%s__iexact" % field_name.removeprefix("=") elif field_name.startswith("@"): return "%s__search" % field_name.removeprefix("@") # Use field_name if it includes a lookup. opts = queryset.model._meta lookup_fields = field_name.split(LOOKUP_SEP) # Go through the fields, following all relations. prev_field = None for path_part in lookup_fields: if path_part == "pk": path_part = opts.pk.name try: field = opts.get_field(path_part) except FieldDoesNotExist: # Use valid query lookups. if prev_field and prev_field.get_lookup(path_part): return field_name else: prev_field = field if hasattr(field, "path_infos"): # Update opts to follow the relation. opts = field.path_infos[-1].to_opts # Otherwise, use the field with icontains. return "%s__icontains" % field_name may_have_duplicates = False search_fields = self.get_search_fields(request) if search_fields and search_term: orm_lookups = [ construct_search(str(search_field)) for search_field in search_fields ] term_queries = [] for bit in smart_split(search_term): if bit.startswith(('"', "'")) and bit[0] == bit[-1]: bit = unescape_string_literal(bit) or_queries = models.Q.create( [(orm_lookup, bit) for orm_lookup in orm_lookups], connector=models.Q.OR, ) term_queries.append(or_queries) queryset = queryset.filter(models.Q.create(term_queries)) may_have_duplicates |= any( lookup_spawns_duplicates(self.opts, search_spec) for search_spec in orm_lookups ) return queryset, may_have_duplicates def get_preserved_filters(self, request): """ Return the preserved filters querystring. """ match = request.resolver_match if self.preserve_filters and match: current_url = "%s:%s" % (match.app_name, match.url_name) changelist_url = "admin:%s_%s_changelist" % ( self.opts.app_label, self.opts.model_name, ) if current_url == changelist_url: preserved_filters = request.GET.urlencode() else: preserved_filters = request.GET.get("_changelist_filters") if preserved_filters: return urlencode({"_changelist_filters": preserved_filters}) return "" def construct_change_message(self, request, form, formsets, add=False): """ Construct a JSON structure describing changes from a changed object. """ return construct_change_message(form, formsets, add) def message_user( self, request, message, level=messages.INFO, extra_tags="", fail_silently=False ): """ Send a message to the user. The default implementation posts a message using the django.contrib.messages backend. Exposes almost the same API as messages.add_message(), but accepts the positional arguments in a different order to maintain backwards compatibility. For convenience, it accepts the `level` argument as a string rather than the usual level number. """ if not isinstance(level, int): # attempt to get the level if passed a string try: level = getattr(messages.constants, level.upper()) except AttributeError: levels = messages.constants.DEFAULT_TAGS.values() levels_repr = ", ".join("`%s`" % level for level in levels) raise ValueError( "Bad message level string: `%s`. Possible values are: %s" % (level, levels_repr) ) messages.add_message( request, level, message, extra_tags=extra_tags, fail_silently=fail_silently ) def save_form(self, request, form, change): """ Given a ModelForm return an unsaved instance. ``change`` is True if the object is being changed, and False if it's being added. """ return form.save(commit=False) def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() def delete_model(self, request, obj): """ Given a model instance delete it from the database. """ obj.delete() def delete_queryset(self, request, queryset): """Given a queryset, delete it from the database.""" queryset.delete() def save_formset(self, request, form, formset, change): """ Given an inline formset save it to the database. """ formset.save() def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change) def render_change_form( self, request, context, add=False, change=False, form_url="", obj=None ): app_label = self.opts.app_label preserved_filters = self.get_preserved_filters(request) form_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, form_url ) view_on_site_url = self.get_view_on_site_url(obj) has_editable_inline_admin_formsets = False for inline in context["inline_admin_formsets"]: if ( inline.has_add_permission or inline.has_change_permission or inline.has_delete_permission ): has_editable_inline_admin_formsets = True break context.update( { "add": add, "change": change, "has_view_permission": self.has_view_permission(request, obj), "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), "has_editable_inline_admin_formsets": ( has_editable_inline_admin_formsets ), "has_file_field": context["adminform"].form.is_multipart() or any( admin_formset.formset.is_multipart() for admin_formset in context["inline_admin_formsets"] ), "has_absolute_url": view_on_site_url is not None, "absolute_url": view_on_site_url, "form_url": form_url, "opts": self.opts, "content_type_id": get_content_type_for_model(self.model).pk, "save_as": self.save_as, "save_on_top": self.save_on_top, "to_field_var": TO_FIELD_VAR, "is_popup_var": IS_POPUP_VAR, "app_label": app_label, } ) if add and self.add_form_template is not None: form_template = self.add_form_template else: form_template = self.change_form_template request.current_app = self.admin_site.name return TemplateResponse( request, form_template or [ "admin/%s/%s/change_form.html" % (app_label, self.opts.model_name), "admin/%s/change_form.html" % app_label, "admin/change_form.html", ], context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. """ opts = obj._meta preserved_filters = self.get_preserved_filters(request) obj_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(quote(obj.pk),), current_app=self.admin_site.name, ) # Add a link to the object's change form if the user can edit the obj. if self.has_change_permission(request, obj): obj_repr = format_html('<a href="{}">{}</a>', urlquote(obj_url), obj) else: obj_repr = str(obj) msg_dict = { "name": opts.verbose_name, "obj": obj_repr, } # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if IS_POPUP_VAR in request.POST: to_field = request.POST.get(TO_FIELD_VAR) if to_field: attr = str(to_field) else: attr = obj._meta.pk.attname value = obj.serializable_value(attr) popup_response_data = json.dumps( { "value": str(value), "obj": str(obj), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) elif "_continue" in request.POST or ( # Redirecting after "Save as new". "_saveasnew" in request.POST and self.save_as_continue and self.has_change_permission(request, obj) ): msg = _("The {name} “{obj}” was added successfully.") if self.has_change_permission(request, obj): msg += " " + _("You may edit it again below.") self.message_user(request, format_html(msg, **msg_dict), messages.SUCCESS) if post_url_continue is None: post_url_continue = obj_url post_url_continue = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, post_url_continue, ) return HttpResponseRedirect(post_url_continue) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was added successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_add(request, obj) def response_change(self, request, obj): """ Determine the HttpResponse for the change_view stage. """ if IS_POPUP_VAR in request.POST: opts = obj._meta to_field = request.POST.get(TO_FIELD_VAR) attr = str(to_field) if to_field else opts.pk.attname value = request.resolver_match.kwargs["object_id"] new_value = obj.serializable_value(attr) popup_response_data = json.dumps( { "action": "change", "value": str(value), "obj": str(obj), "new_value": str(new_value), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (opts.app_label, opts.model_name), "admin/%s/popup_response.html" % opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) opts = self.opts preserved_filters = self.get_preserved_filters(request) msg_dict = { "name": opts.verbose_name, "obj": format_html('<a href="{}">{}</a>', urlquote(request.path), obj), } if "_continue" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may edit it " "again below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = request.path redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_saveasnew" in request.POST: msg = format_html( _( "The {name} “{obj}” was added successfully. You may edit it again " "below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_change" % (opts.app_label, opts.model_name), args=(obj.pk,), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) elif "_addanother" in request.POST: msg = format_html( _( "The {name} “{obj}” was changed successfully. You may add another " "{name} below." ), **msg_dict, ) self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse( "admin:%s_%s_add" % (opts.app_label, opts.model_name), current_app=self.admin_site.name, ) redirect_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": opts}, redirect_url ) return HttpResponseRedirect(redirect_url) else: msg = format_html( _("The {name} “{obj}” was changed successfully."), **msg_dict ) self.message_user(request, msg, messages.SUCCESS) return self.response_post_save_change(request, obj) def _response_post_save(self, request, obj): if self.has_view_or_change_permission(request): post_url = reverse( "admin:%s_%s_changelist" % (self.opts.app_label, self.opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def response_post_save_add(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when adding a new object. """ return self._response_post_save(request, obj) def response_post_save_change(self, request, obj): """ Figure out where to redirect after the 'Save' button has been pressed when editing an existing object. """ return self._response_post_save(request, obj) def response_action(self, request, queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms on the page (at the top # and bottom of the change list, for example). Get the action # whose button was pushed. try: action_index = int(request.POST.get("index", 0)) except ValueError: action_index = 0 # Construct the action form. data = request.POST.copy() data.pop(helpers.ACTION_CHECKBOX_NAME, None) data.pop("index", None) # Use the action whose button was pushed try: data.update({"action": data.getlist("action")[action_index]}) except IndexError: # If we didn't get an action from the chosen form that's invalid # POST data, so by deleting action it'll fail the validation check # below. So no need to do anything here pass action_form = self.action_form(data, auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) # If the form's valid we can handle the action. if action_form.is_valid(): action = action_form.cleaned_data["action"] select_across = action_form.cleaned_data["select_across"] func = self.get_actions(request)[action][0] # Get the list of selected PKs. If nothing's selected, we can't # perform an action on it, so bail. Except we want to perform # the action explicitly on all objects. selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) if not selected and not select_across: # Reminder that something needs to be selected or nothing will happen msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) return None if not select_across: # Perform the action only on the selected objects queryset = queryset.filter(pk__in=selected) response = func(self, request, queryset) # Actions may return an HttpResponse-like object, which will be # used as the response from the POST. If not, we'll be a good # little HTTP citizen and redirect back to the changelist page. if isinstance(response, HttpResponseBase): return response else: return HttpResponseRedirect(request.get_full_path()) else: msg = _("No action selected.") self.message_user(request, msg, messages.WARNING) return None def response_delete(self, request, obj_display, obj_id): """ Determine the HttpResponse for the delete_view stage. """ if IS_POPUP_VAR in request.POST: popup_response_data = json.dumps( { "action": "delete", "value": str(obj_id), } ) return TemplateResponse( request, self.popup_response_template or [ "admin/%s/%s/popup_response.html" % (self.opts.app_label, self.opts.model_name), "admin/%s/popup_response.html" % self.opts.app_label, "admin/popup_response.html", ], { "popup_response_data": popup_response_data, }, ) self.message_user( request, _("The %(name)s “%(obj)s” was deleted successfully.") % { "name": self.opts.verbose_name, "obj": obj_display, }, messages.SUCCESS, ) if self.has_change_permission(request, None): post_url = reverse( "admin:%s_%s_changelist" % (self.opts.app_label, self.opts.model_name), current_app=self.admin_site.name, ) preserved_filters = self.get_preserved_filters(request) post_url = add_preserved_filters( {"preserved_filters": preserved_filters, "opts": self.opts}, post_url ) else: post_url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(post_url) def render_delete_form(self, request, context): app_label = self.opts.app_label request.current_app = self.admin_site.name context.update( to_field_var=TO_FIELD_VAR, is_popup_var=IS_POPUP_VAR, media=self.media, ) return TemplateResponse( request, self.delete_confirmation_template or [ "admin/{}/{}/delete_confirmation.html".format( app_label, self.opts.model_name ), "admin/{}/delete_confirmation.html".format(app_label), "admin/delete_confirmation.html", ], context, ) def get_inline_formsets(self, request, formsets, inline_instances, obj=None): # Edit permissions on parent model are required for editable inlines. can_edit_parent = ( self.has_change_permission(request, obj) if obj else self.has_add_permission(request) ) inline_admin_formsets = [] for inline, formset in zip(inline_instances, formsets): fieldsets = list(inline.get_fieldsets(request, obj)) readonly = list(inline.get_readonly_fields(request, obj)) if can_edit_parent: has_add_permission = inline.has_add_permission(request, obj) has_change_permission = inline.has_change_permission(request, obj) has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and override formset settings. has_add_permission = ( has_change_permission ) = has_delete_permission = False formset.extra = formset.max_num = 0 has_view_permission = inline.has_view_permission(request, obj) prepopulated = dict(inline.get_prepopulated_fields(request, obj)) inline_admin_formset = helpers.InlineAdminFormSet( inline, formset, fieldsets, prepopulated, readonly, model_admin=self, has_add_permission=has_add_permission, has_change_permission=has_change_permission, has_delete_permission=has_delete_permission, has_view_permission=has_view_permission, ) inline_admin_formsets.append(inline_admin_formset) return inline_admin_formsets def get_changeform_initial_data(self, request): """ Get the initial form data from the request's GET params. """ initial = dict(request.GET.items()) for k in initial: try: f = self.opts.get_field(k) except FieldDoesNotExist: continue # We have to special-case M2Ms as a list of comma-separated PKs. if isinstance(f, models.ManyToManyField): initial[k] = initial[k].split(",") return initial def _get_obj_does_not_exist_redirect(self, request, opts, object_id): """ Create a message informing the user that the object doesn't exist and return a redirect to the admin index page. """ msg = _("%(name)s with ID “%(key)s” doesn’t exist. Perhaps it was deleted?") % { "name": opts.verbose_name, "key": unquote(object_id), } self.message_user(request, msg, messages.WARNING) url = reverse("admin:index", current_app=self.admin_site.name) return HttpResponseRedirect(url) @csrf_protect_m def changeform_view(self, request, object_id=None, form_url="", extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._changeform_view(request, object_id, form_url, extra_context) def _changeform_view(self, request, object_id, form_url, extra_context): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) if request.method == "POST" and "_saveasnew" in request.POST: object_id = None add = object_id is None if add: if not self.has_add_permission(request): raise PermissionDenied obj = None else: obj = self.get_object(request, unquote(object_id), to_field) if request.method == "POST": if not self.has_change_permission(request, obj): raise PermissionDenied else: if not self.has_view_or_change_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect( request, self.opts, object_id ) fieldsets = self.get_fieldsets(request, obj) ModelForm = self.get_form( request, obj, change=not add, fields=flatten_fieldsets(fieldsets) ) if request.method == "POST": form = ModelForm(request.POST, request.FILES, instance=obj) formsets, inline_instances = self._create_formsets( request, form.instance, change=not add, ) form_validated = form.is_valid() if form_validated: new_object = self.save_form(request, form, change=not add) else: new_object = form.instance if all_valid(formsets) and form_validated: self.save_model(request, new_object, form, not add) self.save_related(request, form, formsets, not add) change_message = self.construct_change_message( request, form, formsets, add ) if add: self.log_addition(request, new_object, change_message) return self.response_add(request, new_object) else: self.log_change(request, new_object, change_message) return self.response_change(request, new_object) else: form_validated = False else: if add: initial = self.get_changeform_initial_data(request) form = ModelForm(initial=initial) formsets, inline_instances = self._create_formsets( request, form.instance, change=False ) else: form = ModelForm(instance=obj) formsets, inline_instances = self._create_formsets( request, obj, change=True ) if not add and not self.has_change_permission(request, obj): readonly_fields = flatten_fieldsets(fieldsets) else: readonly_fields = self.get_readonly_fields(request, obj) admin_form = helpers.AdminForm( form, list(fieldsets), # Clear prepopulated fields on a view-only form to avoid a crash. self.get_prepopulated_fields(request, obj) if add or self.has_change_permission(request, obj) else {}, readonly_fields, model_admin=self, ) media = self.media + admin_form.media inline_formsets = self.get_inline_formsets( request, formsets, inline_instances, obj ) for inline_formset in inline_formsets: media += inline_formset.media if add: title = _("Add %s") elif self.has_change_permission(request, obj): title = _("Change %s") else: title = _("View %s") context = { **self.admin_site.each_context(request), "title": title % self.opts.verbose_name, "subtitle": str(obj) if obj else None, "adminform": admin_form, "object_id": object_id, "original": obj, "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, "media": media, "inline_admin_formsets": inline_formsets, "errors": helpers.AdminErrorList(form, formsets), "preserved_filters": self.get_preserved_filters(request), } # Hide the "Save" and "Save and continue" buttons if "Save as New" was # previously chosen to prevent the interface from getting confusing. if ( request.method == "POST" and not form_validated and "_saveasnew" in request.POST ): context["show_save"] = False context["show_save_and_continue"] = False # Use the change template instead of the add template. add = False context.update(extra_context or {}) return self.render_change_form( request, context, add=add, change=not add, obj=obj, form_url=form_url ) def add_view(self, request, form_url="", extra_context=None): return self.changeform_view(request, None, form_url, extra_context) def change_view(self, request, object_id, form_url="", extra_context=None): return self.changeform_view(request, object_id, form_url, extra_context) def _get_edited_object_pks(self, request, prefix): """Return POST data values of list_editable primary keys.""" pk_pattern = re.compile( r"{}-\d+-{}$".format(re.escape(prefix), self.opts.pk.name) ) return [value for key, value in request.POST.items() if pk_pattern.match(key)] def _get_list_editable_queryset(self, request, prefix): """ Based on POST data, return a queryset of the objects that were edited via list_editable. """ object_pks = self._get_edited_object_pks(request, prefix) queryset = self.get_queryset(request) validate = queryset.model._meta.pk.to_python try: for pk in object_pks: validate(pk) except ValidationError: # Disable the optimization if the POST data was tampered with. return queryset return queryset.filter(pk__in=object_pks) @csrf_protect_m def changelist_view(self, request, extra_context=None): """ The 'change list' admin view for this model. """ from django.contrib.admin.views.main import ERROR_FLAG app_label = self.opts.app_label if not self.has_view_or_change_permission(request): raise PermissionDenied try: cl = self.get_changelist_instance(request) except IncorrectLookupParameters: # Wacky lookup parameters were given, so redirect to the main # changelist page, without parameters, and pass an 'invalid=1' # parameter via the query string. If wacky parameters were given # and the 'invalid=1' parameter was already in the query string, # something is screwed up with the database, so display an error # page. if ERROR_FLAG in request.GET: return SimpleTemplateResponse( "admin/invalid_setup.html", { "title": _("Database error"), }, ) return HttpResponseRedirect(request.path + "?" + ERROR_FLAG + "=1") # If the request was POSTed, this might be a bulk action or a bulk # edit. Try to look up an action or confirmation first, but if this # isn't an action the POST will fall through to the bulk edit check, # below. action_failed = False selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME) actions = self.get_actions(request) # Actions with no confirmation if ( actions and request.method == "POST" and "index" in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True else: msg = _( "Items must be selected in order to perform " "actions on them. No items have been changed." ) self.message_user(request, msg, messages.WARNING) action_failed = True # Actions with confirmation if ( actions and request.method == "POST" and helpers.ACTION_CHECKBOX_NAME in request.POST and "index" not in request.POST and "_save" not in request.POST ): if selected: response = self.response_action( request, queryset=cl.get_queryset(request) ) if response: return response else: action_failed = True if action_failed: # Redirect back to the changelist page to avoid resubmitting the # form if the user refreshes the browser or uses the "No, take # me back" button on the action confirmation page. return HttpResponseRedirect(request.get_full_path()) # If we're allowing changelist editing, we need to construct a formset # for the changelist given all the fields to be edited. Then we'll # use the formset to validate/process POSTed data. formset = cl.formset = None # Handle POSTed bulk-edit data. if request.method == "POST" and cl.list_editable and "_save" in request.POST: if not self.has_change_permission(request): raise PermissionDenied FormSet = self.get_changelist_formset(request) modified_objects = self._get_list_editable_queryset( request, FormSet.get_default_prefix() ) formset = cl.formset = FormSet( request.POST, request.FILES, queryset=modified_objects ) if formset.is_valid(): changecount = 0 with transaction.atomic(using=router.db_for_write(self.model)): for form in formset.forms: if form.has_changed(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) self.save_related(request, form, formsets=[], change=True) change_msg = self.construct_change_message( request, form, None ) self.log_change(request, obj, change_msg) changecount += 1 if changecount: msg = ngettext( "%(count)s %(name)s was changed successfully.", "%(count)s %(name)s were changed successfully.", changecount, ) % { "count": changecount, "name": model_ngettext(self.opts, changecount), } self.message_user(request, msg, messages.SUCCESS) return HttpResponseRedirect(request.get_full_path()) # Handle GET -- construct a formset for display. elif cl.list_editable and self.has_change_permission(request): FormSet = self.get_changelist_formset(request) formset = cl.formset = FormSet(queryset=cl.result_list) # Build the list of media to be used by the formset. if formset: media = self.media + formset.media else: media = self.media # Build the action form and populate it with available actions. if actions: action_form = self.action_form(auto_id=None) action_form.fields["action"].choices = self.get_action_choices(request) media += action_form.media else: action_form = None selection_note_all = ngettext( "%(total_count)s selected", "All %(total_count)s selected", cl.result_count ) context = { **self.admin_site.each_context(request), "module_name": str(self.opts.verbose_name_plural), "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)}, "selection_note_all": selection_note_all % {"total_count": cl.result_count}, "title": cl.title, "subtitle": None, "is_popup": cl.is_popup, "to_field": cl.to_field, "cl": cl, "media": media, "has_add_permission": self.has_add_permission(request), "opts": cl.opts, "action_form": action_form, "actions_on_top": self.actions_on_top, "actions_on_bottom": self.actions_on_bottom, "actions_selection_counter": self.actions_selection_counter, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_list_template or [ "admin/%s/%s/change_list.html" % (app_label, self.opts.model_name), "admin/%s/change_list.html" % app_label, "admin/change_list.html", ], context, ) def get_deleted_objects(self, objs, request): """ Hook for customizing the delete process for the delete view and the "delete selected" action. """ return get_deleted_objects(objs, request, self.admin_site) @csrf_protect_m def delete_view(self, request, object_id, extra_context=None): with transaction.atomic(using=router.db_for_write(self.model)): return self._delete_view(request, object_id, extra_context) def _delete_view(self, request, object_id, extra_context): "The 'delete' admin view for this model." app_label = self.opts.app_label to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) obj = self.get_object(request, unquote(object_id), to_field) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: return self._get_obj_does_not_exist_redirect(request, self.opts, object_id) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. ( deleted_objects, model_count, perms_needed, protected, ) = self.get_deleted_objects([obj], request) if request.POST and not protected: # The user has confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = str(obj) attr = str(to_field) if to_field else self.opts.pk.attname obj_id = obj.serializable_value(attr) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) return self.response_delete(request, obj_display, obj_id) object_name = str(self.opts.verbose_name) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": object_name} else: title = _("Are you sure?") context = { **self.admin_site.each_context(request), "title": title, "subtitle": None, "object_name": object_name, "object": obj, "deleted_objects": deleted_objects, "model_count": dict(model_count).items(), "perms_lacking": perms_needed, "protected": protected, "opts": self.opts, "app_label": app_label, "preserved_filters": self.get_preserved_filters(request), "is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET, "to_field": to_field, **(extra_context or {}), } return self.render_delete_form(request, context) def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry from django.contrib.admin.views.main import PAGE_VAR # First check if the user can see this history. model = self.model obj = self.get_object(request, unquote(object_id)) if obj is None: return self._get_obj_does_not_exist_redirect( request, model._meta, object_id ) if not self.has_view_or_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. app_label = self.opts.app_label action_list = ( LogEntry.objects.filter( object_id=unquote(object_id), content_type=get_content_type_for_model(model), ) .select_related() .order_by("action_time") ) paginator = self.get_paginator(request, action_list, 100) page_number = request.GET.get(PAGE_VAR, 1) page_obj = paginator.get_page(page_number) page_range = paginator.get_elided_page_range(page_obj.number) context = { **self.admin_site.each_context(request), "title": _("Change history: %s") % obj, "subtitle": None, "action_list": page_obj, "page_range": page_range, "page_var": PAGE_VAR, "pagination_required": paginator.count > 100, "module_name": str(capfirst(self.opts.verbose_name_plural)), "object": obj, "opts": self.opts, "preserved_filters": self.get_preserved_filters(request), **(extra_context or {}), } request.current_app = self.admin_site.name return TemplateResponse( request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, self.opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html", ], context, ) def get_formset_kwargs(self, request, obj, inline, prefix): formset_params = { "instance": obj, "prefix": prefix, "queryset": inline.get_queryset(request), } if request.method == "POST": formset_params.update( { "data": request.POST.copy(), "files": request.FILES, "save_as_new": "_saveasnew" in request.POST, } ) return formset_params def _create_formsets(self, request, obj, change): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = {} get_formsets_args = [request] if change: get_formsets_args.append(obj) for FormSet, inline in self.get_formsets_with_inlines(*get_formsets_args): prefix = FormSet.get_default_prefix() prefixes[prefix] = prefixes.get(prefix, 0) + 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = self.get_formset_kwargs(request, obj, inline, prefix) formset = FormSet(**formset_params) def user_deleted_form(request, obj, formset, index, inline): """Return whether or not the user deleted the form.""" return ( inline.has_delete_permission(request, obj) and "{}-{}-DELETE".format(formset.prefix, index) in request.POST ) # Bypass validation of each view-only inline form (since the form's # data won't be in request.POST), unless the form was deleted. if not inline.has_change_permission(request, obj if change else None): for index, form in enumerate(formset.initial_forms): if user_deleted_form(request, obj, formset, index, inline): continue form._errors = {} form.cleaned_data = form.initial formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances class InlineModelAdmin(BaseModelAdmin): """ Options for inline editing of ``model`` instances. Provide ``fk_name`` to specify the attribute name of the ``ForeignKey`` from ``model`` to its parent. This is required if ``model`` has more than one ``ForeignKey`` to its parent. """ model = None fk_name = None formset = BaseInlineFormSet extra = 3 min_num = None max_num = None template = None verbose_name = None verbose_name_plural = None can_delete = True show_change_link = False checks_class = InlineModelAdminChecks classes = None def __init__(self, parent_model, admin_site): self.admin_site = admin_site self.parent_model = parent_model self.opts = self.model._meta self.has_registered_model = admin_site.is_registered(self.model) super().__init__() if self.verbose_name_plural is None: if self.verbose_name is None: self.verbose_name_plural = self.opts.verbose_name_plural else: self.verbose_name_plural = format_lazy("{}s", self.verbose_name) if self.verbose_name is None: self.verbose_name = self.opts.verbose_name @property def media(self): extra = "" if settings.DEBUG else ".min" js = ["vendor/jquery/jquery%s.js" % extra, "jquery.init.js", "inlines.js"] if self.filter_vertical or self.filter_horizontal: js.extend(["SelectBox.js", "SelectFilter2.js"]) if self.classes and "collapse" in self.classes: js.append("collapse.js") return forms.Media(js=["admin/js/%s" % url for url in js]) def get_extra(self, request, obj=None, **kwargs): """Hook for customizing the number of extra inline forms.""" return self.extra def get_min_num(self, request, obj=None, **kwargs): """Hook for customizing the min number of inline forms.""" return self.min_num def get_max_num(self, request, obj=None, **kwargs): """Hook for customizing the max number of extra inline forms.""" return self.max_num def get_formset(self, request, obj=None, **kwargs): """Return a BaseInlineFormSet class for use in admin add/change views.""" if "fields" in kwargs: fields = kwargs.pop("fields") else: fields = flatten_fieldsets(self.get_fieldsets(request, obj)) excluded = self.get_exclude(request, obj) exclude = [] if excluded is None else list(excluded) exclude.extend(self.get_readonly_fields(request, obj)) if excluded is None and hasattr(self.form, "_meta") and self.form._meta.exclude: # Take the custom ModelForm's Meta.exclude into account only if the # InlineModelAdmin doesn't define its own. exclude.extend(self.form._meta.exclude) # If exclude is an empty list we use None, since that's the actual # default. exclude = exclude or None can_delete = self.can_delete and self.has_delete_permission(request, obj) defaults = { "form": self.form, "formset": self.formset, "fk_name": self.fk_name, "fields": fields, "exclude": exclude, "formfield_callback": partial(self.formfield_for_dbfield, request=request), "extra": self.get_extra(request, obj, **kwargs), "min_num": self.get_min_num(request, obj, **kwargs), "max_num": self.get_max_num(request, obj, **kwargs), "can_delete": can_delete, **kwargs, } base_model_form = defaults["form"] can_change = self.has_change_permission(request, obj) if request else True can_add = self.has_add_permission(request, obj) if request else True class DeleteProtectedModelForm(base_model_form): def hand_clean_DELETE(self): """ We don't validate the 'DELETE' field itself because on templates it's not rendered using the field information, but just using a generic "deletion_field" of the InlineModelAdmin. """ if self.cleaned_data.get(DELETION_FIELD_NAME, False): using = router.db_for_write(self._meta.model) collector = NestedObjects(using=using) if self.instance._state.adding: return collector.collect([self.instance]) if collector.protected: objs = [] for p in collector.protected: objs.append( # Translators: Model verbose name and instance # representation, suitable to be an item in a # list. _("%(class_name)s %(instance)s") % {"class_name": p._meta.verbose_name, "instance": p} ) params = { "class_name": self._meta.model._meta.verbose_name, "instance": self.instance, "related_objects": get_text_list(objs, _("and")), } msg = _( "Deleting %(class_name)s %(instance)s would require " "deleting the following protected related objects: " "%(related_objects)s" ) raise ValidationError( msg, code="deleting_protected", params=params ) def is_valid(self): result = super().is_valid() self.hand_clean_DELETE() return result def has_changed(self): # Protect against unauthorized edits. if not can_change and not self.instance._state.adding: return False if not can_add and self.instance._state.adding: return False return super().has_changed() defaults["form"] = DeleteProtectedModelForm if defaults["fields"] is None and not modelform_defines_fields( defaults["form"] ): defaults["fields"] = forms.ALL_FIELDS return inlineformset_factory(self.parent_model, self.model, **defaults) def _get_form_for_get_fields(self, request, obj=None): return self.get_formset(request, obj, fields=None).form def get_queryset(self, request): queryset = super().get_queryset(request) if not self.has_view_or_change_permission(request): queryset = queryset.none() return queryset def _has_any_perms_for_target_model(self, request, perms): """ This method is called only when the ModelAdmin's model is for an ManyToManyField's implicit through model (if self.opts.auto_created). Return True if the user has any of the given permissions ('add', 'change', etc.) for the model that points to the through model. """ opts = self.opts # Find the target model of an auto-created many-to-many relationship. for field in opts.fields: if field.remote_field and field.remote_field.model != self.parent_model: opts = field.remote_field.model._meta break return any( request.user.has_perm( "%s.%s" % (opts.app_label, get_permission_codename(perm, opts)) ) for perm in perms ) def has_add_permission(self, request, obj): if self.opts.auto_created: # Auto-created intermediate models don't have their own # permissions. The user needs to have the change permission for the # related model in order to be able to do anything with the # intermediate model. return self._has_any_perms_for_target_model(request, ["change"]) return super().has_add_permission(request) def has_change_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_change_permission(request) def has_delete_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). return self._has_any_perms_for_target_model(request, ["change"]) return super().has_delete_permission(request, obj) def has_view_permission(self, request, obj=None): if self.opts.auto_created: # Same comment as has_add_permission(). The 'change' permission # also implies the 'view' permission. return self._has_any_perms_for_target_model(request, ["view", "change"]) return super().has_view_permission(request) class StackedInline(InlineModelAdmin): template = "admin/edit_inline/stacked.html" class TabularInline(InlineModelAdmin): template = "admin/edit_inline/tabular.html"
64383c0866b1e82bf8b2ccc7334dd04f2820b38a76d5fa5d4dcabba11d98e264
from decimal import Decimal from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField from django.contrib.gis.db.models.sql import AreaField, DistanceField from django.contrib.gis.geos import GEOSGeometry from django.core.exceptions import FieldError from django.db import NotSupportedError from django.db.models import ( BinaryField, BooleanField, FloatField, Func, IntegerField, TextField, Transform, Value, ) from django.db.models.functions import Cast from django.utils.functional import cached_property NUMERIC_TYPES = (int, float, Decimal) class GeoFuncMixin: function = None geom_param_pos = (0,) def __init__(self, *expressions, **extra): super().__init__(*expressions, **extra) # Ensure that value expressions are geometric. for pos in self.geom_param_pos: expr = self.source_expressions[pos] if not isinstance(expr, Value): continue try: output_field = expr.output_field except FieldError: output_field = None geom = expr.value if ( not isinstance(geom, GEOSGeometry) or output_field and not isinstance(output_field, GeometryField) ): raise TypeError( "%s function requires a geometric argument in position %d." % (self.name, pos + 1) ) if not geom.srid and not output_field: raise ValueError("SRID is required for all geometries.") if not output_field: self.source_expressions[pos] = Value( geom, output_field=GeometryField(srid=geom.srid) ) @property def name(self): return self.__class__.__name__ @cached_property def geo_field(self): return self.source_expressions[self.geom_param_pos[0]].field def as_sql(self, compiler, connection, function=None, **extra_context): if self.function is None and function is None: function = connection.ops.spatial_function_name(self.name) return super().as_sql(compiler, connection, function=function, **extra_context) def resolve_expression(self, *args, **kwargs): res = super().resolve_expression(*args, **kwargs) if not self.geom_param_pos: return res # Ensure that expressions are geometric. source_fields = res.get_source_fields() for pos in self.geom_param_pos: field = source_fields[pos] if not isinstance(field, GeometryField): raise TypeError( "%s function requires a GeometryField in position %s, got %s." % ( self.name, pos + 1, type(field).__name__, ) ) base_srid = res.geo_field.srid for pos in self.geom_param_pos[1:]: expr = res.source_expressions[pos] expr_srid = expr.output_field.srid if expr_srid != base_srid: # Automatic SRID conversion so objects are comparable. res.source_expressions[pos] = Transform( expr, base_srid ).resolve_expression(*args, **kwargs) return res def _handle_param(self, value, param_name="", check_types=None): if not hasattr(value, "resolve_expression"): if check_types and not isinstance(value, check_types): raise TypeError( "The %s parameter has the wrong type: should be %s." % (param_name, check_types) ) return value class GeoFunc(GeoFuncMixin, Func): pass class GeomOutputGeoFunc(GeoFunc): @cached_property def output_field(self): return GeometryField(srid=self.geo_field.srid) class SQLiteDecimalToFloatMixin: """ By default, Decimal values are converted to str by the SQLite backend, which is not acceptable by the GIS functions expecting numeric values. """ def as_sqlite(self, compiler, connection, **extra_context): copy = self.copy() copy.set_source_expressions( [ Value(float(expr.value)) if hasattr(expr, "value") and isinstance(expr.value, Decimal) else expr for expr in copy.get_source_expressions() ] ) return copy.as_sql(compiler, connection, **extra_context) class OracleToleranceMixin: tolerance = 0.05 def as_oracle(self, compiler, connection, **extra_context): tolerance = Value( self._handle_param( self.extra.get("tolerance", self.tolerance), "tolerance", NUMERIC_TYPES, ) ) clone = self.copy() clone.set_source_expressions([*self.get_source_expressions(), tolerance]) return clone.as_sql(compiler, connection, **extra_context) class Area(OracleToleranceMixin, GeoFunc): arity = 1 @cached_property def output_field(self): return AreaField(self.geo_field) def as_sql(self, compiler, connection, **extra_context): if not connection.features.supports_area_geodetic and self.geo_field.geodetic( connection ): raise NotSupportedError( "Area on geodetic coordinate systems not supported." ) return super().as_sql(compiler, connection, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): extra_context["template"] = "%(function)s(%(expressions)s, %(spheroid)d)" extra_context["spheroid"] = True return self.as_sql(compiler, connection, **extra_context) class Azimuth(GeoFunc): output_field = FloatField() arity = 2 geom_param_pos = (0, 1) class AsGeoJSON(GeoFunc): output_field = TextField() def __init__(self, expression, bbox=False, crs=False, precision=8, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) options = 0 if crs and bbox: options = 3 elif bbox: options = 1 elif crs: options = 2 if options: expressions.append(options) super().__init__(*expressions, **extra) def as_oracle(self, compiler, connection, **extra_context): source_expressions = self.get_source_expressions() clone = self.copy() clone.set_source_expressions(source_expressions[:1]) return super(AsGeoJSON, clone).as_sql(compiler, connection, **extra_context) class AsGML(GeoFunc): geom_param_pos = (1,) output_field = TextField() def __init__(self, expression, version=2, precision=8, **extra): expressions = [version, expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) super().__init__(*expressions, **extra) def as_oracle(self, compiler, connection, **extra_context): source_expressions = self.get_source_expressions() version = source_expressions[0] clone = self.copy() clone.set_source_expressions([source_expressions[1]]) extra_context["function"] = ( "SDO_UTIL.TO_GML311GEOMETRY" if version.value == 3 else "SDO_UTIL.TO_GMLGEOMETRY" ) return super(AsGML, clone).as_sql(compiler, connection, **extra_context) class AsKML(GeoFunc): output_field = TextField() def __init__(self, expression, precision=8, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) super().__init__(*expressions, **extra) class AsSVG(GeoFunc): output_field = TextField() def __init__(self, expression, relative=False, precision=8, **extra): relative = ( relative if hasattr(relative, "resolve_expression") else int(relative) ) expressions = [ expression, relative, self._handle_param(precision, "precision", int), ] super().__init__(*expressions, **extra) class AsWKB(GeoFunc): output_field = BinaryField() arity = 1 class AsWKT(GeoFunc): output_field = TextField() arity = 1 class BoundingCircle(OracleToleranceMixin, GeomOutputGeoFunc): def __init__(self, expression, num_seg=48, **extra): super().__init__(expression, num_seg, **extra) def as_oracle(self, compiler, connection, **extra_context): clone = self.copy() clone.set_source_expressions([self.get_source_expressions()[0]]) return super(BoundingCircle, clone).as_oracle( compiler, connection, **extra_context ) class Centroid(OracleToleranceMixin, GeomOutputGeoFunc): arity = 1 class Difference(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1) class DistanceResultMixin: @cached_property def output_field(self): return DistanceField(self.geo_field) def source_is_geography(self): return self.geo_field.geography and self.geo_field.srid == 4326 class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFunc): geom_param_pos = (0, 1) spheroid = None def __init__(self, expr1, expr2, spheroid=None, **extra): expressions = [expr1, expr2] if spheroid is not None: self.spheroid = self._handle_param(spheroid, "spheroid", bool) super().__init__(*expressions, **extra) def as_postgresql(self, compiler, connection, **extra_context): clone = self.copy() function = None expr2 = clone.source_expressions[1] geography = self.source_is_geography() if expr2.output_field.geography != geography: if isinstance(expr2, Value): expr2.output_field.geography = geography else: clone.source_expressions[1] = Cast( expr2, GeometryField(srid=expr2.output_field.srid, geography=geography), ) if not geography and self.geo_field.geodetic(connection): # Geometry fields with geodetic (lon/lat) coordinates need special # distance functions. if self.spheroid: # DistanceSpheroid is more accurate and resource intensive than # DistanceSphere. function = connection.ops.spatial_function_name("DistanceSpheroid") # Replace boolean param by the real spheroid of the base field clone.source_expressions.append( Value(self.geo_field.spheroid(connection)) ) else: function = connection.ops.spatial_function_name("DistanceSphere") return super(Distance, clone).as_sql( compiler, connection, function=function, **extra_context ) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): # SpatiaLite returns NULL instead of zero on geodetic coordinates extra_context[ "template" ] = "COALESCE(%(function)s(%(expressions)s, %(spheroid)s), 0)" extra_context["spheroid"] = int(bool(self.spheroid)) return super().as_sql(compiler, connection, **extra_context) class Envelope(GeomOutputGeoFunc): arity = 1 class ForcePolygonCW(GeomOutputGeoFunc): arity = 1 class FromWKB(GeoFunc): output_field = GeometryField(srid=0) arity = 1 geom_param_pos = () class FromWKT(GeoFunc): output_field = GeometryField(srid=0) arity = 1 geom_param_pos = () class GeoHash(GeoFunc): output_field = TextField() def __init__(self, expression, precision=None, **extra): expressions = [expression] if precision is not None: expressions.append(self._handle_param(precision, "precision", int)) super().__init__(*expressions, **extra) def as_mysql(self, compiler, connection, **extra_context): clone = self.copy() # If no precision is provided, set it to the maximum. if len(clone.source_expressions) < 2: clone.source_expressions.append(Value(100)) return clone.as_sql(compiler, connection, **extra_context) class GeometryDistance(GeoFunc): output_field = FloatField() arity = 2 function = "" arg_joiner = " <-> " geom_param_pos = (0, 1) class Intersection(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1) @BaseSpatialField.register_lookup class IsEmpty(GeoFuncMixin, Transform): lookup_name = "isempty" output_field = BooleanField() @BaseSpatialField.register_lookup class IsValid(OracleToleranceMixin, GeoFuncMixin, Transform): lookup_name = "isvalid" output_field = BooleanField() def as_oracle(self, compiler, connection, **extra_context): sql, params = super().as_oracle(compiler, connection, **extra_context) return "CASE %s WHEN 'TRUE' THEN 1 ELSE 0 END" % sql, params class Length(DistanceResultMixin, OracleToleranceMixin, GeoFunc): def __init__(self, expr1, spheroid=True, **extra): self.spheroid = spheroid super().__init__(expr1, **extra) def as_sql(self, compiler, connection, **extra_context): if ( self.geo_field.geodetic(connection) and not connection.features.supports_length_geodetic ): raise NotSupportedError( "This backend doesn't support Length on geodetic fields" ) return super().as_sql(compiler, connection, **extra_context) def as_postgresql(self, compiler, connection, **extra_context): clone = self.copy() function = None if self.source_is_geography(): clone.source_expressions.append(Value(self.spheroid)) elif self.geo_field.geodetic(connection): # Geometry fields with geodetic (lon/lat) coordinates need length_spheroid function = connection.ops.spatial_function_name("LengthSpheroid") clone.source_expressions.append(Value(self.geo_field.spheroid(connection))) else: dim = min(f.dim for f in self.get_source_fields() if f) if dim > 2: function = connection.ops.length3d return super(Length, clone).as_sql( compiler, connection, function=function, **extra_context ) def as_sqlite(self, compiler, connection, **extra_context): function = None if self.geo_field.geodetic(connection): function = "GeodesicLength" if self.spheroid else "GreatCircleLength" return super().as_sql(compiler, connection, function=function, **extra_context) class LineLocatePoint(GeoFunc): output_field = FloatField() arity = 2 geom_param_pos = (0, 1) class MakeValid(GeomOutputGeoFunc): pass class MemSize(GeoFunc): output_field = IntegerField() arity = 1 class NumGeometries(GeoFunc): output_field = IntegerField() arity = 1 class NumPoints(GeoFunc): output_field = IntegerField() arity = 1 class Perimeter(DistanceResultMixin, OracleToleranceMixin, GeoFunc): arity = 1 def as_postgresql(self, compiler, connection, **extra_context): function = None if self.geo_field.geodetic(connection) and not self.source_is_geography(): raise NotSupportedError( "ST_Perimeter cannot use a non-projected non-geography field." ) dim = min(f.dim for f in self.get_source_fields()) if dim > 2: function = connection.ops.perimeter3d return super().as_sql(compiler, connection, function=function, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): raise NotSupportedError("Perimeter cannot use a non-projected field.") return super().as_sql(compiler, connection, **extra_context) class PointOnSurface(OracleToleranceMixin, GeomOutputGeoFunc): arity = 1 class Reverse(GeoFunc): arity = 1 class Scale(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc): def __init__(self, expression, x, y, z=0.0, **extra): expressions = [ expression, self._handle_param(x, "x", NUMERIC_TYPES), self._handle_param(y, "y", NUMERIC_TYPES), ] if z != 0.0: expressions.append(self._handle_param(z, "z", NUMERIC_TYPES)) super().__init__(*expressions, **extra) class SnapToGrid(SQLiteDecimalToFloatMixin, GeomOutputGeoFunc): def __init__(self, expression, *args, **extra): nargs = len(args) expressions = [expression] if nargs in (1, 2): expressions.extend( [self._handle_param(arg, "", NUMERIC_TYPES) for arg in args] ) elif nargs == 4: # Reverse origin and size param ordering expressions += [ *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[2:]), *(self._handle_param(arg, "", NUMERIC_TYPES) for arg in args[0:2]), ] else: raise ValueError("Must provide 1, 2, or 4 arguments to `SnapToGrid`.") super().__init__(*expressions, **extra) class SymDifference(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1) class Transform(GeomOutputGeoFunc): def __init__(self, expression, srid, **extra): expressions = [ expression, self._handle_param(srid, "srid", int), ] if "output_field" not in extra: extra["output_field"] = GeometryField(srid=srid) super().__init__(*expressions, **extra) class Translate(Scale): def as_sqlite(self, compiler, connection, **extra_context): clone = self.copy() if len(self.source_expressions) < 4: # Always provide the z parameter for ST_Translate clone.source_expressions.append(Value(0)) return super(Translate, clone).as_sqlite(compiler, connection, **extra_context) class Union(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1)
5bed06aa46f75820983fa2023089c19f782ad9320c559aef293bd64c464a0dc1
""" This module contains the spatial lookup types, and the `get_geo_where_clause` routine for Oracle Spatial. Please note that WKT support is broken on the XE version, and thus this backend will not work on such platforms. Specifically, XE lacks support for an internal JVM, and Java libraries are required to use the WKT constructors. """ import re from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.oracle.operations import DatabaseOperations DEFAULT_TOLERANCE = "0.05" class SDOOperator(SpatialOperator): sql_template = "%(func)s(%(lhs)s, %(rhs)s) = 'TRUE'" class SDODWithin(SpatialOperator): sql_template = "SDO_WITHIN_DISTANCE(%(lhs)s, %(rhs)s, %%s) = 'TRUE'" class SDODisjoint(SpatialOperator): sql_template = ( "SDO_GEOM.RELATE(%%(lhs)s, 'DISJOINT', %%(rhs)s, %s) = 'DISJOINT'" % DEFAULT_TOLERANCE ) class SDORelate(SpatialOperator): sql_template = "SDO_RELATE(%(lhs)s, %(rhs)s, 'mask=%(mask)s') = 'TRUE'" def check_relate_argument(self, arg): masks = ( "TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|" "CONTAINS|COVERS|ANYINTERACT|ON" ) mask_regex = re.compile(r"^(%s)(\+(%s))*$" % (masks, masks), re.I) if not isinstance(arg, str) or not mask_regex.match(arg): raise ValueError('Invalid SDO_RELATE mask: "%s"' % arg) def as_sql(self, connection, lookup, template_params, sql_params): template_params["mask"] = sql_params[-1] return super().as_sql(connection, lookup, template_params, sql_params[:-1]) class OracleOperations(BaseSpatialOperations, DatabaseOperations): name = "oracle" oracle = True disallowed_aggregates = (models.Collect, models.Extent3D, models.MakeLine) Adapter = OracleSpatialAdapter extent = "SDO_AGGR_MBR" unionagg = "SDO_AGGR_UNION" from_text = "SDO_GEOMETRY" function_names = { "Area": "SDO_GEOM.SDO_AREA", "AsGeoJSON": "SDO_UTIL.TO_GEOJSON", "AsWKB": "SDO_UTIL.TO_WKBGEOMETRY", "AsWKT": "SDO_UTIL.TO_WKTGEOMETRY", "BoundingCircle": "SDO_GEOM.SDO_MBC", "Centroid": "SDO_GEOM.SDO_CENTROID", "Difference": "SDO_GEOM.SDO_DIFFERENCE", "Distance": "SDO_GEOM.SDO_DISTANCE", "Envelope": "SDO_GEOM_MBR", "FromWKB": "SDO_UTIL.FROM_WKBGEOMETRY", "FromWKT": "SDO_UTIL.FROM_WKTGEOMETRY", "Intersection": "SDO_GEOM.SDO_INTERSECTION", "IsValid": "SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT", "Length": "SDO_GEOM.SDO_LENGTH", "NumGeometries": "SDO_UTIL.GETNUMELEM", "NumPoints": "SDO_UTIL.GETNUMVERTICES", "Perimeter": "SDO_GEOM.SDO_LENGTH", "PointOnSurface": "SDO_GEOM.SDO_POINTONSURFACE", "Reverse": "SDO_UTIL.REVERSE_LINESTRING", "SymDifference": "SDO_GEOM.SDO_XOR", "Transform": "SDO_CS.TRANSFORM", "Union": "SDO_GEOM.SDO_UNION", } # We want to get SDO Geometries as WKT because it is much easier to # instantiate GEOS proxies from WKT than SDO_GEOMETRY(...) strings. # However, this adversely affects performance (i.e., Java is called # to convert to WKT on every query). If someone wishes to write a # SDO_GEOMETRY(...) parser in Python, let me know =) select = "SDO_UTIL.TO_WKBGEOMETRY(%s)" gis_operators = { "contains": SDOOperator(func="SDO_CONTAINS"), "coveredby": SDOOperator(func="SDO_COVEREDBY"), "covers": SDOOperator(func="SDO_COVERS"), "disjoint": SDODisjoint(), "intersects": SDOOperator( func="SDO_OVERLAPBDYINTERSECT" ), # TODO: Is this really the same as ST_Intersects()? "equals": SDOOperator(func="SDO_EQUAL"), "exact": SDOOperator(func="SDO_EQUAL"), "overlaps": SDOOperator(func="SDO_OVERLAPS"), "same_as": SDOOperator(func="SDO_EQUAL"), # Oracle uses a different syntax, e.g., 'mask=inside+touch' "relate": SDORelate(), "touches": SDOOperator(func="SDO_TOUCH"), "within": SDOOperator(func="SDO_INSIDE"), "dwithin": SDODWithin(), } unsupported_functions = { "AsKML", "AsSVG", "Azimuth", "ForcePolygonCW", "GeoHash", "GeometryDistance", "IsEmpty", "LineLocatePoint", "MakeValid", "MemSize", "Scale", "SnapToGrid", "Translate", } def geo_quote_name(self, name): return super().geo_quote_name(name).upper() def convert_extent(self, clob): if clob: # Generally, Oracle returns a polygon for the extent -- however, # it can return a single point if there's only one Point in the # table. ext_geom = GEOSGeometry(memoryview(clob.read())) gtype = str(ext_geom.geom_type) if gtype == "Polygon": # Construct the 4-tuple from the coordinates in the polygon. shell = ext_geom.shell ll, ur = shell[0][:2], shell[2][:2] elif gtype == "Point": ll = ext_geom.coords[:2] ur = ll else: raise Exception( "Unexpected geometry type returned for extent: %s" % gtype ) xmin, ymin = ll xmax, ymax = ur return (xmin, ymin, xmax, ymax) else: return None def geo_db_type(self, f): """ Return the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it's the same for all geometry types. """ return "MDSYS.SDO_GEOMETRY" def get_distance(self, f, value, lookup_type): """ Return the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value # dwithin lookups on Oracle require a special string parameter # that starts with "distance=". if lookup_type == "dwithin": dist_param = "distance=%s" % dist_param return [dist_param] def get_geom_placeholder(self, f, value, compiler): if value is None: return "NULL" return super().get_geom_placeholder(f, value, compiler) def spatial_aggregate_name(self, agg_name): """ Return the spatial aggregate SQL name. """ agg_name = "unionagg" if agg_name.lower() == "union" else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.oracle.models import OracleGeometryColumns return OracleGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.oracle.models import OracleSpatialRefSys return OracleSpatialRefSys def modify_insert_params(self, placeholder, params): """Drop out insert parameters for NULL placeholder. Needed for Oracle Spatial backend due to #10888. """ if placeholder == "NULL": return [] return super().modify_insert_params(placeholder, params) def get_geometry_converter(self, expression): read = wkb_r().read srid = expression.output_field.srid if srid == -1: srid = None geom_class = expression.output_field.geom_class def converter(value, expression, connection): if value is not None: geom = GEOSGeometryBase(read(memoryview(value.read())), geom_class) if srid: geom.srid = srid return geom return converter def get_area_att_for_field(self, field): return "sq_m"
ec6c207c29b0e117b1ace26e9f13f6b50c15ed3904dc1a10c05a63650c60ddae
from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models.functions import Distance from django.contrib.gis.measure import Area as AreaMeasure from django.contrib.gis.measure import Distance as DistanceMeasure from django.db import NotSupportedError from django.utils.functional import cached_property class BaseSpatialOperations: # Quick booleans for the type of this spatial backend, and # an attribute for the spatial database version tuple (if applicable) postgis = False spatialite = False mariadb = False mysql = False oracle = False spatial_version = None # How the geometry column should be selected. select = "%s" @cached_property def select_extent(self): return self.select # Aggregates disallowed_aggregates = () geom_func_prefix = "" # Mapping between Django function names and backend names, when names do not # match; used in spatial_function_name(). function_names = {} # Set of known unsupported functions of the backend unsupported_functions = { "Area", "AsGeoJSON", "AsGML", "AsKML", "AsSVG", "Azimuth", "BoundingCircle", "Centroid", "Difference", "Distance", "Envelope", "FromWKB", "FromWKT", "GeoHash", "GeometryDistance", "Intersection", "IsEmpty", "IsValid", "Length", "LineLocatePoint", "MakeValid", "MemSize", "NumGeometries", "NumPoints", "Perimeter", "PointOnSurface", "Reverse", "Scale", "SnapToGrid", "SymDifference", "Transform", "Translate", "Union", } # Constructors from_text = False # Default conversion functions for aggregates; will be overridden if implemented # for the spatial backend. def convert_extent(self, box, srid): raise NotImplementedError( "Aggregate extent not implemented for this spatial backend." ) def convert_extent3d(self, box, srid): raise NotImplementedError( "Aggregate 3D extent not implemented for this spatial backend." ) # For quoting column values, rather than columns. def geo_quote_name(self, name): return "'%s'" % name # GeometryField operations def geo_db_type(self, f): """ Return the database column type for the geometry field on the spatial backend. """ raise NotImplementedError( "subclasses of BaseSpatialOperations must provide a geo_db_type() method" ) def get_distance(self, f, value, lookup_type): """ Return the distance parameters for the given geometry field, lookup value, and lookup type. """ raise NotImplementedError( "Distance operations not available on this spatial backend." ) def get_geom_placeholder(self, f, value, compiler): """ Return the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend. """ def transform_value(value, field): return value is not None and value.srid != field.srid if hasattr(value, "as_sql"): return ( "%s(%%s, %s)" % (self.spatial_function_name("Transform"), f.srid) if transform_value(value.output_field, f) else "%s" ) if transform_value(value, f): # Add Transform() to the SQL placeholder. return "%s(%s(%%s,%s), %s)" % ( self.spatial_function_name("Transform"), self.from_text, value.srid, f.srid, ) elif self.connection.features.has_spatialrefsys_table: return "%s(%%s,%s)" % (self.from_text, f.srid) else: # For backwards compatibility on MySQL (#27464). return "%s(%%s)" % self.from_text def check_expression_support(self, expression): if isinstance(expression, self.disallowed_aggregates): raise NotSupportedError( "%s spatial aggregation is not supported by this database backend." % expression.name ) super().check_expression_support(expression) def spatial_aggregate_name(self, agg_name): raise NotImplementedError( "Aggregate support not implemented for this spatial backend." ) def spatial_function_name(self, func_name): if func_name in self.unsupported_functions: raise NotSupportedError( "This backend doesn't support the %s function." % func_name ) return self.function_names.get(func_name, self.geom_func_prefix + func_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): raise NotImplementedError( "Subclasses of BaseSpatialOperations must provide a geometry_columns() " "method." ) def spatial_ref_sys(self): raise NotImplementedError( "subclasses of BaseSpatialOperations must a provide spatial_ref_sys() " "method" ) distance_expr_for_lookup = staticmethod(Distance) def get_db_converters(self, expression): converters = super().get_db_converters(expression) if isinstance(expression.output_field, GeometryField): converters.append(self.get_geometry_converter(expression)) return converters def get_geometry_converter(self, expression): raise NotImplementedError( "Subclasses of BaseSpatialOperations must provide a " "get_geometry_converter() method." ) def get_area_att_for_field(self, field): if field.geodetic(self.connection): if self.connection.features.supports_area_geodetic: return "sq_m" raise NotImplementedError( "Area on geodetic coordinate systems not supported." ) else: units_name = field.units_name(self.connection) if units_name: return AreaMeasure.unit_attname(units_name) def get_distance_att_for_field(self, field): dist_att = None if field.geodetic(self.connection): if self.connection.features.supports_distance_geodetic: dist_att = "m" else: units = field.units_name(self.connection) if units: dist_att = DistanceMeasure.unit_attname(units) return dist_att
fd05fbd73595783d4440f95e482588384164e13859644de9c46f902e4136606e
from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.adapter import WKTAdapter from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.mysql.operations import DatabaseOperations from django.utils.functional import cached_property class MySQLOperations(BaseSpatialOperations, DatabaseOperations): name = "mysql" geom_func_prefix = "ST_" Adapter = WKTAdapter @cached_property def mariadb(self): return self.connection.mysql_is_mariadb @cached_property def mysql(self): return not self.connection.mysql_is_mariadb @cached_property def select(self): return self.geom_func_prefix + "AsBinary(%s)" @cached_property def from_text(self): return self.geom_func_prefix + "GeomFromText" @cached_property def gis_operators(self): operators = { "bbcontains": SpatialOperator( func="MBRContains" ), # For consistency w/PostGIS API "bboverlaps": SpatialOperator(func="MBROverlaps"), # ... "contained": SpatialOperator(func="MBRWithin"), # ... "contains": SpatialOperator(func="ST_Contains"), "crosses": SpatialOperator(func="ST_Crosses"), "disjoint": SpatialOperator(func="ST_Disjoint"), "equals": SpatialOperator(func="ST_Equals"), "exact": SpatialOperator(func="ST_Equals"), "intersects": SpatialOperator(func="ST_Intersects"), "overlaps": SpatialOperator(func="ST_Overlaps"), "same_as": SpatialOperator(func="ST_Equals"), "touches": SpatialOperator(func="ST_Touches"), "within": SpatialOperator(func="ST_Within"), } if self.connection.mysql_is_mariadb: operators["relate"] = SpatialOperator(func="ST_Relate") return operators disallowed_aggregates = ( models.Collect, models.Extent, models.Extent3D, models.MakeLine, models.Union, ) function_names = { "FromWKB": "ST_GeomFromWKB", "FromWKT": "ST_GeomFromText", } @cached_property def unsupported_functions(self): unsupported = { "AsGML", "AsKML", "AsSVG", "Azimuth", "BoundingCircle", "ForcePolygonCW", "GeometryDistance", "IsEmpty", "LineLocatePoint", "MakeValid", "MemSize", "Perimeter", "PointOnSurface", "Reverse", "Scale", "SnapToGrid", "Transform", "Translate", } if self.connection.mysql_is_mariadb: unsupported.remove("PointOnSurface") unsupported.update({"GeoHash", "IsValid"}) return unsupported def geo_db_type(self, f): return f.geom_type def get_distance(self, f, value, lookup_type): value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError( "Only numeric values of degree units are allowed on " "geodetic distance queries." ) dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value return [dist_param] def get_geometry_converter(self, expression): read = wkb_r().read srid = expression.output_field.srid if srid == -1: srid = None geom_class = expression.output_field.geom_class def converter(value, expression, connection): if value is not None: geom = GEOSGeometryBase(read(memoryview(value)), geom_class) if srid: geom.srid = srid return geom return converter
c382661c6e7a0a948f285c713864f5b458cf00245c86bdcd12d0e76acc5091b6
""" Tests for django.core.servers. """ import errno import os import socket import threading import unittest from http.client import HTTPConnection from urllib.error import HTTPError from urllib.parse import urlencode from urllib.request import urlopen from django.conf import settings from django.core.servers.basehttp import ThreadedWSGIServer, WSGIServer from django.db import DEFAULT_DB_ALIAS, connection, connections from django.test import LiveServerTestCase, override_settings from django.test.testcases import LiveServerThread, QuietWSGIRequestHandler from .models import Person TEST_ROOT = os.path.dirname(__file__) TEST_SETTINGS = { "MEDIA_URL": "media/", "MEDIA_ROOT": os.path.join(TEST_ROOT, "media"), "STATIC_URL": "static/", "STATIC_ROOT": os.path.join(TEST_ROOT, "static"), } @override_settings(ROOT_URLCONF="servers.urls", **TEST_SETTINGS) class LiveServerBase(LiveServerTestCase): available_apps = [ "servers", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", ] fixtures = ["testdata.json"] def urlopen(self, url): return urlopen(self.live_server_url + url) class CloseConnectionTestServer(ThreadedWSGIServer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This event is set right after the first time a request closes its # database connections. self._connections_closed = threading.Event() def _close_connections(self): super()._close_connections() self._connections_closed.set() class CloseConnectionTestLiveServerThread(LiveServerThread): server_class = CloseConnectionTestServer def _create_server(self, connections_override=None): return super()._create_server(connections_override=self.connections_override) class LiveServerTestCloseConnectionTest(LiveServerBase): server_thread_class = CloseConnectionTestLiveServerThread @classmethod def _make_connections_override(cls): conn = connections[DEFAULT_DB_ALIAS] cls.conn = conn cls.old_conn_max_age = conn.settings_dict["CONN_MAX_AGE"] # Set the connection's CONN_MAX_AGE to None to simulate the # CONN_MAX_AGE setting being set to None on the server. This prevents # Django from closing the connection and allows testing that # ThreadedWSGIServer closes connections. conn.settings_dict["CONN_MAX_AGE"] = None # Pass a database connection through to the server to check it is being # closed by ThreadedWSGIServer. return {DEFAULT_DB_ALIAS: conn} @classmethod def tearDownConnectionTest(cls): cls.conn.settings_dict["CONN_MAX_AGE"] = cls.old_conn_max_age @classmethod def tearDownClass(cls): cls.tearDownConnectionTest() super().tearDownClass() def test_closes_connections(self): # The server's request thread sets this event after closing # its database connections. closed_event = self.server_thread.httpd._connections_closed conn = self.conn # Open a connection to the database. conn.connect() self.assertIsNotNone(conn.connection) with self.urlopen("/model_view/") as f: # The server can access the database. self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"]) # Wait for the server's request thread to close the connection. # A timeout of 0.1 seconds should be more than enough. If the wait # times out, the assertion after should fail. closed_event.wait(timeout=0.1) self.assertIsNone(conn.connection) @unittest.skipUnless(connection.vendor == "sqlite", "SQLite specific test.") class LiveServerInMemoryDatabaseLockTest(LiveServerBase): def test_in_memory_database_lock(self): """ With a threaded LiveServer and an in-memory database, an error can occur when 2 requests reach the server and try to lock the database at the same time, if the requests do not share the same database connection. """ conn = self.server_thread.connections_override[DEFAULT_DB_ALIAS] # Open a connection to the database. conn.connect() # Create a transaction to lock the database. cursor = conn.cursor() cursor.execute("BEGIN IMMEDIATE TRANSACTION") try: with self.urlopen("/create_model_instance/") as f: self.assertEqual(f.status, 200) except HTTPError: self.fail("Unexpected error due to a database lock.") finally: # Release the transaction. cursor.execute("ROLLBACK") class FailingLiveServerThread(LiveServerThread): def _create_server(self, connections_override=None): raise RuntimeError("Error creating server.") class LiveServerTestCaseSetupTest(LiveServerBase): server_thread_class = FailingLiveServerThread @classmethod def check_allowed_hosts(cls, expected): if settings.ALLOWED_HOSTS != expected: raise RuntimeError(f"{settings.ALLOWED_HOSTS} != {expected}") @classmethod def setUpClass(cls): cls.check_allowed_hosts(["testserver"]) try: super().setUpClass() except RuntimeError: # LiveServerTestCase's change to ALLOWED_HOSTS should be reverted. cls.doClassCleanups() cls.check_allowed_hosts(["testserver"]) else: raise RuntimeError("Server did not fail.") cls.set_up_called = True def test_set_up_class(self): self.assertIs(self.set_up_called, True) class LiveServerAddress(LiveServerBase): @classmethod def setUpClass(cls): super().setUpClass() # put it in a list to prevent descriptor lookups in test cls.live_server_url_test = [cls.live_server_url] def test_live_server_url_is_class_property(self): self.assertIsInstance(self.live_server_url_test[0], str) self.assertEqual(self.live_server_url_test[0], self.live_server_url) class LiveServerSingleThread(LiveServerThread): def _create_server(self, connections_override=None): return WSGIServer( (self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False ) class SingleThreadLiveServerTestCase(LiveServerTestCase): server_thread_class = LiveServerSingleThread class LiveServerViews(LiveServerBase): def test_protocol(self): """Launched server serves with HTTP 1.1.""" with self.urlopen("/example_view/") as f: self.assertEqual(f.version, 11) def test_closes_connection_without_content_length(self): """ An HTTP 1.1 server is supposed to support keep-alive. Since our development server is rather simple we support it only in cases where we can detect a content length from the response. This should be doable for all simple views and streaming responses where an iterable with length of one is passed. The latter follows as result of `set_content_length` from https://github.com/python/cpython/blob/main/Lib/wsgiref/handlers.py. If we cannot detect a content length we explicitly set the `Connection` header to `close` to notify the client that we do not actually support it. """ conn = HTTPConnection( LiveServerViews.server_thread.host, LiveServerViews.server_thread.port, timeout=1, ) try: conn.request( "GET", "/streaming_example_view/", headers={"Connection": "keep-alive"} ) response = conn.getresponse() self.assertTrue(response.will_close) self.assertEqual(response.read(), b"Iamastream") self.assertEqual(response.status, 200) self.assertEqual(response.getheader("Connection"), "close") conn.request( "GET", "/streaming_example_view/", headers={"Connection": "close"} ) response = conn.getresponse() self.assertTrue(response.will_close) self.assertEqual(response.read(), b"Iamastream") self.assertEqual(response.status, 200) self.assertEqual(response.getheader("Connection"), "close") finally: conn.close() def test_keep_alive_on_connection_with_content_length(self): """ See `test_closes_connection_without_content_length` for details. This is a follow up test, which ensure that we do not close the connection if not needed, hence allowing us to take advantage of keep-alive. """ conn = HTTPConnection( LiveServerViews.server_thread.host, LiveServerViews.server_thread.port ) try: conn.request("GET", "/example_view/", headers={"Connection": "keep-alive"}) response = conn.getresponse() self.assertFalse(response.will_close) self.assertEqual(response.read(), b"example view") self.assertEqual(response.status, 200) self.assertIsNone(response.getheader("Connection")) conn.request("GET", "/example_view/", headers={"Connection": "close"}) response = conn.getresponse() self.assertFalse(response.will_close) self.assertEqual(response.read(), b"example view") self.assertEqual(response.status, 200) self.assertIsNone(response.getheader("Connection")) finally: conn.close() def test_keep_alive_connection_clears_previous_request_data(self): conn = HTTPConnection( LiveServerViews.server_thread.host, LiveServerViews.server_thread.port ) try: conn.request( "POST", "/method_view/", b"{}", headers={"Connection": "keep-alive"} ) response = conn.getresponse() self.assertFalse(response.will_close) self.assertEqual(response.status, 200) self.assertEqual(response.read(), b"POST") conn.request( "POST", "/method_view/", b"{}", headers={"Connection": "close"} ) response = conn.getresponse() self.assertFalse(response.will_close) self.assertEqual(response.status, 200) self.assertEqual(response.read(), b"POST") finally: conn.close() def test_404(self): with self.assertRaises(HTTPError) as err: self.urlopen("/") err.exception.close() self.assertEqual(err.exception.code, 404, "Expected 404 response") def test_view(self): with self.urlopen("/example_view/") as f: self.assertEqual(f.read(), b"example view") def test_static_files(self): with self.urlopen("/static/example_static_file.txt") as f: self.assertEqual(f.read().rstrip(b"\r\n"), b"example static file") def test_no_collectstatic_emulation(self): """ LiveServerTestCase reports a 404 status code when HTTP client tries to access a static file that isn't explicitly put under STATIC_ROOT. """ with self.assertRaises(HTTPError) as err: self.urlopen("/static/another_app/another_app_static_file.txt") err.exception.close() self.assertEqual(err.exception.code, 404, "Expected 404 response") def test_media_files(self): with self.urlopen("/media/example_media_file.txt") as f: self.assertEqual(f.read().rstrip(b"\r\n"), b"example media file") def test_environ(self): with self.urlopen("/environ_view/?%s" % urlencode({"q": "тест"})) as f: self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read()) @override_settings(ROOT_URLCONF="servers.urls") class SingleThreadLiveServerViews(SingleThreadLiveServerTestCase): available_apps = ["servers"] def test_closes_connection_with_content_length(self): """ Contrast to LiveServerViews.test_keep_alive_on_connection_with_content_length(). Persistent connections require threading server. """ conn = HTTPConnection( SingleThreadLiveServerViews.server_thread.host, SingleThreadLiveServerViews.server_thread.port, timeout=1, ) try: conn.request("GET", "/example_view/", headers={"Connection": "keep-alive"}) response = conn.getresponse() self.assertTrue(response.will_close) self.assertEqual(response.read(), b"example view") self.assertEqual(response.status, 200) self.assertEqual(response.getheader("Connection"), "close") finally: conn.close() class LiveServerDatabase(LiveServerBase): def test_fixtures_loaded(self): """ Fixtures are properly loaded and visible to the live server thread. """ with self.urlopen("/model_view/") as f: self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"]) def test_database_writes(self): """ Data written to the database by a view can be read. """ with self.urlopen("/create_model_instance/"): pass self.assertQuerySetEqual( Person.objects.order_by("pk"), ["jane", "robert", "emily"], lambda b: b.name, ) class LiveServerPort(LiveServerBase): def test_port_bind(self): """ Each LiveServerTestCase binds to a unique port or fails to start a server thread when run concurrently (#26011). """ TestCase = type("TestCase", (LiveServerBase,), {}) try: TestCase._start_server_thread() except OSError as e: if e.errno == errno.EADDRINUSE: # We're out of ports, LiveServerTestCase correctly fails with # an OSError. return # Unexpected error. raise try: self.assertNotEqual( self.live_server_url, TestCase.live_server_url, f"Acquired duplicate server addresses for server threads: " f"{self.live_server_url}", ) finally: TestCase.doClassCleanups() def test_specified_port_bind(self): """LiveServerTestCase.port customizes the server's port.""" TestCase = type("TestCase", (LiveServerBase,), {}) # Find an open port and tell TestCase to use it. s = socket.socket() s.bind(("", 0)) TestCase.port = s.getsockname()[1] s.close() TestCase._start_server_thread() try: self.assertEqual( TestCase.port, TestCase.server_thread.port, f"Did not use specified port for LiveServerTestCase thread: " f"{TestCase.port}", ) finally: TestCase.doClassCleanups() class LiveServerThreadedTests(LiveServerBase): """If LiveServerTestCase isn't threaded, these tests will hang.""" def test_view_calls_subview(self): url = "/subview_calling_view/?%s" % urlencode({"url": self.live_server_url}) with self.urlopen(url) as f: self.assertEqual(f.read(), b"subview calling view: subview") def test_check_model_instance_from_subview(self): url = "/check_model_instance_from_subview/?%s" % urlencode( { "url": self.live_server_url, } ) with self.urlopen(url) as f: self.assertIn(b"emily", f.read())
a798ec454995a3402f07a58e9cf75b34e4b7d290dd5eff965149720e95ba2d45
import os import sys import unittest from types import ModuleType, SimpleNamespace from unittest import mock from django.conf import ENVIRONMENT_VARIABLE, LazySettings, Settings, settings from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, modify_settings, override_settings, signals, ) from django.test.utils import requires_tz_support from django.urls import clear_script_prefix, set_script_prefix @modify_settings(ITEMS={"prepend": ["b"], "append": ["d"], "remove": ["a", "e"]}) @override_settings( ITEMS=["a", "c", "e"], ITEMS_OUTER=[1, 2, 3], TEST="override", TEST_OUTER="outer" ) class FullyDecoratedTranTestCase(TransactionTestCase): available_apps = [] def test_override(self): self.assertEqual(settings.ITEMS, ["b", "c", "d"]) self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3]) self.assertEqual(settings.TEST, "override") self.assertEqual(settings.TEST_OUTER, "outer") @modify_settings( ITEMS={ "append": ["e", "f"], "prepend": ["a"], "remove": ["d", "c"], } ) def test_method_list_override(self): self.assertEqual(settings.ITEMS, ["a", "b", "e", "f"]) self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3]) @modify_settings( ITEMS={ "append": ["b"], "prepend": ["d"], "remove": ["a", "c", "e"], } ) def test_method_list_override_no_ops(self): self.assertEqual(settings.ITEMS, ["b", "d"]) @modify_settings( ITEMS={ "append": "e", "prepend": "a", "remove": "c", } ) def test_method_list_override_strings(self): self.assertEqual(settings.ITEMS, ["a", "b", "d", "e"]) @modify_settings(ITEMS={"remove": ["b", "d"]}) @modify_settings(ITEMS={"append": ["b"], "prepend": ["d"]}) def test_method_list_override_nested_order(self): self.assertEqual(settings.ITEMS, ["d", "c", "b"]) @override_settings(TEST="override2") def test_method_override(self): self.assertEqual(settings.TEST, "override2") self.assertEqual(settings.TEST_OUTER, "outer") def test_decorated_testcase_name(self): self.assertEqual( FullyDecoratedTranTestCase.__name__, "FullyDecoratedTranTestCase" ) def test_decorated_testcase_module(self): self.assertEqual(FullyDecoratedTranTestCase.__module__, __name__) @modify_settings(ITEMS={"prepend": ["b"], "append": ["d"], "remove": ["a", "e"]}) @override_settings(ITEMS=["a", "c", "e"], TEST="override") class FullyDecoratedTestCase(TestCase): def test_override(self): self.assertEqual(settings.ITEMS, ["b", "c", "d"]) self.assertEqual(settings.TEST, "override") @modify_settings( ITEMS={ "append": "e", "prepend": "a", "remove": "c", } ) @override_settings(TEST="override2") def test_method_override(self): self.assertEqual(settings.ITEMS, ["a", "b", "d", "e"]) self.assertEqual(settings.TEST, "override2") class ClassDecoratedTestCaseSuper(TestCase): """ Dummy class for testing max recursion error in child class call to super(). Refs #17011. """ def test_max_recursion_error(self): pass @override_settings(TEST="override") class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): super().setUpClass() cls.foo = getattr(settings, "TEST", "BUG") def test_override(self): self.assertEqual(settings.TEST, "override") def test_setupclass_override(self): """Settings are overridden within setUpClass (#21281).""" self.assertEqual(self.foo, "override") @override_settings(TEST="override2") def test_method_override(self): self.assertEqual(settings.TEST, "override2") def test_max_recursion_error(self): """ Overriding a method on a super class and then calling that method on the super class should not trigger infinite recursion. See #17011. """ super().test_max_recursion_error() @modify_settings(ITEMS={"append": "mother"}) @override_settings(ITEMS=["father"], TEST="override-parent") class ParentDecoratedTestCase(TestCase): pass @modify_settings(ITEMS={"append": ["child"]}) @override_settings(TEST="override-child") class ChildDecoratedTestCase(ParentDecoratedTestCase): def test_override_settings_inheritance(self): self.assertEqual(settings.ITEMS, ["father", "mother", "child"]) self.assertEqual(settings.TEST, "override-child") class SettingsTests(SimpleTestCase): def setUp(self): self.testvalue = None signals.setting_changed.connect(self.signal_callback) def tearDown(self): signals.setting_changed.disconnect(self.signal_callback) def signal_callback(self, sender, setting, value, **kwargs): if setting == "TEST": self.testvalue = value def test_override(self): settings.TEST = "test" self.assertEqual("test", settings.TEST) with self.settings(TEST="override"): self.assertEqual("override", settings.TEST) self.assertEqual("test", settings.TEST) del settings.TEST def test_override_change(self): settings.TEST = "test" self.assertEqual("test", settings.TEST) with self.settings(TEST="override"): self.assertEqual("override", settings.TEST) settings.TEST = "test2" self.assertEqual("test", settings.TEST) del settings.TEST def test_override_doesnt_leak(self): with self.assertRaises(AttributeError): getattr(settings, "TEST") with self.settings(TEST="override"): self.assertEqual("override", settings.TEST) settings.TEST = "test" with self.assertRaises(AttributeError): getattr(settings, "TEST") @override_settings(TEST="override") def test_decorator(self): self.assertEqual("override", settings.TEST) def test_context_manager(self): with self.assertRaises(AttributeError): getattr(settings, "TEST") override = override_settings(TEST="override") with self.assertRaises(AttributeError): getattr(settings, "TEST") override.enable() self.assertEqual("override", settings.TEST) override.disable() with self.assertRaises(AttributeError): getattr(settings, "TEST") def test_class_decorator(self): # SimpleTestCase can be decorated by override_settings, but not ut.TestCase class SimpleTestCaseSubclass(SimpleTestCase): pass class UnittestTestCaseSubclass(unittest.TestCase): pass decorated = override_settings(TEST="override")(SimpleTestCaseSubclass) self.assertIsInstance(decorated, type) self.assertTrue(issubclass(decorated, SimpleTestCase)) with self.assertRaisesMessage( Exception, "Only subclasses of Django SimpleTestCase" ): decorated = override_settings(TEST="override")(UnittestTestCaseSubclass) def test_signal_callback_context_manager(self): with self.assertRaises(AttributeError): getattr(settings, "TEST") with self.settings(TEST="override"): self.assertEqual(self.testvalue, "override") self.assertIsNone(self.testvalue) @override_settings(TEST="override") def test_signal_callback_decorator(self): self.assertEqual(self.testvalue, "override") # # Regression tests for #10130: deleting settings. # def test_settings_delete(self): settings.TEST = "test" self.assertEqual("test", settings.TEST) del settings.TEST msg = "'Settings' object has no attribute 'TEST'" with self.assertRaisesMessage(AttributeError, msg): getattr(settings, "TEST") def test_settings_delete_wrapped(self): with self.assertRaisesMessage(TypeError, "can't delete _wrapped."): delattr(settings, "_wrapped") def test_override_settings_delete(self): """ Allow deletion of a setting in an overridden settings set (#18824) """ previous_i18n = settings.USE_I18N previous_tz = settings.USE_TZ with self.settings(USE_I18N=False): del settings.USE_I18N with self.assertRaises(AttributeError): getattr(settings, "USE_I18N") # Should also work for a non-overridden setting del settings.USE_TZ with self.assertRaises(AttributeError): getattr(settings, "USE_TZ") self.assertNotIn("USE_I18N", dir(settings)) self.assertNotIn("USE_TZ", dir(settings)) self.assertEqual(settings.USE_I18N, previous_i18n) self.assertEqual(settings.USE_TZ, previous_tz) def test_override_settings_nested(self): """ override_settings uses the actual _wrapped attribute at runtime, not when it was instantiated. """ with self.assertRaises(AttributeError): getattr(settings, "TEST") with self.assertRaises(AttributeError): getattr(settings, "TEST2") inner = override_settings(TEST2="override") with override_settings(TEST="override"): self.assertEqual("override", settings.TEST) with inner: self.assertEqual("override", settings.TEST) self.assertEqual("override", settings.TEST2) # inner's __exit__ should have restored the settings of the outer # context manager, not those when the class was instantiated self.assertEqual("override", settings.TEST) with self.assertRaises(AttributeError): getattr(settings, "TEST2") with self.assertRaises(AttributeError): getattr(settings, "TEST") with self.assertRaises(AttributeError): getattr(settings, "TEST2") @override_settings(SECRET_KEY="") def test_no_secret_key(self): msg = "The SECRET_KEY setting must not be empty." with self.assertRaisesMessage(ImproperlyConfigured, msg): settings.SECRET_KEY def test_no_settings_module(self): msg = ( "Requested setting%s, but settings are not configured. You " "must either define the environment variable DJANGO_SETTINGS_MODULE " "or call settings.configure() before accessing settings." ) orig_settings = os.environ[ENVIRONMENT_VARIABLE] os.environ[ENVIRONMENT_VARIABLE] = "" try: with self.assertRaisesMessage(ImproperlyConfigured, msg % "s"): settings._setup() with self.assertRaisesMessage(ImproperlyConfigured, msg % " TEST"): settings._setup("TEST") finally: os.environ[ENVIRONMENT_VARIABLE] = orig_settings def test_already_configured(self): with self.assertRaisesMessage(RuntimeError, "Settings already configured."): settings.configure() def test_nonupper_settings_prohibited_in_configure(self): s = LazySettings() with self.assertRaisesMessage(TypeError, "Setting 'foo' must be uppercase."): s.configure(foo="bar") def test_nonupper_settings_ignored_in_default_settings(self): s = LazySettings() s.configure(SimpleNamespace(foo="bar")) with self.assertRaises(AttributeError): getattr(s, "foo") @requires_tz_support @mock.patch("django.conf.global_settings.TIME_ZONE", "test") def test_incorrect_timezone(self): with self.assertRaisesMessage(ValueError, "Incorrect timezone setting: test"): settings._setup() class TestComplexSettingOverride(SimpleTestCase): def setUp(self): self.old_warn_override_settings = signals.COMPLEX_OVERRIDE_SETTINGS.copy() signals.COMPLEX_OVERRIDE_SETTINGS.add("TEST_WARN") def tearDown(self): signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings self.assertNotIn("TEST_WARN", signals.COMPLEX_OVERRIDE_SETTINGS) def test_complex_override_warning(self): """Regression test for #19031""" msg = "Overriding setting TEST_WARN can lead to unexpected behavior." with self.assertWarnsMessage(UserWarning, msg) as cm: with override_settings(TEST_WARN="override"): self.assertEqual(settings.TEST_WARN, "override") self.assertEqual(cm.filename, __file__) class SecureProxySslHeaderTest(SimpleTestCase): @override_settings(SECURE_PROXY_SSL_HEADER=None) def test_none(self): req = HttpRequest() self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_set_without_xheader(self): req = HttpRequest() self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_set_with_xheader_wrong(self): req = HttpRequest() req.META["HTTP_X_FORWARDED_PROTO"] = "wrongvalue" self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_set_with_xheader_right(self): req = HttpRequest() req.META["HTTP_X_FORWARDED_PROTO"] = "https" self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_set_with_xheader_leftmost_right(self): req = HttpRequest() req.META["HTTP_X_FORWARDED_PROTO"] = "https, http" self.assertIs(req.is_secure(), True) req.META["HTTP_X_FORWARDED_PROTO"] = "https , http" self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_set_with_xheader_leftmost_not_secure(self): req = HttpRequest() req.META["HTTP_X_FORWARDED_PROTO"] = "http, https" self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_set_with_xheader_multiple_not_secure(self): req = HttpRequest() req.META["HTTP_X_FORWARDED_PROTO"] = "http ,wrongvalue,http,http" self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https")) def test_xheader_preferred_to_underlying_request(self): class ProxyRequest(HttpRequest): def _get_scheme(self): """Proxy always connecting via HTTPS""" return "https" # Client connects via HTTP. req = ProxyRequest() req.META["HTTP_X_FORWARDED_PROTO"] = "http" self.assertIs(req.is_secure(), False) class IsOverriddenTest(SimpleTestCase): def test_configure(self): s = LazySettings() s.configure(SECRET_KEY="foo") self.assertTrue(s.is_overridden("SECRET_KEY")) def test_module(self): settings_module = ModuleType("fake_settings_module") settings_module.SECRET_KEY = "foo" settings_module.USE_TZ = False sys.modules["fake_settings_module"] = settings_module try: s = Settings("fake_settings_module") self.assertTrue(s.is_overridden("SECRET_KEY")) self.assertFalse(s.is_overridden("ALLOWED_HOSTS")) finally: del sys.modules["fake_settings_module"] def test_override(self): self.assertFalse(settings.is_overridden("ALLOWED_HOSTS")) with override_settings(ALLOWED_HOSTS=[]): self.assertTrue(settings.is_overridden("ALLOWED_HOSTS")) def test_unevaluated_lazysettings_repr(self): lazy_settings = LazySettings() expected = "<LazySettings [Unevaluated]>" self.assertEqual(repr(lazy_settings), expected) def test_evaluated_lazysettings_repr(self): lazy_settings = LazySettings() module = os.environ.get(ENVIRONMENT_VARIABLE) expected = '<LazySettings "%s">' % module # Force evaluation of the lazy object. lazy_settings.APPEND_SLASH self.assertEqual(repr(lazy_settings), expected) def test_usersettingsholder_repr(self): lazy_settings = LazySettings() lazy_settings.configure(APPEND_SLASH=False) expected = "<UserSettingsHolder>" self.assertEqual(repr(lazy_settings._wrapped), expected) def test_settings_repr(self): module = os.environ.get(ENVIRONMENT_VARIABLE) lazy_settings = Settings(module) expected = '<Settings "%s">' % module self.assertEqual(repr(lazy_settings), expected) class TestListSettings(SimpleTestCase): """ Make sure settings that should be lists or tuples throw ImproperlyConfigured if they are set to a string instead of a list or tuple. """ list_or_tuple_settings = ( "ALLOWED_HOSTS", "INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS", "SECRET_KEY_FALLBACKS", ) def test_tuple_settings(self): settings_module = ModuleType("fake_settings_module") settings_module.SECRET_KEY = "foo" msg = "The %s setting must be a list or a tuple." for setting in self.list_or_tuple_settings: setattr(settings_module, setting, ("non_list_or_tuple_value")) sys.modules["fake_settings_module"] = settings_module try: with self.assertRaisesMessage(ImproperlyConfigured, msg % setting): Settings("fake_settings_module") finally: del sys.modules["fake_settings_module"] delattr(settings_module, setting) class SettingChangeEnterException(Exception): pass class SettingChangeExitException(Exception): pass class OverrideSettingsIsolationOnExceptionTests(SimpleTestCase): """ The override_settings context manager restore settings if one of the receivers of "setting_changed" signal fails. Check the three cases of receiver failure detailed in receiver(). In each case, ALL receivers are called when exiting the context manager. """ def setUp(self): signals.setting_changed.connect(self.receiver) self.addCleanup(signals.setting_changed.disconnect, self.receiver) # Create a spy that's connected to the `setting_changed` signal and # executed AFTER `self.receiver`. self.spy_receiver = mock.Mock() signals.setting_changed.connect(self.spy_receiver) self.addCleanup(signals.setting_changed.disconnect, self.spy_receiver) def receiver(self, **kwargs): """ A receiver that fails while certain settings are being changed. - SETTING_BOTH raises an error while receiving the signal on both entering and exiting the context manager. - SETTING_ENTER raises an error only on enter. - SETTING_EXIT raises an error only on exit. """ setting = kwargs["setting"] enter = kwargs["enter"] if setting in ("SETTING_BOTH", "SETTING_ENTER") and enter: raise SettingChangeEnterException if setting in ("SETTING_BOTH", "SETTING_EXIT") and not enter: raise SettingChangeExitException def check_settings(self): """Assert that settings for these tests aren't present.""" self.assertFalse(hasattr(settings, "SETTING_BOTH")) self.assertFalse(hasattr(settings, "SETTING_ENTER")) self.assertFalse(hasattr(settings, "SETTING_EXIT")) self.assertFalse(hasattr(settings, "SETTING_PASS")) def check_spy_receiver_exit_calls(self, call_count): """ Assert that `self.spy_receiver` was called exactly `call_count` times with the ``enter=False`` keyword argument. """ kwargs_with_exit = [ kwargs for args, kwargs in self.spy_receiver.call_args_list if ("enter", False) in kwargs.items() ] self.assertEqual(len(kwargs_with_exit), call_count) def test_override_settings_both(self): """Receiver fails on both enter and exit.""" with self.assertRaises(SettingChangeEnterException): with override_settings(SETTING_PASS="BOTH", SETTING_BOTH="BOTH"): pass self.check_settings() # Two settings were touched, so expect two calls of `spy_receiver`. self.check_spy_receiver_exit_calls(call_count=2) def test_override_settings_enter(self): """Receiver fails on enter only.""" with self.assertRaises(SettingChangeEnterException): with override_settings(SETTING_PASS="ENTER", SETTING_ENTER="ENTER"): pass self.check_settings() # Two settings were touched, so expect two calls of `spy_receiver`. self.check_spy_receiver_exit_calls(call_count=2) def test_override_settings_exit(self): """Receiver fails on exit only.""" with self.assertRaises(SettingChangeExitException): with override_settings(SETTING_PASS="EXIT", SETTING_EXIT="EXIT"): pass self.check_settings() # Two settings were touched, so expect two calls of `spy_receiver`. self.check_spy_receiver_exit_calls(call_count=2) def test_override_settings_reusable_on_enter(self): """ Error is raised correctly when reusing the same override_settings instance. """ @override_settings(SETTING_ENTER="ENTER") def decorated_function(): pass with self.assertRaises(SettingChangeEnterException): decorated_function() signals.setting_changed.disconnect(self.receiver) # This call shouldn't raise any errors. decorated_function() class MediaURLStaticURLPrefixTest(SimpleTestCase): def set_script_name(self, val): clear_script_prefix() if val is not None: set_script_prefix(val) def test_not_prefixed(self): # Don't add SCRIPT_NAME prefix to absolute paths, URLs, or None. tests = ( "/path/", "http://myhost.com/path/", "http://myhost/path/", "https://myhost/path/", None, ) for setting in ("MEDIA_URL", "STATIC_URL"): for path in tests: new_settings = {setting: path} with self.settings(**new_settings): for script_name in ["/somesubpath", "/somesubpath/", "/", "", None]: with self.subTest(script_name=script_name, **new_settings): try: self.set_script_name(script_name) self.assertEqual(getattr(settings, setting), path) finally: clear_script_prefix() def test_add_script_name_prefix(self): tests = ( # Relative paths. ("/somesubpath", "path/", "/somesubpath/path/"), ("/somesubpath/", "path/", "/somesubpath/path/"), ("/", "path/", "/path/"), # Invalid URLs. ( "/somesubpath/", "htp://myhost.com/path/", "/somesubpath/htp://myhost.com/path/", ), # Blank settings. ("/somesubpath/", "", "/somesubpath/"), ) for setting in ("MEDIA_URL", "STATIC_URL"): for script_name, path, expected_path in tests: new_settings = {setting: path} with self.settings(**new_settings): with self.subTest(script_name=script_name, **new_settings): try: self.set_script_name(script_name) self.assertEqual(getattr(settings, setting), expected_path) finally: clear_script_prefix()
104bf0322621d40b3391e360159e8ac77424d46cf4cecc4eaddb845e8b9dd4cf
from datetime import datetime, timezone from django.conf import settings from django.contrib.auth import authenticate from django.contrib.auth.backends import RemoteUserBackend from django.contrib.auth.middleware import RemoteUserMiddleware from django.contrib.auth.models import User from django.middleware.csrf import _get_new_csrf_string, _mask_cipher_secret from django.test import Client, TestCase, modify_settings, override_settings @override_settings(ROOT_URLCONF="auth_tests.urls") class RemoteUserTest(TestCase): middleware = "django.contrib.auth.middleware.RemoteUserMiddleware" backend = "django.contrib.auth.backends.RemoteUserBackend" header = "REMOTE_USER" email_header = "REMOTE_EMAIL" # Usernames to be passed in REMOTE_USER for the test_known_user test case. known_user = "knownuser" known_user2 = "knownuser2" def setUp(self): self.patched_settings = modify_settings( AUTHENTICATION_BACKENDS={"append": self.backend}, MIDDLEWARE={"append": self.middleware}, ) self.patched_settings.enable() def tearDown(self): self.patched_settings.disable() def test_no_remote_user(self): """Users are not created when remote user is not specified.""" num_users = User.objects.count() response = self.client.get("/remote_user/") self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) response = self.client.get("/remote_user/", **{self.header: None}) self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) response = self.client.get("/remote_user/", **{self.header: ""}) self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) def test_csrf_validation_passes_after_process_request_login(self): """ CSRF check must access the CSRF token from the session or cookie, rather than the request, as rotate_token() may have been called by an authentication middleware during the process_request() phase. """ csrf_client = Client(enforce_csrf_checks=True) csrf_secret = _get_new_csrf_string() csrf_token = _mask_cipher_secret(csrf_secret) csrf_token_form = _mask_cipher_secret(csrf_secret) headers = {self.header: "fakeuser"} data = {"csrfmiddlewaretoken": csrf_token_form} # Verify that CSRF is configured for the view csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token}) response = csrf_client.post("/remote_user/", **headers) self.assertEqual(response.status_code, 403) self.assertIn(b"CSRF verification failed.", response.content) # This request will call django.contrib.auth.login() which will call # django.middleware.csrf.rotate_token() thus changing the value of # request.META['CSRF_COOKIE'] from the user submitted value set by # CsrfViewMiddleware.process_request() to the new csrftoken value set # by rotate_token(). Csrf validation should still pass when the view is # later processed by CsrfViewMiddleware.process_view() csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token}) response = csrf_client.post("/remote_user/", data, **headers) self.assertEqual(response.status_code, 200) def test_unknown_user(self): """ Tests the case where the username passed in the header does not exist as a User. """ num_users = User.objects.count() response = self.client.get("/remote_user/", **{self.header: "newuser"}) self.assertEqual(response.context["user"].username, "newuser") self.assertEqual(User.objects.count(), num_users + 1) User.objects.get(username="newuser") # Another request with same user should not create any new users. response = self.client.get("/remote_user/", **{self.header: "newuser"}) self.assertEqual(User.objects.count(), num_users + 1) def test_known_user(self): """ Tests the case where the username passed in the header is a valid User. """ User.objects.create(username="knownuser") User.objects.create(username="knownuser2") num_users = User.objects.count() response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") self.assertEqual(User.objects.count(), num_users) # A different user passed in the headers causes the new user # to be logged in. response = self.client.get("/remote_user/", **{self.header: self.known_user2}) self.assertEqual(response.context["user"].username, "knownuser2") self.assertEqual(User.objects.count(), num_users) def test_last_login(self): """ A user's last_login is set the first time they make a request but not updated in subsequent requests with the same session. """ user = User.objects.create(username="knownuser") # Set last_login to something so we can determine if it changes. default_login = datetime(2000, 1, 1) if settings.USE_TZ: default_login = default_login.replace(tzinfo=timezone.utc) user.last_login = default_login user.save() response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertNotEqual(default_login, response.context["user"].last_login) user = User.objects.get(username="knownuser") user.last_login = default_login user.save() response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(default_login, response.context["user"].last_login) def test_header_disappears(self): """ A logged in user is logged out automatically when the REMOTE_USER header disappears during the same browser session. """ User.objects.create(username="knownuser") # Known user authenticates response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") # During the session, the REMOTE_USER header disappears. Should trigger logout. response = self.client.get("/remote_user/") self.assertTrue(response.context["user"].is_anonymous) # verify the remoteuser middleware will not remove a user # authenticated via another backend User.objects.create_user(username="modeluser", password="foo") self.client.login(username="modeluser", password="foo") authenticate(username="modeluser", password="foo") response = self.client.get("/remote_user/") self.assertEqual(response.context["user"].username, "modeluser") def test_user_switch_forces_new_login(self): """ If the username in the header changes between requests that the original user is logged out """ User.objects.create(username="knownuser") # Known user authenticates response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") # During the session, the REMOTE_USER changes to a different user. response = self.client.get("/remote_user/", **{self.header: "newnewuser"}) # The current user is not the prior remote_user. # In backends that create a new user, username is "newnewuser" # In backends that do not create new users, it is '' (anonymous user) self.assertNotEqual(response.context["user"].username, "knownuser") def test_inactive_user(self): User.objects.create(username="knownuser", is_active=False) response = self.client.get("/remote_user/", **{self.header: "knownuser"}) self.assertTrue(response.context["user"].is_anonymous) class RemoteUserNoCreateBackend(RemoteUserBackend): """Backend that doesn't create unknown users.""" create_unknown_user = False class RemoteUserNoCreateTest(RemoteUserTest): """ Contains the same tests as RemoteUserTest, but using a custom auth backend class that doesn't create unknown users. """ backend = "auth_tests.test_remote_user.RemoteUserNoCreateBackend" def test_unknown_user(self): num_users = User.objects.count() response = self.client.get("/remote_user/", **{self.header: "newuser"}) self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) class AllowAllUsersRemoteUserBackendTest(RemoteUserTest): """Backend that allows inactive users.""" backend = "django.contrib.auth.backends.AllowAllUsersRemoteUserBackend" def test_inactive_user(self): user = User.objects.create(username="knownuser", is_active=False) response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, user.username) class CustomRemoteUserBackend(RemoteUserBackend): """ Backend that overrides RemoteUserBackend methods. """ def clean_username(self, username): """ Grabs username before the @ character. """ return username.split("@")[0] def configure_user(self, request, user, created=True): """ Sets user's email address using the email specified in an HTTP header. Sets user's last name for existing users. """ user.email = request.META.get(RemoteUserTest.email_header, "") if not created: user.last_name = user.username user.save() return user class RemoteUserCustomTest(RemoteUserTest): """ Tests a custom RemoteUserBackend subclass that overrides the clean_username and configure_user methods. """ backend = "auth_tests.test_remote_user.CustomRemoteUserBackend" # REMOTE_USER strings with email addresses for the custom backend to # clean. known_user = "[email protected]" known_user2 = "[email protected]" def test_known_user(self): """ The strings passed in REMOTE_USER should be cleaned and the known users should not have been configured with an email address. """ super().test_known_user() knownuser = User.objects.get(username="knownuser") knownuser2 = User.objects.get(username="knownuser2") self.assertEqual(knownuser.email, "") self.assertEqual(knownuser2.email, "") self.assertEqual(knownuser.last_name, "knownuser") self.assertEqual(knownuser2.last_name, "knownuser2") def test_unknown_user(self): """ The unknown user created should be configured with an email address provided in the request header. """ num_users = User.objects.count() response = self.client.get( "/remote_user/", **{ self.header: "newuser", self.email_header: "[email protected]", }, ) self.assertEqual(response.context["user"].username, "newuser") self.assertEqual(response.context["user"].email, "[email protected]") self.assertEqual(response.context["user"].last_name, "") self.assertEqual(User.objects.count(), num_users + 1) newuser = User.objects.get(username="newuser") self.assertEqual(newuser.email, "[email protected]") class CustomHeaderMiddleware(RemoteUserMiddleware): """ Middleware that overrides custom HTTP auth user header. """ header = "HTTP_AUTHUSER" class CustomHeaderRemoteUserTest(RemoteUserTest): """ Tests a custom RemoteUserMiddleware subclass with custom HTTP auth user header. """ middleware = "auth_tests.test_remote_user.CustomHeaderMiddleware" header = "HTTP_AUTHUSER" class PersistentRemoteUserTest(RemoteUserTest): """ PersistentRemoteUserMiddleware keeps the user logged in even if the subsequent calls do not contain the header value. """ middleware = "django.contrib.auth.middleware.PersistentRemoteUserMiddleware" require_header = False def test_header_disappears(self): """ A logged in user is kept logged in even if the REMOTE_USER header disappears during the same browser session. """ User.objects.create(username="knownuser") # Known user authenticates response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") # Should stay logged in if the REMOTE_USER header disappears. response = self.client.get("/remote_user/") self.assertFalse(response.context["user"].is_anonymous) self.assertEqual(response.context["user"].username, "knownuser")
ca0c90aaae7e48476250f4c57746eb158336cc5a5636bab2321848623a8f6f51
import os import shutil import sys import tempfile import threading import time import unittest from datetime import datetime, timedelta from datetime import timezone as datetime_timezone from io import StringIO from pathlib import Path from urllib.request import urlopen from django.conf import DEFAULT_STORAGE_ALIAS, STATICFILES_STORAGE_ALIAS from django.core.cache import cache from django.core.exceptions import SuspiciousFileOperation from django.core.files.base import ContentFile, File from django.core.files.storage import ( GET_STORAGE_CLASS_DEPRECATED_MSG, FileSystemStorage, InvalidStorageError, ) from django.core.files.storage import Storage as BaseStorage from django.core.files.storage import ( StorageHandler, default_storage, get_storage_class, storages, ) from django.core.files.uploadedfile import ( InMemoryUploadedFile, SimpleUploadedFile, TemporaryUploadedFile, ) from django.db.models import FileField from django.db.models.fields.files import FileDescriptor from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings from django.test.utils import ignore_warnings, requires_tz_support from django.urls import NoReverseMatch, reverse_lazy from django.utils import timezone from django.utils._os import symlinks_supported from django.utils.deprecation import RemovedInDjango51Warning from .models import Storage, callable_storage, temp_storage, temp_storage_location FILE_SUFFIX_REGEX = "[A-Za-z0-9]{7}" class GetStorageClassTests(SimpleTestCase): @ignore_warnings(category=RemovedInDjango51Warning) def test_get_filesystem_storage(self): """ get_storage_class returns the class for a storage backend name/path. """ self.assertEqual( get_storage_class("django.core.files.storage.FileSystemStorage"), FileSystemStorage, ) @ignore_warnings(category=RemovedInDjango51Warning) def test_get_invalid_storage_module(self): """ get_storage_class raises an error if the requested import don't exist. """ with self.assertRaisesMessage(ImportError, "No module named 'storage'"): get_storage_class("storage.NonexistentStorage") @ignore_warnings(category=RemovedInDjango51Warning) def test_get_nonexistent_storage_class(self): """ get_storage_class raises an error if the requested class don't exist. """ with self.assertRaises(ImportError): get_storage_class("django.core.files.storage.NonexistentStorage") @ignore_warnings(category=RemovedInDjango51Warning) def test_get_nonexistent_storage_module(self): """ get_storage_class raises an error if the requested module don't exist. """ with self.assertRaisesMessage( ImportError, "No module named 'django.core.files.nonexistent_storage'" ): get_storage_class( "django.core.files.nonexistent_storage.NonexistentStorage" ) def test_deprecation_warning(self): msg = GET_STORAGE_CLASS_DEPRECATED_MSG with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_storage_class("django.core.files.storage.FileSystemStorage"), class FileSystemStorageTests(unittest.TestCase): def test_deconstruction(self): path, args, kwargs = temp_storage.deconstruct() self.assertEqual(path, "django.core.files.storage.FileSystemStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {"location": temp_storage_location}) kwargs_orig = { "location": temp_storage_location, "base_url": "http://myfiles.example.com/", } storage = FileSystemStorage(**kwargs_orig) path, args, kwargs = storage.deconstruct() self.assertEqual(kwargs, kwargs_orig) def test_lazy_base_url_init(self): """ FileSystemStorage.__init__() shouldn't evaluate base_url. """ storage = FileSystemStorage(base_url=reverse_lazy("app:url")) with self.assertRaises(NoReverseMatch): storage.url(storage.base_url) class FileStorageTests(SimpleTestCase): storage_class = FileSystemStorage def setUp(self): self.temp_dir = tempfile.mkdtemp() self.storage = self.storage_class( location=self.temp_dir, base_url="/test_media_url/" ) # Set up a second temporary directory which is ensured to have a mixed # case name. self.temp_dir2 = tempfile.mkdtemp(suffix="aBc") def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.temp_dir2) def test_empty_location(self): """ Makes sure an exception is raised if the location is empty """ storage = self.storage_class(location="") self.assertEqual(storage.base_location, "") self.assertEqual(storage.location, os.getcwd()) def test_file_access_options(self): """ Standard file access options are available, and work as expected. """ self.assertFalse(self.storage.exists("storage_test")) f = self.storage.open("storage_test", "w") f.write("storage contents") f.close() self.assertTrue(self.storage.exists("storage_test")) f = self.storage.open("storage_test", "r") self.assertEqual(f.read(), "storage contents") f.close() self.storage.delete("storage_test") self.assertFalse(self.storage.exists("storage_test")) def _test_file_time_getter(self, getter): # Check for correct behavior under both USE_TZ=True and USE_TZ=False. # The tests are similar since they both set up a situation where the # system time zone, Django's TIME_ZONE, and UTC are distinct. self._test_file_time_getter_tz_handling_on(getter) self._test_file_time_getter_tz_handling_off(getter) @override_settings(USE_TZ=True, TIME_ZONE="Africa/Algiers") def _test_file_time_getter_tz_handling_on(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. The following will be aware in UTC. now = timezone.now() self.assertFalse(self.storage.exists("test.file.tz.on")) f = ContentFile("custom contents") f_name = self.storage.save("test.file.tz.on", f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be aware, in UTC self.assertTrue(timezone.is_aware(dt)) self.assertEqual(now.tzname(), dt.tzname()) # The three timezones are indeed distinct. naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = datetime_timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and now should be the same effective time. self.assertLess(abs(dt - now), timedelta(seconds=2)) @override_settings(USE_TZ=False, TIME_ZONE="Africa/Algiers") def _test_file_time_getter_tz_handling_off(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. self.assertFalse(self.storage.exists("test.file.tz.off")) f = ContentFile("custom contents") f_name = self.storage.save("test.file.tz.off", f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be naive, in system (+1) TZ self.assertTrue(timezone.is_naive(dt)) # The three timezones are indeed distinct. naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = datetime_timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and naive_now should be the same effective time. self.assertLess(abs(dt - naive_now), timedelta(seconds=2)) # If we convert dt to an aware object using the Algiers # timezone then it should be the same effective time to # now_in_algiers. _dt = timezone.make_aware(dt, now_in_algiers.tzinfo) self.assertLess(abs(_dt - now_in_algiers), timedelta(seconds=2)) def test_file_get_accessed_time(self): """ File storage returns a Datetime object for the last accessed time of a file. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.addCleanup(self.storage.delete, f_name) atime = self.storage.get_accessed_time(f_name) self.assertEqual( atime, datetime.fromtimestamp(os.path.getatime(self.storage.path(f_name))) ) self.assertLess( timezone.now() - self.storage.get_accessed_time(f_name), timedelta(seconds=2), ) @requires_tz_support def test_file_get_accessed_time_timezone(self): self._test_file_time_getter(self.storage.get_accessed_time) def test_file_get_created_time(self): """ File storage returns a datetime for the creation time of a file. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.addCleanup(self.storage.delete, f_name) ctime = self.storage.get_created_time(f_name) self.assertEqual( ctime, datetime.fromtimestamp(os.path.getctime(self.storage.path(f_name))) ) self.assertLess( timezone.now() - self.storage.get_created_time(f_name), timedelta(seconds=2) ) @requires_tz_support def test_file_get_created_time_timezone(self): self._test_file_time_getter(self.storage.get_created_time) def test_file_get_modified_time(self): """ File storage returns a datetime for the last modified time of a file. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.addCleanup(self.storage.delete, f_name) mtime = self.storage.get_modified_time(f_name) self.assertEqual( mtime, datetime.fromtimestamp(os.path.getmtime(self.storage.path(f_name))) ) self.assertLess( timezone.now() - self.storage.get_modified_time(f_name), timedelta(seconds=2), ) @requires_tz_support def test_file_get_modified_time_timezone(self): self._test_file_time_getter(self.storage.get_modified_time) def test_file_save_without_name(self): """ File storage extracts the filename from the content object if no name is given explicitly. """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f.name = "test.file" storage_f_name = self.storage.save(None, f) self.assertEqual(storage_f_name, f.name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_f_name) def test_file_save_with_path(self): """ Saving a pathname should create intermediate directories as necessary. """ self.assertFalse(self.storage.exists("path/to")) self.storage.save("path/to/test.file", ContentFile("file saved with path")) self.assertTrue(self.storage.exists("path/to")) with self.storage.open("path/to/test.file") as f: self.assertEqual(f.read(), b"file saved with path") self.assertTrue( os.path.exists(os.path.join(self.temp_dir, "path", "to", "test.file")) ) self.storage.delete("path/to/test.file") def test_file_save_abs_path(self): test_name = "path/to/test.file" f = ContentFile("file saved with path") f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual(f_name, test_name) @unittest.skipUnless( symlinks_supported(), "Must be able to symlink to run this test." ) def test_file_save_broken_symlink(self): """A new path is created on save when a broken symlink is supplied.""" nonexistent_file_path = os.path.join(self.temp_dir, "nonexistent.txt") broken_symlink_path = os.path.join(self.temp_dir, "symlink.txt") os.symlink(nonexistent_file_path, broken_symlink_path) f = ContentFile("some content") f_name = self.storage.save(broken_symlink_path, f) self.assertIs(os.path.exists(os.path.join(self.temp_dir, f_name)), True) def test_save_doesnt_close(self): with TemporaryUploadedFile("test", "text/plain", 1, "utf8") as file: file.write(b"1") file.seek(0) self.assertFalse(file.closed) self.storage.save("path/to/test.file", file) self.assertFalse(file.closed) self.assertFalse(file.file.closed) file = InMemoryUploadedFile(StringIO("1"), "", "test", "text/plain", 1, "utf8") with file: self.assertFalse(file.closed) self.storage.save("path/to/test.file", file) self.assertFalse(file.closed) self.assertFalse(file.file.closed) def test_file_path(self): """ File storage returns the full path of a file """ self.assertFalse(self.storage.exists("test.file")) f = ContentFile("custom contents") f_name = self.storage.save("test.file", f) self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name)) self.storage.delete(f_name) def test_file_url(self): """ File storage returns a url to access a given file from the web. """ self.assertEqual( self.storage.url("test.file"), self.storage.base_url + "test.file" ) # should encode special chars except ~!*()' # like encodeURIComponent() JavaScript function do self.assertEqual( self.storage.url(r"~!*()'@#$%^&*abc`+ =.file"), "/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file", ) self.assertEqual(self.storage.url("ab\0c"), "/test_media_url/ab%00c") # should translate os path separator(s) to the url path separator self.assertEqual( self.storage.url("""a/b\\c.file"""), "/test_media_url/a/b/c.file" ) # #25905: remove leading slashes from file names to prevent unsafe url output self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(r"\evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url("///evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(r"\\\evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(None), "/test_media_url/") def test_base_url(self): """ File storage returns a url even when its base_url is unset or modified. """ self.storage.base_url = None with self.assertRaises(ValueError): self.storage.url("test.file") # #22717: missing ending slash in base_url should be auto-corrected storage = self.storage_class( location=self.temp_dir, base_url="/no_ending_slash" ) self.assertEqual( storage.url("test.file"), "%s%s" % (storage.base_url, "test.file") ) def test_listdir(self): """ File storage returns a tuple containing directories and files. """ self.assertFalse(self.storage.exists("storage_test_1")) self.assertFalse(self.storage.exists("storage_test_2")) self.assertFalse(self.storage.exists("storage_dir_1")) self.storage.save("storage_test_1", ContentFile("custom content")) self.storage.save("storage_test_2", ContentFile("custom content")) os.mkdir(os.path.join(self.temp_dir, "storage_dir_1")) self.addCleanup(self.storage.delete, "storage_test_1") self.addCleanup(self.storage.delete, "storage_test_2") for directory in ("", Path("")): with self.subTest(directory=directory): dirs, files = self.storage.listdir(directory) self.assertEqual(set(dirs), {"storage_dir_1"}) self.assertEqual(set(files), {"storage_test_1", "storage_test_2"}) def test_file_storage_prevents_directory_traversal(self): """ File storage prevents directory traversal (files can only be accessed if they're below the storage location). """ with self.assertRaises(SuspiciousFileOperation): self.storage.exists("..") with self.assertRaises(SuspiciousFileOperation): self.storage.exists("/etc/passwd") def test_file_storage_preserves_filename_case(self): """The storage backend should preserve case of filenames.""" # Create a storage backend associated with the mixed case name # directory. other_temp_storage = self.storage_class(location=self.temp_dir2) # Ask that storage backend to store a file with a mixed case filename. mixed_case = "CaSe_SeNsItIvE" file = other_temp_storage.open(mixed_case, "w") file.write("storage contents") file.close() self.assertEqual( os.path.join(self.temp_dir2, mixed_case), other_temp_storage.path(mixed_case), ) other_temp_storage.delete(mixed_case) def test_makedirs_race_handling(self): """ File storage should be robust against directory creation race conditions. """ real_makedirs = os.makedirs # Monkey-patch os.makedirs, to simulate a normal call, a raced call, # and an error. def fake_makedirs(path, mode=0o777, exist_ok=False): if path == os.path.join(self.temp_dir, "normal"): real_makedirs(path, mode, exist_ok) elif path == os.path.join(self.temp_dir, "raced"): real_makedirs(path, mode, exist_ok) if not exist_ok: raise FileExistsError() elif path == os.path.join(self.temp_dir, "error"): raise PermissionError() else: self.fail("unexpected argument %r" % path) try: os.makedirs = fake_makedirs self.storage.save("normal/test.file", ContentFile("saved normally")) with self.storage.open("normal/test.file") as f: self.assertEqual(f.read(), b"saved normally") self.storage.save("raced/test.file", ContentFile("saved with race")) with self.storage.open("raced/test.file") as f: self.assertEqual(f.read(), b"saved with race") # Exceptions aside from FileExistsError are raised. with self.assertRaises(PermissionError): self.storage.save("error/test.file", ContentFile("not saved")) finally: os.makedirs = real_makedirs def test_remove_race_handling(self): """ File storage should be robust against file removal race conditions. """ real_remove = os.remove # Monkey-patch os.remove, to simulate a normal call, a raced call, # and an error. def fake_remove(path): if path == os.path.join(self.temp_dir, "normal.file"): real_remove(path) elif path == os.path.join(self.temp_dir, "raced.file"): real_remove(path) raise FileNotFoundError() elif path == os.path.join(self.temp_dir, "error.file"): raise PermissionError() else: self.fail("unexpected argument %r" % path) try: os.remove = fake_remove self.storage.save("normal.file", ContentFile("delete normally")) self.storage.delete("normal.file") self.assertFalse(self.storage.exists("normal.file")) self.storage.save("raced.file", ContentFile("delete with race")) self.storage.delete("raced.file") self.assertFalse(self.storage.exists("normal.file")) # Exceptions aside from FileNotFoundError are raised. self.storage.save("error.file", ContentFile("delete with error")) with self.assertRaises(PermissionError): self.storage.delete("error.file") finally: os.remove = real_remove def test_file_chunks_error(self): """ Test behavior when file.chunks() is raising an error """ f1 = ContentFile("chunks fails") def failing_chunks(): raise OSError f1.chunks = failing_chunks with self.assertRaises(OSError): self.storage.save("error.file", f1) def test_delete_no_name(self): """ Calling delete with an empty name should not try to remove the base storage directory, but fail loudly (#20660). """ msg = "The name must be given to delete()." with self.assertRaisesMessage(ValueError, msg): self.storage.delete(None) with self.assertRaisesMessage(ValueError, msg): self.storage.delete("") def test_delete_deletes_directories(self): tmp_dir = tempfile.mkdtemp(dir=self.storage.location) self.storage.delete(tmp_dir) self.assertFalse(os.path.exists(tmp_dir)) @override_settings( MEDIA_ROOT="media_root", MEDIA_URL="media_url/", FILE_UPLOAD_PERMISSIONS=0o777, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777, ) def test_setting_changed(self): """ Properties using settings values as defaults should be updated on referenced settings change while specified values should be unchanged. """ storage = self.storage_class( location="explicit_location", base_url="explicit_base_url/", file_permissions_mode=0o666, directory_permissions_mode=0o666, ) defaults_storage = self.storage_class() settings = { "MEDIA_ROOT": "overridden_media_root", "MEDIA_URL": "/overridden_media_url/", "FILE_UPLOAD_PERMISSIONS": 0o333, "FILE_UPLOAD_DIRECTORY_PERMISSIONS": 0o333, } with self.settings(**settings): self.assertEqual(storage.base_location, "explicit_location") self.assertIn("explicit_location", storage.location) self.assertEqual(storage.base_url, "explicit_base_url/") self.assertEqual(storage.file_permissions_mode, 0o666) self.assertEqual(storage.directory_permissions_mode, 0o666) self.assertEqual(defaults_storage.base_location, settings["MEDIA_ROOT"]) self.assertIn(settings["MEDIA_ROOT"], defaults_storage.location) self.assertEqual(defaults_storage.base_url, settings["MEDIA_URL"]) self.assertEqual( defaults_storage.file_permissions_mode, settings["FILE_UPLOAD_PERMISSIONS"], ) self.assertEqual( defaults_storage.directory_permissions_mode, settings["FILE_UPLOAD_DIRECTORY_PERMISSIONS"], ) def test_file_methods_pathlib_path(self): p = Path("test.file") self.assertFalse(self.storage.exists(p)) f = ContentFile("custom contents") f_name = self.storage.save(p, f) # Storage basic methods. self.assertEqual(self.storage.path(p), os.path.join(self.temp_dir, p)) self.assertEqual(self.storage.size(p), 15) self.assertEqual(self.storage.url(p), self.storage.base_url + f_name) with self.storage.open(p) as f: self.assertEqual(f.read(), b"custom contents") self.addCleanup(self.storage.delete, p) class CustomStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): """ Append numbers to duplicate files rather than underscores, like Trac. """ basename, *ext = os.path.splitext(name) number = 2 while self.exists(name): name = "".join([basename, ".", str(number)] + ext) number += 1 return name class CustomStorageTests(FileStorageTests): storage_class = CustomStorage def test_custom_get_available_name(self): first = self.storage.save("custom_storage", ContentFile("custom contents")) self.assertEqual(first, "custom_storage") second = self.storage.save("custom_storage", ContentFile("more contents")) self.assertEqual(second, "custom_storage.2") self.storage.delete(first) self.storage.delete(second) class OverwritingStorage(FileSystemStorage): """ Overwrite existing files instead of appending a suffix to generate an unused name. """ # Mask out O_EXCL so os.open() doesn't raise OSError if the file exists. OS_OPEN_FLAGS = FileSystemStorage.OS_OPEN_FLAGS & ~os.O_EXCL def get_available_name(self, name, max_length=None): """Override the effort to find an used name.""" return name class OverwritingStorageTests(FileStorageTests): storage_class = OverwritingStorage def test_save_overwrite_behavior(self): """Saving to same file name twice overwrites the first file.""" name = "test.file" self.assertFalse(self.storage.exists(name)) content_1 = b"content one" content_2 = b"second content" f_1 = ContentFile(content_1) f_2 = ContentFile(content_2) stored_name_1 = self.storage.save(name, f_1) try: self.assertEqual(stored_name_1, name) self.assertTrue(self.storage.exists(name)) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name))) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_1) stored_name_2 = self.storage.save(name, f_2) self.assertEqual(stored_name_2, name) self.assertTrue(self.storage.exists(name)) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name))) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_2) finally: self.storage.delete(name) class DiscardingFalseContentStorage(FileSystemStorage): def _save(self, name, content): if content: return super()._save(name, content) return "" class DiscardingFalseContentStorageTests(FileStorageTests): storage_class = DiscardingFalseContentStorage def test_custom_storage_discarding_empty_content(self): """ When Storage.save() wraps a file-like object in File, it should include the name argument so that bool(file) evaluates to True (#26495). """ output = StringIO("content") self.storage.save("tests/stringio", output) self.assertTrue(self.storage.exists("tests/stringio")) with self.storage.open("tests/stringio") as f: self.assertEqual(f.read(), b"content") class FileFieldStorageTests(TestCase): def tearDown(self): shutil.rmtree(temp_storage_location) def _storage_max_filename_length(self, storage): """ Query filesystem for maximum filename length (e.g. AUFS has 242). """ dir_to_test = storage.location while not os.path.exists(dir_to_test): dir_to_test = os.path.dirname(dir_to_test) try: return os.pathconf(dir_to_test, "PC_NAME_MAX") except Exception: return 255 # Should be safe on most backends def test_files(self): self.assertIsInstance(Storage.normal, FileDescriptor) # An object without a file has limited functionality. obj1 = Storage() self.assertEqual(obj1.normal.name, "") with self.assertRaises(ValueError): obj1.normal.size # Saving a file enables full functionality. obj1.normal.save("django_test.txt", ContentFile("content")) self.assertEqual(obj1.normal.name, "tests/django_test.txt") self.assertEqual(obj1.normal.size, 7) self.assertEqual(obj1.normal.read(), b"content") obj1.normal.close() # File objects can be assigned to FileField attributes, but shouldn't # get committed until the model it's attached to is saved. obj1.normal = SimpleUploadedFile("assignment.txt", b"content") dirs, files = temp_storage.listdir("tests") self.assertEqual(dirs, []) self.assertNotIn("assignment.txt", files) obj1.save() dirs, files = temp_storage.listdir("tests") self.assertEqual(sorted(files), ["assignment.txt", "django_test.txt"]) # Save another file with the same name. obj2 = Storage() obj2.normal.save("django_test.txt", ContentFile("more content")) obj2_name = obj2.normal.name self.assertRegex(obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX) self.assertEqual(obj2.normal.size, 12) obj2.normal.close() # Deleting an object does not delete the file it uses. obj2.delete() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertNotEqual(obj2_name, obj2.normal.name) self.assertRegex( obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX ) obj2.normal.close() def test_filefield_read(self): # Files can be read in a little at a time, if necessary. obj = Storage.objects.create( normal=SimpleUploadedFile("assignment.txt", b"content") ) obj.normal.open() self.assertEqual(obj.normal.read(3), b"con") self.assertEqual(obj.normal.read(), b"tent") self.assertEqual( list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"] ) obj.normal.close() def test_filefield_write(self): # Files can be written to. obj = Storage.objects.create( normal=SimpleUploadedFile("rewritten.txt", b"content") ) with obj.normal as normal: normal.open("wb") normal.write(b"updated") obj.refresh_from_db() self.assertEqual(obj.normal.read(), b"updated") obj.normal.close() def test_filefield_reopen(self): obj = Storage.objects.create( normal=SimpleUploadedFile("reopen.txt", b"content") ) with obj.normal as normal: normal.open() obj.normal.open() obj.normal.file.seek(0) obj.normal.close() def test_duplicate_filename(self): # Multiple files with the same name get _(7 random chars) appended to them. objs = [Storage() for i in range(2)] for o in objs: o.normal.save("multiple_files.txt", ContentFile("Same Content")) try: names = [o.normal.name for o in objs] self.assertEqual(names[0], "tests/multiple_files.txt") self.assertRegex( names[1], "tests/multiple_files_%s.txt" % FILE_SUFFIX_REGEX ) finally: for o in objs: o.delete() def test_file_truncation(self): # Given the max_length is limited, when multiple files get uploaded # under the same name, then the filename get truncated in order to fit # in _(7 random chars). When most of the max_length is taken by # dirname + extension and there are not enough characters in the # filename to truncate, an exception should be raised. objs = [Storage() for i in range(2)] filename = "filename.ext" for o in objs: o.limited_length.save(filename, ContentFile("Same Content")) try: # Testing truncation. names = [o.limited_length.name for o in objs] self.assertEqual(names[0], "tests/%s" % filename) self.assertRegex(names[1], "tests/fi_%s.ext" % FILE_SUFFIX_REGEX) # Testing exception is raised when filename is too short to truncate. filename = "short.longext" objs[0].limited_length.save(filename, ContentFile("Same Content")) with self.assertRaisesMessage( SuspiciousFileOperation, "Storage can not find an available filename" ): objs[1].limited_length.save(*(filename, ContentFile("Same Content"))) finally: for o in objs: o.delete() @unittest.skipIf( sys.platform == "win32", "Windows supports at most 260 characters in a path.", ) def test_extended_length_storage(self): # Testing FileField with max_length > 255. Most systems have filename # length limitation of 255. Path takes extra chars. filename = ( self._storage_max_filename_length(temp_storage) - 4 ) * "a" # 4 chars for extension. obj = Storage() obj.extended_length.save("%s.txt" % filename, ContentFile("Same Content")) self.assertEqual(obj.extended_length.name, "tests/%s.txt" % filename) self.assertEqual(obj.extended_length.read(), b"Same Content") obj.extended_length.close() def test_filefield_default(self): # Default values allow an object to access a single file. temp_storage.save("tests/default.txt", ContentFile("default content")) obj = Storage.objects.create() self.assertEqual(obj.default.name, "tests/default.txt") self.assertEqual(obj.default.read(), b"default content") obj.default.close() # But it shouldn't be deleted, even if there are no more objects using # it. obj.delete() obj = Storage() self.assertEqual(obj.default.read(), b"default content") obj.default.close() def test_empty_upload_to(self): # upload_to can be empty, meaning it does not use subdirectory. obj = Storage() obj.empty.save("django_test.txt", ContentFile("more content")) self.assertEqual(obj.empty.name, "django_test.txt") self.assertEqual(obj.empty.read(), b"more content") obj.empty.close() def test_pathlib_upload_to(self): obj = Storage() obj.pathlib_callable.save("some_file1.txt", ContentFile("some content")) self.assertEqual(obj.pathlib_callable.name, "bar/some_file1.txt") obj.pathlib_direct.save("some_file2.txt", ContentFile("some content")) self.assertEqual(obj.pathlib_direct.name, "bar/some_file2.txt") obj.random.close() def test_random_upload_to(self): # Verify the fix for #5655, making sure the directory is only # determined once. obj = Storage() obj.random.save("random_file", ContentFile("random content")) self.assertTrue(obj.random.name.endswith("/random_file")) obj.random.close() def test_custom_valid_name_callable_upload_to(self): """ Storage.get_valid_name() should be called when upload_to is a callable. """ obj = Storage() obj.custom_valid_name.save("random_file", ContentFile("random content")) # CustomValidNameStorage.get_valid_name() appends '_valid' to the name self.assertTrue(obj.custom_valid_name.name.endswith("/random_file_valid")) obj.custom_valid_name.close() def test_filefield_pickling(self): # Push an object into the cache to make sure it pickles properly obj = Storage() obj.normal.save("django_test.txt", ContentFile("more content")) obj.normal.close() cache.set("obj", obj) self.assertEqual(cache.get("obj").normal.name, "tests/django_test.txt") def test_file_object(self): # Create sample file temp_storage.save("tests/example.txt", ContentFile("some content")) # Load it as Python file object with open(temp_storage.path("tests/example.txt")) as file_obj: # Save it using storage and read its content temp_storage.save("tests/file_obj", file_obj) self.assertTrue(temp_storage.exists("tests/file_obj")) with temp_storage.open("tests/file_obj") as f: self.assertEqual(f.read(), b"some content") def test_stringio(self): # Test passing StringIO instance as content argument to save output = StringIO() output.write("content") output.seek(0) # Save it and read written file temp_storage.save("tests/stringio", output) self.assertTrue(temp_storage.exists("tests/stringio")) with temp_storage.open("tests/stringio") as f: self.assertEqual(f.read(), b"content") class FieldCallableFileStorageTests(SimpleTestCase): def setUp(self): self.temp_storage_location = tempfile.mkdtemp( suffix="filefield_callable_storage" ) def tearDown(self): shutil.rmtree(self.temp_storage_location) def test_callable_base_class_error_raises(self): class NotStorage: pass msg = ( "FileField.storage must be a subclass/instance of " "django.core.files.storage.base.Storage" ) for invalid_type in (NotStorage, str, list, set, tuple): with self.subTest(invalid_type=invalid_type): with self.assertRaisesMessage(TypeError, msg): FileField(storage=invalid_type) def test_file_field_storage_none_uses_default_storage(self): self.assertEqual(FileField().storage, default_storage) def test_callable_function_storage_file_field(self): storage = FileSystemStorage(location=self.temp_storage_location) def get_storage(): return storage obj = FileField(storage=get_storage) self.assertEqual(obj.storage, storage) self.assertEqual(obj.storage.location, storage.location) def test_callable_class_storage_file_field(self): class GetStorage(FileSystemStorage): pass obj = FileField(storage=GetStorage) self.assertIsInstance(obj.storage, BaseStorage) def test_callable_storage_file_field_in_model(self): obj = Storage() self.assertEqual(obj.storage_callable.storage, temp_storage) self.assertEqual(obj.storage_callable.storage.location, temp_storage_location) self.assertIsInstance(obj.storage_callable_class.storage, BaseStorage) def test_deconstruction(self): """ Deconstructing gives the original callable, not the evaluated value. """ obj = Storage() *_, kwargs = obj._meta.get_field("storage_callable").deconstruct() storage = kwargs["storage"] self.assertIs(storage, callable_storage) # Tests for a race condition on file saving (#4948). # This is written in such a way that it'll always pass on platforms # without threading. class SlowFile(ContentFile): def chunks(self): time.sleep(1) return super().chunks() class FileSaveRaceConditionTest(SimpleTestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) self.thread = threading.Thread(target=self.save_file, args=["conflict"]) def tearDown(self): shutil.rmtree(self.storage_dir) def save_file(self, name): name = self.storage.save(name, SlowFile(b"Data")) def test_race_condition(self): self.thread.start() self.save_file("conflict") self.thread.join() files = sorted(os.listdir(self.storage_dir)) self.assertEqual(files[0], "conflict") self.assertRegex(files[1], "conflict_%s" % FILE_SUFFIX_REGEX) @unittest.skipIf( sys.platform == "win32", "Windows only partially supports umasks and chmod." ) class FileStoragePermissions(unittest.TestCase): def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) self.storage_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.storage_dir) os.umask(self.old_umask) @override_settings(FILE_UPLOAD_PERMISSIONS=0o654) def test_file_upload_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_file", ContentFile("data")) actual_mode = os.stat(self.storage.path(name))[0] & 0o777 self.assertEqual(actual_mode, 0o654) @override_settings(FILE_UPLOAD_PERMISSIONS=None) def test_file_upload_default_permissions(self): self.storage = FileSystemStorage(self.storage_dir) fname = self.storage.save("some_file", ContentFile("data")) mode = os.stat(self.storage.path(fname))[0] & 0o777 self.assertEqual(mode, 0o666 & ~self.umask) @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/subdir/the_file", ContentFile("data")) file_path = Path(self.storage.path(name)) self.assertEqual(file_path.parent.stat().st_mode & 0o777, 0o765) self.assertEqual(file_path.parent.parent.stat().st_mode & 0o777, 0o765) @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=None) def test_file_upload_directory_default_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/subdir/the_file", ContentFile("data")) file_path = Path(self.storage.path(name)) expected_mode = 0o777 & ~self.umask self.assertEqual(file_path.parent.stat().st_mode & 0o777, expected_mode) self.assertEqual(file_path.parent.parent.stat().st_mode & 0o777, expected_mode) class FileStoragePathParsing(SimpleTestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_directory_with_dot(self): """Regression test for #9610. If the directory name contains a dot and the file name doesn't, make sure we still mangle the file name instead of the directory name. """ self.storage.save("dotted.path/test", ContentFile("1")) self.storage.save("dotted.path/test", ContentFile("2")) files = sorted(os.listdir(os.path.join(self.storage_dir, "dotted.path"))) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, "dotted_.path"))) self.assertEqual(files[0], "test") self.assertRegex(files[1], "test_%s" % FILE_SUFFIX_REGEX) def test_first_character_dot(self): """ File names with a dot as their first character don't have an extension, and the underscore should get added to the end. """ self.storage.save("dotted.path/.test", ContentFile("1")) self.storage.save("dotted.path/.test", ContentFile("2")) files = sorted(os.listdir(os.path.join(self.storage_dir, "dotted.path"))) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, "dotted_.path"))) self.assertEqual(files[0], ".test") self.assertRegex(files[1], ".test_%s" % FILE_SUFFIX_REGEX) class ContentFileStorageTestCase(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_content_saving(self): """ ContentFile can be saved correctly with the filesystem storage, if it was initialized with either bytes or unicode content. """ self.storage.save("bytes.txt", ContentFile(b"content")) self.storage.save("unicode.txt", ContentFile("español")) @override_settings(ROOT_URLCONF="file_storage.urls") class FileLikeObjectTestCase(LiveServerTestCase): """ Test file-like objects (#15644). """ available_apps = [] def setUp(self): self.temp_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(location=self.temp_dir) def tearDown(self): shutil.rmtree(self.temp_dir) def test_urllib_request_urlopen(self): """ Test the File storage API with a file-like object coming from urllib.request.urlopen(). """ file_like_object = urlopen(self.live_server_url + "/") f = File(file_like_object) stored_filename = self.storage.save("remote_file.html", f) remote_file = urlopen(self.live_server_url + "/") with self.storage.open(stored_filename) as stored_file: self.assertEqual(stored_file.read(), remote_file.read()) class StorageHandlerTests(SimpleTestCase): @override_settings( STORAGES={ "custom_storage": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, } ) def test_same_instance(self): cache1 = storages["custom_storage"] cache2 = storages["custom_storage"] self.assertIs(cache1, cache2) def test_defaults(self): storages = StorageHandler() self.assertEqual( storages.backends, { DEFAULT_STORAGE_ALIAS: { "BACKEND": "django.core.files.storage.FileSystemStorage", }, STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, }, ) def test_nonexistent_alias(self): msg = "Could not find config for 'nonexistent' in settings.STORAGES." storages = StorageHandler() with self.assertRaisesMessage(InvalidStorageError, msg): storages["nonexistent"] def test_nonexistent_backend(self): test_storages = StorageHandler( { "invalid_backend": { "BACKEND": "django.nonexistent.NonexistentBackend", }, } ) msg = ( "Could not find backend 'django.nonexistent.NonexistentBackend': " "No module named 'django.nonexistent'" ) with self.assertRaisesMessage(InvalidStorageError, msg): test_storages["invalid_backend"]
933e7c411d097d76f6684d18bdb5d5380743f1ea136082bef8b315e8e5928ada
import re from django.conf import settings from django.contrib.sessions.backends.cache import SessionStore from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest, HttpResponse, UnreadablePostError from django.middleware.csrf import ( CSRF_ALLOWED_CHARS, CSRF_SECRET_LENGTH, CSRF_SESSION_KEY, CSRF_TOKEN_LENGTH, REASON_BAD_ORIGIN, REASON_CSRF_TOKEN_MISSING, REASON_NO_CSRF_COOKIE, CsrfViewMiddleware, InvalidTokenFormat, RejectRequest, _check_token_format, _does_token_match, _mask_cipher_secret, _unmask_cipher_token, get_token, rotate_token, ) from django.test import SimpleTestCase, override_settings from django.views.decorators.csrf import csrf_exempt, requires_csrf_token from .views import ( ensure_csrf_cookie_view, ensured_and_protected_view, non_token_view_using_request_processor, post_form_view, protected_view, sandwiched_rotate_token_view, token_view, ) # This is a test (unmasked) CSRF cookie / secret. TEST_SECRET = "lcccccccX2kcccccccY2jcccccccssIC" # Two masked versions of TEST_SECRET for testing purposes. MASKED_TEST_SECRET1 = "1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD" MASKED_TEST_SECRET2 = "2JgchWvM1tpxT2lfz9aydoXW9yT1DN3NdLiejYxOOlzzV4nhBbYqmqZYbAV3V5Bf" class CsrfFunctionTestMixin: # This method depends on _unmask_cipher_token() being correct. def assertMaskedSecretCorrect(self, masked_secret, secret): """Test that a string is a valid masked version of a secret.""" self.assertEqual(len(masked_secret), CSRF_TOKEN_LENGTH) self.assertEqual(len(secret), CSRF_SECRET_LENGTH) self.assertTrue( set(masked_secret).issubset(set(CSRF_ALLOWED_CHARS)), msg=f"invalid characters in {masked_secret!r}", ) actual = _unmask_cipher_token(masked_secret) self.assertEqual(actual, secret) class CsrfFunctionTests(CsrfFunctionTestMixin, SimpleTestCase): def test_unmask_cipher_token(self): cases = [ (TEST_SECRET, MASKED_TEST_SECRET1), (TEST_SECRET, MASKED_TEST_SECRET2), ( 32 * "a", "vFioG3XOLyGyGsPRFyB9iYUs341ufzIEvFioG3XOLyGyGsPRFyB9iYUs341ufzIE", ), (32 * "a", 64 * "a"), (32 * "a", 64 * "b"), (32 * "b", 32 * "a" + 32 * "b"), (32 * "b", 32 * "b" + 32 * "c"), (32 * "c", 32 * "a" + 32 * "c"), ] for secret, masked_secret in cases: with self.subTest(masked_secret=masked_secret): actual = _unmask_cipher_token(masked_secret) self.assertEqual(actual, secret) def test_mask_cipher_secret(self): cases = [ 32 * "a", TEST_SECRET, "da4SrUiHJYoJ0HYQ0vcgisoIuFOxx4ER", ] for secret in cases: with self.subTest(secret=secret): masked = _mask_cipher_secret(secret) self.assertMaskedSecretCorrect(masked, secret) def test_get_token_csrf_cookie_set(self): request = HttpRequest() request.META["CSRF_COOKIE"] = TEST_SECRET self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) token = get_token(request) self.assertMaskedSecretCorrect(token, TEST_SECRET) # The existing cookie is preserved. self.assertEqual(request.META["CSRF_COOKIE"], TEST_SECRET) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_get_token_csrf_cookie_not_set(self): request = HttpRequest() self.assertNotIn("CSRF_COOKIE", request.META) self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) token = get_token(request) cookie = request.META["CSRF_COOKIE"] self.assertMaskedSecretCorrect(token, cookie) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_rotate_token(self): request = HttpRequest() request.META["CSRF_COOKIE"] = TEST_SECRET self.assertNotIn("CSRF_COOKIE_NEEDS_UPDATE", request.META) rotate_token(request) # The underlying secret was changed. cookie = request.META["CSRF_COOKIE"] self.assertEqual(len(cookie), CSRF_SECRET_LENGTH) self.assertNotEqual(cookie, TEST_SECRET) self.assertIs(request.META["CSRF_COOKIE_NEEDS_UPDATE"], True) def test_check_token_format_valid(self): cases = [ # A token of length CSRF_SECRET_LENGTH. TEST_SECRET, # A token of length CSRF_TOKEN_LENGTH. MASKED_TEST_SECRET1, 64 * "a", ] for token in cases: with self.subTest(token=token): actual = _check_token_format(token) self.assertIsNone(actual) def test_check_token_format_invalid(self): cases = [ (64 * "*", "has invalid characters"), (16 * "a", "has incorrect length"), ] for token, expected_message in cases: with self.subTest(token=token): with self.assertRaisesMessage(InvalidTokenFormat, expected_message): _check_token_format(token) def test_does_token_match(self): cases = [ # Masked tokens match. ((MASKED_TEST_SECRET1, TEST_SECRET), True), ((MASKED_TEST_SECRET2, TEST_SECRET), True), ((64 * "a", _unmask_cipher_token(64 * "a")), True), # Unmasked tokens match. ((TEST_SECRET, TEST_SECRET), True), ((32 * "a", 32 * "a"), True), # Incorrect tokens don't match. ((32 * "a", TEST_SECRET), False), ((64 * "a", TEST_SECRET), False), ] for (token, secret), expected in cases: with self.subTest(token=token, secret=secret): actual = _does_token_match(token, secret) self.assertIs(actual, expected) def test_does_token_match_wrong_token_length(self): with self.assertRaises(AssertionError): _does_token_match(16 * "a", TEST_SECRET) class TestingSessionStore(SessionStore): """ A version of SessionStore that stores what cookie values are passed to set_cookie() when CSRF_USE_SESSIONS=True. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # This is a list of the cookie values passed to set_cookie() over # the course of the request-response. self._cookies_set = [] def __setitem__(self, key, value): super().__setitem__(key, value) self._cookies_set.append(value) class TestingHttpRequest(HttpRequest): """ A version of HttpRequest that lets one track and change some things more easily. """ def __init__(self): super().__init__() self.session = TestingSessionStore() def is_secure(self): return getattr(self, "_is_secure_override", False) class PostErrorRequest(TestingHttpRequest): """ TestingHttpRequest that can raise errors when accessing POST data. """ post_error = None def _get_post(self): if self.post_error is not None: raise self.post_error return self._post def _set_post(self, post): self._post = post POST = property(_get_post, _set_post) class CsrfViewMiddlewareTestMixin(CsrfFunctionTestMixin): """ Shared methods and tests for session-based and cookie-based tokens. """ _csrf_id_cookie = MASKED_TEST_SECRET1 _csrf_id_token = MASKED_TEST_SECRET2 def _set_csrf_cookie(self, req, cookie): raise NotImplementedError("This method must be implemented by a subclass.") def _read_csrf_cookie(self, req, resp): """ Return the CSRF cookie as a string, or False if no cookie is present. """ raise NotImplementedError("This method must be implemented by a subclass.") def _get_cookies_set(self, req, resp): """ Return a list of the cookie values passed to set_cookie() over the course of the request-response. """ raise NotImplementedError("This method must be implemented by a subclass.") def _get_request(self, method=None, cookie=None, request_class=None): if method is None: method = "GET" if request_class is None: request_class = TestingHttpRequest req = request_class() req.method = method if cookie is not None: self._set_csrf_cookie(req, cookie) return req def _get_csrf_cookie_request( self, method=None, cookie=None, post_token=None, meta_token=None, token_header=None, request_class=None, ): """ The method argument defaults to "GET". The cookie argument defaults to this class's default test cookie. The post_token and meta_token arguments are included in the request's req.POST and req.META headers, respectively, when that argument is provided and non-None. The token_header argument is the header key to use for req.META, defaults to "HTTP_X_CSRFTOKEN". """ if cookie is None: cookie = self._csrf_id_cookie if token_header is None: token_header = "HTTP_X_CSRFTOKEN" req = self._get_request( method=method, cookie=cookie, request_class=request_class, ) if post_token is not None: req.POST["csrfmiddlewaretoken"] = post_token if meta_token is not None: req.META[token_header] = meta_token return req def _get_POST_csrf_cookie_request( self, cookie=None, post_token=None, meta_token=None, token_header=None, request_class=None, ): return self._get_csrf_cookie_request( method="POST", cookie=cookie, post_token=post_token, meta_token=meta_token, token_header=token_header, request_class=request_class, ) def _get_POST_request_with_token(self, cookie=None, request_class=None): """The cookie argument defaults to this class's default test cookie.""" return self._get_POST_csrf_cookie_request( cookie=cookie, post_token=self._csrf_id_token, request_class=request_class, ) # This method depends on _unmask_cipher_token() being correct. def _check_token_present(self, response, csrf_secret=None): if csrf_secret is None: csrf_secret = TEST_SECRET text = str(response.content, response.charset) match = re.search('name="csrfmiddlewaretoken" value="(.*?)"', text) self.assertTrue( match, f"Could not find a csrfmiddlewaretoken value in: {text}", ) csrf_token = match[1] self.assertMaskedSecretCorrect(csrf_token, csrf_secret) def test_process_response_get_token_not_used(self): """ If get_token() is not called, the view middleware does not add a cookie. """ # This is important to make pages cacheable. Pages which do call # get_token(), assuming they use the token, are not cacheable because # the token is specific to the user req = self._get_request() # non_token_view_using_request_processor does not call get_token(), but # does use the csrf request processor. By using this, we are testing # that the view processor is properly lazy and doesn't call get_token() # until needed. mw = CsrfViewMiddleware(non_token_view_using_request_processor) mw.process_request(req) mw.process_view(req, non_token_view_using_request_processor, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertIs(csrf_cookie, False) def _check_bad_or_missing_cookie(self, cookie, expected): """Passing None for cookie includes no cookie.""" req = self._get_request(method="POST", cookie=cookie) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertEqual(403, resp.status_code) self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % expected) def test_no_csrf_cookie(self): """ If no CSRF cookies is present, the middleware rejects the incoming request. This will stop login CSRF. """ self._check_bad_or_missing_cookie(None, REASON_NO_CSRF_COOKIE) def _check_bad_or_missing_token( self, expected, post_token=None, meta_token=None, token_header=None, ): req = self._get_POST_csrf_cookie_request( post_token=post_token, meta_token=meta_token, token_header=token_header, ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertEqual(403, resp.status_code) self.assertEqual(resp["Content-Type"], "text/html; charset=utf-8") self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % expected) def test_csrf_cookie_bad_or_missing_token(self): """ If a CSRF cookie is present but the token is missing or invalid, the middleware rejects the incoming request. """ cases = [ (None, None, REASON_CSRF_TOKEN_MISSING), (16 * "a", None, "CSRF token from POST has incorrect length."), (64 * "*", None, "CSRF token from POST has invalid characters."), (64 * "a", None, "CSRF token from POST incorrect."), ( None, 16 * "a", "CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.", ), ( None, 64 * "*", "CSRF token from the 'X-Csrftoken' HTTP header has invalid characters.", ), ( None, 64 * "a", "CSRF token from the 'X-Csrftoken' HTTP header incorrect.", ), ] for post_token, meta_token, expected in cases: with self.subTest(post_token=post_token, meta_token=meta_token): self._check_bad_or_missing_token( expected, post_token=post_token, meta_token=meta_token, ) @override_settings(CSRF_HEADER_NAME="HTTP_X_CSRFTOKEN_CUSTOMIZED") def test_csrf_cookie_bad_token_custom_header(self): """ If a CSRF cookie is present and an invalid token is passed via a custom CSRF_HEADER_NAME, the middleware rejects the incoming request. """ expected = ( "CSRF token from the 'X-Csrftoken-Customized' HTTP header has " "incorrect length." ) self._check_bad_or_missing_token( expected, meta_token=16 * "a", token_header="HTTP_X_CSRFTOKEN_CUSTOMIZED", ) def test_process_request_csrf_cookie_and_token(self): """ If both a cookie and a token is present, the middleware lets it through. """ req = self._get_POST_request_with_token() mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def test_process_request_csrf_cookie_no_token_exempt_view(self): """ If a CSRF cookie is present and no token, but the csrf_exempt decorator has been applied to the view, the middleware lets it through """ req = self._get_POST_csrf_cookie_request() mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, csrf_exempt(post_form_view), (), {}) self.assertIsNone(resp) def test_csrf_token_in_header(self): """ The token may be passed in a header instead of in the form. """ req = self._get_POST_csrf_cookie_request(meta_token=self._csrf_id_token) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings(CSRF_HEADER_NAME="HTTP_X_CSRFTOKEN_CUSTOMIZED") def test_csrf_token_in_header_with_customized_name(self): """ settings.CSRF_HEADER_NAME can be used to customize the CSRF header name """ req = self._get_POST_csrf_cookie_request( meta_token=self._csrf_id_token, token_header="HTTP_X_CSRFTOKEN_CUSTOMIZED", ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def test_put_and_delete_rejected(self): """ HTTP PUT and DELETE methods have protection """ req = self._get_request(method="PUT") mw = CsrfViewMiddleware(post_form_view) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertEqual(403, resp.status_code) self.assertEqual( cm.records[0].getMessage(), "Forbidden (%s): " % REASON_NO_CSRF_COOKIE ) req = self._get_request(method="DELETE") with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertEqual(403, resp.status_code) self.assertEqual( cm.records[0].getMessage(), "Forbidden (%s): " % REASON_NO_CSRF_COOKIE ) def test_put_and_delete_allowed(self): """ HTTP PUT and DELETE can get through with X-CSRFToken and a cookie. """ req = self._get_csrf_cookie_request( method="PUT", meta_token=self._csrf_id_token ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) req = self._get_csrf_cookie_request( method="DELETE", meta_token=self._csrf_id_token ) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def test_rotate_token_triggers_second_reset(self): """ If rotate_token() is called after the token is reset in CsrfViewMiddleware's process_response() and before another call to the same process_response(), the cookie is reset a second time. """ req = self._get_POST_request_with_token() resp = sandwiched_rotate_token_view(req) self.assertContains(resp, "OK") actual_secret = self._read_csrf_cookie(req, resp) # set_cookie() was called a second time with a different secret. cookies_set = self._get_cookies_set(req, resp) # Only compare the last two to exclude a spurious entry that's present # when CsrfViewMiddlewareUseSessionsTests is running. self.assertEqual(cookies_set[-2:], [TEST_SECRET, actual_secret]) self.assertNotEqual(actual_secret, TEST_SECRET) # Tests for the template tag method def test_token_node_no_csrf_cookie(self): """ CsrfTokenNode works when no CSRF cookie is set. """ req = self._get_request() resp = token_view(req) token = get_token(req) self.assertIsNotNone(token) csrf_secret = _unmask_cipher_token(token) self._check_token_present(resp, csrf_secret) def test_token_node_empty_csrf_cookie(self): """ A new token is sent if the csrf_cookie is the empty string. """ req = self._get_request(cookie="") mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = token_view(req) token = get_token(req) self.assertIsNotNone(token) csrf_secret = _unmask_cipher_token(token) self._check_token_present(resp, csrf_secret) def test_token_node_with_csrf_cookie(self): """ CsrfTokenNode works when a CSRF cookie is set. """ req = self._get_csrf_cookie_request() mw = CsrfViewMiddleware(token_view) mw.process_request(req) mw.process_view(req, token_view, (), {}) resp = token_view(req) self._check_token_present(resp) def test_get_token_for_exempt_view(self): """ get_token still works for a view decorated with 'csrf_exempt'. """ req = self._get_csrf_cookie_request() mw = CsrfViewMiddleware(token_view) mw.process_request(req) mw.process_view(req, csrf_exempt(token_view), (), {}) resp = token_view(req) self._check_token_present(resp) def test_get_token_for_requires_csrf_token_view(self): """ get_token() works for a view decorated solely with requires_csrf_token. """ req = self._get_csrf_cookie_request() resp = requires_csrf_token(token_view)(req) self._check_token_present(resp) def test_token_node_with_new_csrf_cookie(self): """ CsrfTokenNode works when a CSRF cookie is created by the middleware (when one was not already present) """ req = self._get_request() mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self._check_token_present(resp, csrf_cookie) def test_cookie_not_reset_on_accepted_request(self): """ The csrf token used in posts is changed on every request (although stays equivalent). The csrf cookie should not change on accepted requests. If it appears in the response, it should keep its value. """ req = self._get_POST_request_with_token() mw = CsrfViewMiddleware(token_view) mw.process_request(req) mw.process_view(req, token_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual( csrf_cookie, TEST_SECRET, "CSRF cookie was changed on an accepted request", ) @override_settings(DEBUG=True, ALLOWED_HOSTS=["www.example.com"]) def test_https_bad_referer(self): """ A POST HTTPS request with a bad referer is rejected """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(post_form_view) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - https://www.evil.org/somepage does not " "match any trusted origins.", status_code=403, ) def _check_referer_rejects(self, mw, req): with self.assertRaises(RejectRequest): mw._check_referer(req) @override_settings(DEBUG=True) def test_https_no_referer(self): """A POST HTTPS request with a missing referer is rejected.""" req = self._get_POST_request_with_token() req._is_secure_override = True mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - no Referer.", status_code=403, ) def test_https_malformed_host(self): """ CsrfViewMiddleware generates a 403 response if it receives an HTTPS request with a bad host. """ req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://www.evil.org/somepage" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(token_view) expected = ( "Referer checking failed - https://www.evil.org/somepage does not " "match any trusted origins." ) with self.assertRaisesMessage(RejectRequest, expected): mw._check_referer(req) response = mw.process_view(req, token_view, (), {}) self.assertEqual(response.status_code, 403) def test_origin_malformed_host(self): req = self._get_request(method="POST") req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_ORIGIN"] = "https://www.evil.org" mw = CsrfViewMiddleware(token_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, token_view, (), {}) self.assertEqual(response.status_code, 403) @override_settings(DEBUG=True) def test_https_malformed_referer(self): """ A POST HTTPS request with a bad referer is rejected. """ malformed_referer_msg = "Referer checking failed - Referer is malformed." req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "http://http://www.example.com/" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - Referer is insecure while host is secure.", status_code=403, ) # Empty req.META["HTTP_REFERER"] = "" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # Non-ASCII req.META["HTTP_REFERER"] = "ØBöIß" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # missing scheme # >>> urlparse('//example.com/') # ParseResult( # scheme='', netloc='example.com', path='/', params='', query='', fragment='', # ) req.META["HTTP_REFERER"] = "//example.com/" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # missing netloc # >>> urlparse('https://') # ParseResult( # scheme='https', netloc='', path='', params='', query='', fragment='', # ) req.META["HTTP_REFERER"] = "https://" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) # Invalid URL # >>> urlparse('https://[') # ValueError: Invalid IPv6 URL req.META["HTTP_REFERER"] = "https://[" self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains(response, malformed_referer_msg, status_code=403) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_https_good_referer(self): """ A POST HTTPS request with a good referer is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://www.example.com/somepage" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_https_good_referer_2(self): """ A POST HTTPS request with a good referer is accepted where the referer contains no trailing slash. """ # See ticket #15617 req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://www.example.com" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) def _test_https_good_referer_behind_proxy(self): req = self._get_POST_request_with_token() req._is_secure_override = True req.META.update( { "HTTP_HOST": "10.0.0.2", "HTTP_REFERER": "https://www.example.com/somepage", "SERVER_PORT": "8080", "HTTP_X_FORWARDED_HOST": "www.example.com", "HTTP_X_FORWARDED_PORT": "443", } ) mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings(CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"]) def test_https_good_referer_malformed_host(self): """ A POST HTTPS request is accepted if it receives a good referer with a bad host. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "@malformed" req.META["HTTP_REFERER"] = "https://dashboard.example.com/somepage" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"], ) def test_https_csrf_trusted_origin_allowed(self): """ A POST HTTPS request with a referer added to the CSRF_TRUSTED_ORIGINS setting is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://dashboard.example.com" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=["https://*.example.com"], ) def test_https_csrf_wildcard_trusted_origin_allowed(self): """ A POST HTTPS request with a referer that matches a CSRF_TRUSTED_ORIGINS wildcard is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://dashboard.example.com" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) def _test_https_good_referer_matches_cookie_domain(self): req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "https://foo.example.com/" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) def _test_https_good_referer_matches_cookie_domain_with_different_port(self): req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_REFERER"] = "https://foo.example.com:4443/" req.META["SERVER_PORT"] = "4443" mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) def test_ensures_csrf_cookie_no_logging(self): """ ensure_csrf_cookie() doesn't log warnings (#19436). """ with self.assertNoLogs("django.request", "WARNING"): req = self._get_request() ensure_csrf_cookie_view(req) def test_reading_post_data_raises_unreadable_post_error(self): """ An UnreadablePostError raised while reading the POST data should be handled by the middleware. """ req = self._get_POST_request_with_token() mw = CsrfViewMiddleware(post_form_view) mw.process_request(req) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) req = self._get_POST_request_with_token(request_class=PostErrorRequest) req.post_error = UnreadablePostError("Error reading input data.") mw.process_request(req) with self.assertLogs("django.security.csrf", "WARNING") as cm: resp = mw.process_view(req, post_form_view, (), {}) self.assertEqual(resp.status_code, 403) self.assertEqual( cm.records[0].getMessage(), "Forbidden (%s): " % REASON_CSRF_TOKEN_MISSING, ) def test_reading_post_data_raises_os_error(self): """ An OSError raised while reading the POST data should not be handled by the middleware. """ mw = CsrfViewMiddleware(post_form_view) req = self._get_POST_request_with_token(request_class=PostErrorRequest) req.post_error = OSError("Deleted directories/Missing permissions.") mw.process_request(req) with self.assertRaises(OSError): mw.process_view(req, post_form_view, (), {}) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_bad_origin_bad_domain(self): """A request with a bad origin is rejected.""" req = self._get_POST_request_with_token() req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "https://www.evil.org" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) self.assertIs(mw._origin_verified(req), False) with self.assertLogs("django.security.csrf", "WARNING") as cm: response = mw.process_view(req, post_form_view, (), {}) self.assertEqual(response.status_code, 403) msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % msg) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_bad_origin_null_origin(self): """A request with a null origin is rejected.""" req = self._get_POST_request_with_token() req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "null" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) self.assertIs(mw._origin_verified(req), False) with self.assertLogs("django.security.csrf", "WARNING") as cm: response = mw.process_view(req, post_form_view, (), {}) self.assertEqual(response.status_code, 403) msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % msg) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_bad_origin_bad_protocol(self): """A request with an origin with wrong protocol is rejected.""" req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "http://example.com" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) self.assertIs(mw._origin_verified(req), False) with self.assertLogs("django.security.csrf", "WARNING") as cm: response = mw.process_view(req, post_form_view, (), {}) self.assertEqual(response.status_code, 403) msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % msg) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=[ "http://no-match.com", "https://*.example.com", "http://*.no-match.com", "http://*.no-match-2.com", ], ) def test_bad_origin_csrf_trusted_origin_bad_protocol(self): """ A request with an origin with the wrong protocol compared to CSRF_TRUSTED_ORIGINS is rejected. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "http://foo.example.com" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) self.assertIs(mw._origin_verified(req), False) with self.assertLogs("django.security.csrf", "WARNING") as cm: response = mw.process_view(req, post_form_view, (), {}) self.assertEqual(response.status_code, 403) msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % msg) self.assertEqual(mw.allowed_origins_exact, {"http://no-match.com"}) self.assertEqual( mw.allowed_origin_subdomains, { "https": [".example.com"], "http": [".no-match.com", ".no-match-2.com"], }, ) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_bad_origin_cannot_be_parsed(self): """ A POST request with an origin that can't be parsed by urlparse() is rejected. """ req = self._get_POST_request_with_token() req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "https://[" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) self.assertIs(mw._origin_verified(req), False) with self.assertLogs("django.security.csrf", "WARNING") as cm: response = mw.process_view(req, post_form_view, (), {}) self.assertEqual(response.status_code, 403) msg = REASON_BAD_ORIGIN % req.META["HTTP_ORIGIN"] self.assertEqual(cm.records[0].getMessage(), "Forbidden (%s): " % msg) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_good_origin_insecure(self): """A POST HTTP request with a good origin is accepted.""" req = self._get_POST_request_with_token() req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "http://www.example.com" mw = CsrfViewMiddleware(post_form_view) self.assertIs(mw._origin_verified(req), True) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) @override_settings(ALLOWED_HOSTS=["www.example.com"]) def test_good_origin_secure(self): """A POST HTTPS request with a good origin is accepted.""" req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "https://www.example.com" mw = CsrfViewMiddleware(post_form_view) self.assertIs(mw._origin_verified(req), True) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=["https://dashboard.example.com"], ) def test_good_origin_csrf_trusted_origin_allowed(self): """ A POST request with an origin added to the CSRF_TRUSTED_ORIGINS setting is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "https://dashboard.example.com" mw = CsrfViewMiddleware(post_form_view) self.assertIs(mw._origin_verified(req), True) resp = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(resp) self.assertEqual(mw.allowed_origins_exact, {"https://dashboard.example.com"}) self.assertEqual(mw.allowed_origin_subdomains, {}) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_TRUSTED_ORIGINS=["https://*.example.com"], ) def test_good_origin_wildcard_csrf_trusted_origin_allowed(self): """ A POST request with an origin that matches a CSRF_TRUSTED_ORIGINS wildcard is accepted. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_HOST"] = "www.example.com" req.META["HTTP_ORIGIN"] = "https://foo.example.com" mw = CsrfViewMiddleware(post_form_view) self.assertIs(mw._origin_verified(req), True) response = mw.process_view(req, post_form_view, (), {}) self.assertIsNone(response) self.assertEqual(mw.allowed_origins_exact, set()) self.assertEqual(mw.allowed_origin_subdomains, {"https": [".example.com"]}) class CsrfViewMiddlewareTests(CsrfViewMiddlewareTestMixin, SimpleTestCase): def _set_csrf_cookie(self, req, cookie): req.COOKIES[settings.CSRF_COOKIE_NAME] = cookie def _read_csrf_cookie(self, req, resp): """ Return the CSRF cookie as a string, or False if no cookie is present. """ if settings.CSRF_COOKIE_NAME not in resp.cookies: return False csrf_cookie = resp.cookies[settings.CSRF_COOKIE_NAME] return csrf_cookie.value def _get_cookies_set(self, req, resp): return resp._cookies_set def test_ensures_csrf_cookie_no_middleware(self): """ The ensure_csrf_cookie() decorator works without middleware. """ req = self._get_request() resp = ensure_csrf_cookie_view(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertTrue(csrf_cookie) self.assertIn("Cookie", resp.get("Vary", "")) def test_ensures_csrf_cookie_with_middleware(self): """ The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware enabled. """ req = self._get_request() mw = CsrfViewMiddleware(ensure_csrf_cookie_view) mw.process_view(req, ensure_csrf_cookie_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertTrue(csrf_cookie) self.assertIn("Cookie", resp.get("Vary", "")) def test_csrf_cookie_age(self): """ CSRF cookie age can be set using settings.CSRF_COOKIE_AGE. """ req = self._get_request() MAX_AGE = 123 with self.settings( CSRF_COOKIE_NAME="csrfcookie", CSRF_COOKIE_DOMAIN=".example.com", CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH="/test/", CSRF_COOKIE_SECURE=True, CSRF_COOKIE_HTTPONLY=True, ): # token_view calls get_token() indirectly mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) max_age = resp.cookies.get("csrfcookie").get("max-age") self.assertEqual(max_age, MAX_AGE) def test_csrf_cookie_age_none(self): """ CSRF cookie age does not have max age set and therefore uses session-based cookies. """ req = self._get_request() MAX_AGE = None with self.settings( CSRF_COOKIE_NAME="csrfcookie", CSRF_COOKIE_DOMAIN=".example.com", CSRF_COOKIE_AGE=MAX_AGE, CSRF_COOKIE_PATH="/test/", CSRF_COOKIE_SECURE=True, CSRF_COOKIE_HTTPONLY=True, ): # token_view calls get_token() indirectly mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) max_age = resp.cookies.get("csrfcookie").get("max-age") self.assertEqual(max_age, "") def test_csrf_cookie_samesite(self): req = self._get_request() with self.settings( CSRF_COOKIE_NAME="csrfcookie", CSRF_COOKIE_SAMESITE="Strict" ): mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) self.assertEqual(resp.cookies["csrfcookie"]["samesite"], "Strict") def test_bad_csrf_cookie_characters(self): """ If the CSRF cookie has invalid characters in a POST request, the middleware rejects the incoming request. """ self._check_bad_or_missing_cookie( 64 * "*", "CSRF cookie has invalid characters." ) def test_bad_csrf_cookie_length(self): """ If the CSRF cookie has an incorrect length in a POST request, the middleware rejects the incoming request. """ self._check_bad_or_missing_cookie(16 * "a", "CSRF cookie has incorrect length.") def test_process_view_token_too_long(self): """ If the token is longer than expected, it is ignored and a new token is created. """ req = self._get_request(cookie="x" * 100000) mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual(len(csrf_cookie), CSRF_SECRET_LENGTH) def test_process_view_token_invalid_chars(self): """ If the token contains non-alphanumeric characters, it is ignored and a new token is created. """ token = ("!@#" + self._csrf_id_token)[:CSRF_TOKEN_LENGTH] req = self._get_request(cookie=token) mw = CsrfViewMiddleware(token_view) mw.process_view(req, token_view, (), {}) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual(len(csrf_cookie), CSRF_SECRET_LENGTH) self.assertNotEqual(csrf_cookie, token) def test_masked_unmasked_combinations(self): """ All combinations are allowed of (1) masked and unmasked cookies, (2) masked and unmasked tokens, and (3) tokens provided via POST and the X-CSRFToken header. """ cases = [ (TEST_SECRET, TEST_SECRET, None), (TEST_SECRET, MASKED_TEST_SECRET2, None), (TEST_SECRET, None, TEST_SECRET), (TEST_SECRET, None, MASKED_TEST_SECRET2), (MASKED_TEST_SECRET1, TEST_SECRET, None), (MASKED_TEST_SECRET1, MASKED_TEST_SECRET2, None), (MASKED_TEST_SECRET1, None, TEST_SECRET), (MASKED_TEST_SECRET1, None, MASKED_TEST_SECRET2), ] for args in cases: with self.subTest(args=args): cookie, post_token, meta_token = args req = self._get_POST_csrf_cookie_request( cookie=cookie, post_token=post_token, meta_token=meta_token, ) mw = CsrfViewMiddleware(token_view) mw.process_request(req) resp = mw.process_view(req, token_view, (), {}) self.assertIsNone(resp) def test_set_cookie_called_only_once(self): """ set_cookie() is called only once when the view is decorated with both ensure_csrf_cookie and csrf_protect. """ req = self._get_POST_request_with_token() resp = ensured_and_protected_view(req) self.assertContains(resp, "OK") csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual(csrf_cookie, TEST_SECRET) # set_cookie() was called only once and with the expected secret. cookies_set = self._get_cookies_set(req, resp) self.assertEqual(cookies_set, [TEST_SECRET]) def test_invalid_cookie_replaced_on_GET(self): """ A CSRF cookie with the wrong format is replaced during a GET request. """ req = self._get_request(cookie="badvalue") resp = protected_view(req) self.assertContains(resp, "OK") csrf_cookie = self._read_csrf_cookie(req, resp) self.assertTrue(csrf_cookie, msg="No CSRF cookie was sent.") self.assertEqual(len(csrf_cookie), CSRF_SECRET_LENGTH) def test_valid_secret_not_replaced_on_GET(self): """ Masked and unmasked CSRF cookies are not replaced during a GET request. """ cases = [ TEST_SECRET, MASKED_TEST_SECRET1, ] for cookie in cases: with self.subTest(cookie=cookie): req = self._get_request(cookie=cookie) resp = protected_view(req) self.assertContains(resp, "OK") csrf_cookie = self._read_csrf_cookie(req, resp) self.assertFalse(csrf_cookie, msg="A CSRF cookie was sent.") def test_masked_secret_accepted_and_replaced(self): """ For a view that uses the csrf_token, the csrf cookie is replaced with the unmasked version if originally masked. """ req = self._get_POST_request_with_token(cookie=MASKED_TEST_SECRET1) mw = CsrfViewMiddleware(token_view) mw.process_request(req) resp = mw.process_view(req, token_view, (), {}) self.assertIsNone(resp) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual(csrf_cookie, TEST_SECRET) self._check_token_present(resp, csrf_cookie) def test_bare_secret_accepted_and_not_replaced(self): """ The csrf cookie is left unchanged if originally not masked. """ req = self._get_POST_request_with_token(cookie=TEST_SECRET) mw = CsrfViewMiddleware(token_view) mw.process_request(req) resp = mw.process_view(req, token_view, (), {}) self.assertIsNone(resp) resp = mw(req) csrf_cookie = self._read_csrf_cookie(req, resp) self.assertEqual(csrf_cookie, TEST_SECRET) self._check_token_present(resp, csrf_cookie) @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_COOKIE_DOMAIN=".example.com", USE_X_FORWARDED_PORT=True, ) def test_https_good_referer_behind_proxy(self): """ A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True. """ self._test_https_good_referer_behind_proxy() @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_COOKIE_DOMAIN=".example.com" ) def test_https_good_referer_matches_cookie_domain(self): """ A POST HTTPS request with a good referer should be accepted from a subdomain that's allowed by CSRF_COOKIE_DOMAIN. """ self._test_https_good_referer_matches_cookie_domain() @override_settings( ALLOWED_HOSTS=["www.example.com"], CSRF_COOKIE_DOMAIN=".example.com" ) def test_https_good_referer_matches_cookie_domain_with_different_port(self): """ A POST HTTPS request with a good referer should be accepted from a subdomain that's allowed by CSRF_COOKIE_DOMAIN and a non-443 port. """ self._test_https_good_referer_matches_cookie_domain_with_different_port() @override_settings(CSRF_COOKIE_DOMAIN=".example.com", DEBUG=True) def test_https_reject_insecure_referer(self): """ A POST HTTPS request from an insecure referer should be rejected. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "http://example.com/" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(post_form_view) self._check_referer_rejects(mw, req) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - Referer is insecure while host is secure.", status_code=403, ) @override_settings(CSRF_USE_SESSIONS=True, CSRF_COOKIE_DOMAIN=None) class CsrfViewMiddlewareUseSessionsTests(CsrfViewMiddlewareTestMixin, SimpleTestCase): """ CSRF tests with CSRF_USE_SESSIONS=True. """ def _set_csrf_cookie(self, req, cookie): req.session[CSRF_SESSION_KEY] = cookie def _read_csrf_cookie(self, req, resp=None): """ Return the CSRF cookie as a string, or False if no cookie is present. """ if CSRF_SESSION_KEY not in req.session: return False return req.session[CSRF_SESSION_KEY] def _get_cookies_set(self, req, resp): return req.session._cookies_set def test_no_session_on_request(self): msg = ( "CSRF_USE_SESSIONS is enabled, but request.session is not set. " "SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): mw = CsrfViewMiddleware(lambda req: HttpResponse()) mw.process_request(HttpRequest()) def test_masked_unmasked_combinations(self): """ Masked and unmasked tokens are allowed both as POST and as the X-CSRFToken header. """ cases = [ # Bare secrets are not allowed when CSRF_USE_SESSIONS=True. (MASKED_TEST_SECRET1, TEST_SECRET, None), (MASKED_TEST_SECRET1, MASKED_TEST_SECRET2, None), (MASKED_TEST_SECRET1, None, TEST_SECRET), (MASKED_TEST_SECRET1, None, MASKED_TEST_SECRET2), ] for args in cases: with self.subTest(args=args): cookie, post_token, meta_token = args req = self._get_POST_csrf_cookie_request( cookie=cookie, post_token=post_token, meta_token=meta_token, ) mw = CsrfViewMiddleware(token_view) mw.process_request(req) resp = mw.process_view(req, token_view, (), {}) self.assertIsNone(resp) def test_process_response_get_token_used(self): """The ensure_csrf_cookie() decorator works without middleware.""" req = self._get_request() ensure_csrf_cookie_view(req) csrf_cookie = self._read_csrf_cookie(req) self.assertTrue(csrf_cookie) def test_session_modify(self): """The session isn't saved if the CSRF cookie is unchanged.""" req = self._get_request() mw = CsrfViewMiddleware(ensure_csrf_cookie_view) mw.process_view(req, ensure_csrf_cookie_view, (), {}) mw(req) csrf_cookie = self._read_csrf_cookie(req) self.assertTrue(csrf_cookie) req.session.modified = False mw.process_view(req, ensure_csrf_cookie_view, (), {}) mw(req) self.assertFalse(req.session.modified) def test_ensures_csrf_cookie_with_middleware(self): """ The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware enabled. """ req = self._get_request() mw = CsrfViewMiddleware(ensure_csrf_cookie_view) mw.process_view(req, ensure_csrf_cookie_view, (), {}) mw(req) csrf_cookie = self._read_csrf_cookie(req) self.assertTrue(csrf_cookie) @override_settings( ALLOWED_HOSTS=["www.example.com"], SESSION_COOKIE_DOMAIN=".example.com", USE_X_FORWARDED_PORT=True, DEBUG=True, ) def test_https_good_referer_behind_proxy(self): """ A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True. """ self._test_https_good_referer_behind_proxy() @override_settings( ALLOWED_HOSTS=["www.example.com"], SESSION_COOKIE_DOMAIN=".example.com" ) def test_https_good_referer_matches_cookie_domain(self): """ A POST HTTPS request with a good referer should be accepted from a subdomain that's allowed by SESSION_COOKIE_DOMAIN. """ self._test_https_good_referer_matches_cookie_domain() @override_settings( ALLOWED_HOSTS=["www.example.com"], SESSION_COOKIE_DOMAIN=".example.com" ) def test_https_good_referer_matches_cookie_domain_with_different_port(self): """ A POST HTTPS request with a good referer should be accepted from a subdomain that's allowed by SESSION_COOKIE_DOMAIN and a non-443 port. """ self._test_https_good_referer_matches_cookie_domain_with_different_port() @override_settings(SESSION_COOKIE_DOMAIN=".example.com", DEBUG=True) def test_https_reject_insecure_referer(self): """ A POST HTTPS request from an insecure referer should be rejected. """ req = self._get_POST_request_with_token() req._is_secure_override = True req.META["HTTP_REFERER"] = "http://example.com/" req.META["SERVER_PORT"] = "443" mw = CsrfViewMiddleware(post_form_view) response = mw.process_view(req, post_form_view, (), {}) self.assertContains( response, "Referer checking failed - Referer is insecure while host is secure.", status_code=403, ) @override_settings(ROOT_URLCONF="csrf_tests.csrf_token_error_handler_urls", DEBUG=False) class CsrfInErrorHandlingViewsTests(CsrfFunctionTestMixin, SimpleTestCase): def test_csrf_token_on_404_stays_constant(self): response = self.client.get("/does not exist/") # The error handler returns status code 599. self.assertEqual(response.status_code, 599) token1 = response.content.decode("ascii") response = self.client.get("/does not exist/") self.assertEqual(response.status_code, 599) token2 = response.content.decode("ascii") secret2 = _unmask_cipher_token(token2) self.assertMaskedSecretCorrect(token1, secret2)
08c7ad7216ffc861d48899390c8a8f6c0d132639c8353f2b27816675a42daa96
import os import unittest import warnings from io import StringIO from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.finders import get_finder, get_finders from django.contrib.staticfiles.storage import staticfiles_storage from django.core.exceptions import ImproperlyConfigured from django.core.files.storage import default_storage from django.db import ( IntegrityError, connection, connections, models, router, transaction, ) from django.forms import ( CharField, EmailField, Form, IntegerField, ValidationError, formset_factory, ) from django.http import HttpResponse from django.template.loader import render_to_string from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.html import HTMLParseError, parse_html from django.test.testcases import DatabaseOperationForbidden from django.test.utils import ( CaptureQueriesContext, TestContextDecorator, ignore_warnings, isolate_apps, override_settings, setup_test_environment, ) from django.urls import NoReverseMatch, path, reverse, reverse_lazy from django.utils.deprecation import RemovedInDjango51Warning from django.utils.version import PY311 from .models import Car, Person, PossessedCar from .views import empty_response class SkippingTestCase(SimpleTestCase): def _assert_skipping(self, func, expected_exc, msg=None): try: if msg is not None: with self.assertRaisesMessage(expected_exc, msg): func() else: with self.assertRaises(expected_exc): func() except unittest.SkipTest: self.fail("%s should not result in a skipped test." % func.__name__) def test_skip_unless_db_feature(self): """ Testing the django.test.skipUnlessDBFeature decorator. """ # Total hack, but it works, just want an attribute that's always true. @skipUnlessDBFeature("__class__") def test_func(): raise ValueError @skipUnlessDBFeature("notprovided") def test_func2(): raise ValueError @skipUnlessDBFeature("__class__", "__class__") def test_func3(): raise ValueError @skipUnlessDBFeature("__class__", "notprovided") def test_func4(): raise ValueError self._assert_skipping(test_func, ValueError) self._assert_skipping(test_func2, unittest.SkipTest) self._assert_skipping(test_func3, ValueError) self._assert_skipping(test_func4, unittest.SkipTest) class SkipTestCase(SimpleTestCase): @skipUnlessDBFeature("missing") def test_foo(self): pass self._assert_skipping( SkipTestCase("test_foo").test_foo, ValueError, "skipUnlessDBFeature cannot be used on test_foo (test_utils.tests." "SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase%s) " "as SkippingTestCase.test_skip_unless_db_feature.<locals>.SkipTestCase " "doesn't allow queries against the 'default' database." # Python 3.11 uses fully qualified test name in the output. % (".test_foo" if PY311 else ""), ) def test_skip_if_db_feature(self): """ Testing the django.test.skipIfDBFeature decorator. """ @skipIfDBFeature("__class__") def test_func(): raise ValueError @skipIfDBFeature("notprovided") def test_func2(): raise ValueError @skipIfDBFeature("__class__", "__class__") def test_func3(): raise ValueError @skipIfDBFeature("__class__", "notprovided") def test_func4(): raise ValueError @skipIfDBFeature("notprovided", "notprovided") def test_func5(): raise ValueError self._assert_skipping(test_func, unittest.SkipTest) self._assert_skipping(test_func2, ValueError) self._assert_skipping(test_func3, unittest.SkipTest) self._assert_skipping(test_func4, unittest.SkipTest) self._assert_skipping(test_func5, ValueError) class SkipTestCase(SimpleTestCase): @skipIfDBFeature("missing") def test_foo(self): pass self._assert_skipping( SkipTestCase("test_foo").test_foo, ValueError, "skipIfDBFeature cannot be used on test_foo (test_utils.tests." "SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase%s) " "as SkippingTestCase.test_skip_if_db_feature.<locals>.SkipTestCase " "doesn't allow queries against the 'default' database." # Python 3.11 uses fully qualified test name in the output. % (".test_foo" if PY311 else ""), ) class SkippingClassTestCase(TestCase): def test_skip_class_unless_db_feature(self): @skipUnlessDBFeature("__class__") class NotSkippedTests(TestCase): def test_dummy(self): return @skipUnlessDBFeature("missing") @skipIfDBFeature("__class__") class SkippedTests(TestCase): def test_will_be_skipped(self): self.fail("We should never arrive here.") @skipIfDBFeature("__dict__") class SkippedTestsSubclass(SkippedTests): pass test_suite = unittest.TestSuite() test_suite.addTest(NotSkippedTests("test_dummy")) try: test_suite.addTest(SkippedTests("test_will_be_skipped")) test_suite.addTest(SkippedTestsSubclass("test_will_be_skipped")) except unittest.SkipTest: self.fail("SkipTest should not be raised here.") result = unittest.TextTestRunner(stream=StringIO()).run(test_suite) self.assertEqual(result.testsRun, 3) self.assertEqual(len(result.skipped), 2) self.assertEqual(result.skipped[0][1], "Database has feature(s) __class__") self.assertEqual(result.skipped[1][1], "Database has feature(s) __class__") def test_missing_default_databases(self): @skipIfDBFeature("missing") class MissingDatabases(SimpleTestCase): def test_assertion_error(self): pass suite = unittest.TestSuite() try: suite.addTest(MissingDatabases("test_assertion_error")) except unittest.SkipTest: self.fail("SkipTest should not be raised at this stage") runner = unittest.TextTestRunner(stream=StringIO()) msg = ( "skipIfDBFeature cannot be used on <class 'test_utils.tests." "SkippingClassTestCase.test_missing_default_databases.<locals>." "MissingDatabases'> as it doesn't allow queries against the " "'default' database." ) with self.assertRaisesMessage(ValueError, msg): runner.run(suite) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertNumQueriesTests(TestCase): def test_assert_num_queries(self): def test_func(): raise ValueError with 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 AssertNumQueriesUponConnectionTests(TransactionTestCase): available_apps = [] def test_ignores_connection_configuration_queries(self): real_ensure_connection = connection.ensure_connection connection.close() def make_configuration_query(): is_opening_connection = connection.connection is None real_ensure_connection() if is_opening_connection: # Avoid infinite recursion. Creating a cursor calls # ensure_connection() which is currently mocked by this method. with connection.cursor() as cursor: cursor.execute("SELECT 1" + connection.features.bare_select_suffix) ensure_connection = ( "django.db.backends.base.base.BaseDatabaseWrapper.ensure_connection" ) with mock.patch(ensure_connection, side_effect=make_configuration_query): with self.assertNumQueries(1): list(Car.objects.all()) class AssertQuerySetEqualTests(TestCase): @classmethod def setUpTestData(cls): cls.p1 = Person.objects.create(name="p1") cls.p2 = Person.objects.create(name="p2") def test_rename_assertquerysetequal_deprecation_warning(self): msg = "assertQuerysetEqual() is deprecated in favor of assertQuerySetEqual()." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): self.assertQuerysetEqual() @ignore_warnings(category=RemovedInDjango51Warning) def test_deprecated_assertquerysetequal(self): self.assertQuerysetEqual(Person.objects.filter(name="p3"), []) def test_empty(self): self.assertQuerySetEqual(Person.objects.filter(name="p3"), []) def test_ordered(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [self.p1, self.p2], ) def test_unordered(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [self.p2, self.p1], ordered=False ) def test_queryset(self): self.assertQuerySetEqual( Person.objects.order_by("name"), Person.objects.order_by("name"), ) def test_flat_values_list(self): self.assertQuerySetEqual( Person.objects.order_by("name").values_list("name", flat=True), ["p1", "p2"], ) def test_transform(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [self.p1.pk, self.p2.pk], transform=lambda x: x.pk, ) def test_repr_transform(self): self.assertQuerySetEqual( Person.objects.order_by("name"), [repr(self.p1), repr(self.p2)], transform=repr, ) def test_undefined_order(self): # Using an unordered queryset with more than one ordered value # is an error. msg = ( "Trying to compare non-ordered queryset against more than one " "ordered value." ) with self.assertRaisesMessage(ValueError, msg): self.assertQuerySetEqual( Person.objects.all(), [self.p1, self.p2], ) # No error for one value. self.assertQuerySetEqual(Person.objects.filter(name="p1"), [self.p1]) def test_repeated_values(self): """ assertQuerySetEqual checks the number of appearance of each item when used with option ordered=False. """ batmobile = Car.objects.create(name="Batmobile") k2000 = Car.objects.create(name="K 2000") PossessedCar.objects.bulk_create( [ PossessedCar(car=batmobile, belongs_to=self.p1), PossessedCar(car=batmobile, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), PossessedCar(car=k2000, belongs_to=self.p1), ] ) with self.assertRaises(AssertionError): self.assertQuerySetEqual( self.p1.cars.all(), [batmobile, k2000], ordered=False ) self.assertQuerySetEqual( self.p1.cars.all(), [batmobile] * 2 + [k2000] * 4, ordered=False ) def test_maxdiff(self): names = ["Joe Smith %s" % i for i in range(20)] Person.objects.bulk_create([Person(name=name) for name in names]) names.append("Extra Person") with self.assertRaises(AssertionError) as ctx: self.assertQuerySetEqual( Person.objects.filter(name__startswith="Joe"), names, ordered=False, transform=lambda p: p.name, ) self.assertIn("Set self.maxDiff to None to see it.", str(ctx.exception)) original = self.maxDiff self.maxDiff = None try: with self.assertRaises(AssertionError) as ctx: self.assertQuerySetEqual( Person.objects.filter(name__startswith="Joe"), names, ordered=False, transform=lambda p: p.name, ) finally: self.maxDiff = original exception_msg = str(ctx.exception) self.assertNotIn("Set self.maxDiff to None to see it.", exception_msg) for name in names: self.assertIn(name, exception_msg) @override_settings(ROOT_URLCONF="test_utils.urls") class CaptureQueriesContextManagerTests(TestCase): @classmethod def setUpTestData(cls): cls.person_pk = str(Person.objects.create(name="test").pk) def test_simple(self): with CaptureQueriesContext(connection) as captured_queries: Person.objects.get(pk=self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) with CaptureQueriesContext(connection) as captured_queries: pass self.assertEqual(0, len(captured_queries)) def test_within(self): with CaptureQueriesContext(connection) as captured_queries: Person.objects.get(pk=self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) def test_nested(self): with CaptureQueriesContext(connection) as captured_queries: Person.objects.count() with CaptureQueriesContext(connection) as nested_captured_queries: Person.objects.count() self.assertEqual(1, len(nested_captured_queries)) self.assertEqual(2, len(captured_queries)) def test_failure(self): with self.assertRaises(TypeError): with CaptureQueriesContext(connection): raise TypeError def test_with_client(self): with CaptureQueriesContext(connection) as captured_queries: self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) with CaptureQueriesContext(connection) as captured_queries: self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.assertEqual(len(captured_queries), 1) self.assertIn(self.person_pk, captured_queries[0]["sql"]) with CaptureQueriesContext(connection) as captured_queries: self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.client.get("/test_utils/get_person/%s/" % self.person_pk) self.assertEqual(len(captured_queries), 2) self.assertIn(self.person_pk, captured_queries[0]["sql"]) self.assertIn(self.person_pk, captured_queries[1]["sql"]) @override_settings(ROOT_URLCONF="test_utils.urls") 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): msg = "1 != 2 : 1 queries executed, 2 expected\nCaptured queries were:\n1." with self.assertRaisesMessage(AssertionError, msg): with self.assertNumQueries(2): Person.objects.count() 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) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertTemplateUsedContextManagerTests(SimpleTestCase): def test_usage(self): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/base.html") with self.assertTemplateUsed(template_name="template_used/base.html"): render_to_string("template_used/base.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/include.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/extends.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/base.html") render_to_string("template_used/base.html") def test_nested_usage(self): with self.assertTemplateUsed("template_used/base.html"): with self.assertTemplateUsed("template_used/include.html"): render_to_string("template_used/include.html") with self.assertTemplateUsed("template_used/extends.html"): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/extends.html") with self.assertTemplateUsed("template_used/base.html"): with self.assertTemplateUsed("template_used/alternative.html"): render_to_string("template_used/alternative.html") render_to_string("template_used/base.html") with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/extends.html") with self.assertTemplateNotUsed("template_used/base.html"): render_to_string("template_used/alternative.html") render_to_string("template_used/base.html") def test_not_used(self): with self.assertTemplateNotUsed("template_used/base.html"): pass with self.assertTemplateNotUsed("template_used/alternative.html"): pass def test_error_message(self): msg = "No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed("template_used/base.html"): pass with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(template_name="template_used/base.html"): pass msg2 = ( "Template 'template_used/base.html' was not a template used to render " "the response. Actual template(s) used: template_used/alternative.html" ) with self.assertRaisesMessage(AssertionError, msg2): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/alternative.html") with self.assertRaisesMessage( AssertionError, "No templates used to render the response" ): response = self.client.get("/test_utils/no_template_used/") self.assertTemplateUsed(response, "template_used/base.html") def test_msg_prefix(self): msg_prefix = "Prefix" msg = f"{msg_prefix}: No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed( "template_used/base.html", msg_prefix=msg_prefix ): pass with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed( template_name="template_used/base.html", msg_prefix=msg_prefix, ): pass msg = ( f"{msg_prefix}: Template 'template_used/base.html' was not a " f"template used to render the response. Actual template(s) used: " f"template_used/alternative.html" ) with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed( "template_used/base.html", msg_prefix=msg_prefix ): render_to_string("template_used/alternative.html") def test_count(self): with self.assertTemplateUsed("template_used/base.html", count=2): render_to_string("template_used/base.html") render_to_string("template_used/base.html") msg = ( "Template 'template_used/base.html' was expected to be rendered " "3 time(s) but was actually rendered 2 time(s)." ) with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed("template_used/base.html", count=3): render_to_string("template_used/base.html") render_to_string("template_used/base.html") def test_failure(self): msg = "response and/or template_name argument must be provided" with self.assertRaisesMessage(TypeError, msg): with self.assertTemplateUsed(): pass msg = "No templates used to render the response" with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(""): pass with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(""): render_to_string("template_used/base.html") with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed(template_name=""): pass msg = ( "Template 'template_used/base.html' was not a template used to " "render the response. Actual template(s) used: " "template_used/alternative.html" ) with self.assertRaisesMessage(AssertionError, msg): with self.assertTemplateUsed("template_used/base.html"): render_to_string("template_used/alternative.html") def test_assert_used_on_http_response(self): response = HttpResponse() msg = "%s() is only usable on responses fetched using the Django test Client." with self.assertRaisesMessage(ValueError, msg % "assertTemplateUsed"): self.assertTemplateUsed(response, "template.html") with self.assertRaisesMessage(ValueError, msg % "assertTemplateNotUsed"): self.assertTemplateNotUsed(response, "template.html") class HTMLEqualTests(SimpleTestCase): def test_html_parser(self): element = parse_html("<div><p>Hello</p></div>") self.assertEqual(len(element.children), 1) self.assertEqual(element.children[0].name, "p") self.assertEqual(element.children[0].children[0], "Hello") parse_html("<p>") parse_html("<p attr>") dom = parse_html("<p>foo") self.assertEqual(len(dom.children), 1) self.assertEqual(dom.name, "p") self.assertEqual(dom[0], "foo") def test_parse_html_in_script(self): parse_html('<script>var a = "<p" + ">";</script>') parse_html( """ <script> var js_sha_link='<p>***</p>'; </script> """ ) # script content will be parsed to text dom = parse_html( """ <script><p>foo</p> '</scr'+'ipt>' <span>bar</span></script> """ ) self.assertEqual(len(dom.children), 1) self.assertEqual(dom.children[0], "<p>foo</p> '</scr'+'ipt>' <span>bar</span>") def test_self_closing_tags(self): self_closing_tags = [ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", # Deprecated tags "frame", "spacer", ] for tag in self_closing_tags: with self.subTest(tag): dom = parse_html("<p>Hello <%s> world</p>" % tag) self.assertEqual(len(dom.children), 3) self.assertEqual(dom[0], "Hello") self.assertEqual(dom[1].name, tag) self.assertEqual(dom[2], "world") dom = parse_html("<p>Hello <%s /> world</p>" % tag) self.assertEqual(len(dom.children), 3) self.assertEqual(dom[0], "Hello") self.assertEqual(dom[1].name, tag) self.assertEqual(dom[2], "world") def test_simple_equal_html(self): self.assertHTMLEqual("", "") self.assertHTMLEqual("<p></p>", "<p></p>") self.assertHTMLEqual("<p></p>", " <p> </p> ") self.assertHTMLEqual("<div><p>Hello</p></div>", "<div><p>Hello</p></div>") self.assertHTMLEqual("<div><p>Hello</p></div>", "<div> <p>Hello</p> </div>") self.assertHTMLEqual("<div>\n<p>Hello</p></div>", "<div><p>Hello</p></div>\n") self.assertHTMLEqual( "<div><p>Hello\nWorld !</p></div>", "<div><p>Hello World\n!</p></div>" ) self.assertHTMLEqual( "<div><p>Hello\nWorld !</p></div>", "<div><p>Hello World\n!</p></div>" ) self.assertHTMLEqual("<p>Hello World !</p>", "<p>Hello World\n\n!</p>") self.assertHTMLEqual("<p> </p>", "<p></p>") self.assertHTMLEqual("<p/>", "<p></p>") self.assertHTMLEqual("<p />", "<p></p>") self.assertHTMLEqual("<input checked>", '<input checked="checked">') self.assertHTMLEqual("<p>Hello", "<p> Hello") self.assertHTMLEqual("<p>Hello</p>World", "<p>Hello</p> World") def test_ignore_comments(self): self.assertHTMLEqual( "<div>Hello<!-- this is a comment --> World!</div>", "<div>Hello World!</div>", ) def test_unequal_html(self): self.assertHTMLNotEqual("<p>Hello</p>", "<p>Hello!</p>") self.assertHTMLNotEqual("<p>foo&#20;bar</p>", "<p>foo&nbsp;bar</p>") self.assertHTMLNotEqual("<p>foo bar</p>", "<p>foo &nbsp;bar</p>") self.assertHTMLNotEqual("<p>foo nbsp</p>", "<p>foo &nbsp;</p>") self.assertHTMLNotEqual("<p>foo #20</p>", "<p>foo &#20;</p>") self.assertHTMLNotEqual( "<p><span>Hello</span><span>World</span></p>", "<p><span>Hello</span>World</p>", ) self.assertHTMLNotEqual( "<p><span>Hello</span>World</p>", "<p><span>Hello</span><span>World</span></p>", ) def test_attributes(self): self.assertHTMLEqual( '<input type="text" id="id_name" />', '<input id="id_name" type="text" />' ) self.assertHTMLEqual( """<input type='text' id="id_name" />""", '<input id="id_name" type="text" />', ) self.assertHTMLNotEqual( '<input type="text" id="id_name" />', '<input type="password" id="id_name" />', ) def test_class_attribute(self): pairs = [ ('<p class="foo bar"></p>', '<p class="bar foo"></p>'), ('<p class=" foo bar "></p>', '<p class="bar foo"></p>'), ('<p class=" foo bar "></p>', '<p class="bar foo"></p>'), ('<p class="foo\tbar"></p>', '<p class="bar foo"></p>'), ('<p class="\tfoo\tbar\t"></p>', '<p class="bar foo"></p>'), ('<p class="\t\t\tfoo\t\t\tbar\t\t\t"></p>', '<p class="bar foo"></p>'), ('<p class="\t \nfoo \t\nbar\n\t "></p>', '<p class="bar foo"></p>'), ] for html1, html2 in pairs: with self.subTest(html1): self.assertHTMLEqual(html1, html2) def test_boolean_attribute(self): html1 = "<input checked>" html2 = '<input checked="">' html3 = '<input checked="checked">' self.assertHTMLEqual(html1, html2) self.assertHTMLEqual(html1, html3) self.assertHTMLEqual(html2, html3) self.assertHTMLNotEqual(html1, '<input checked="invalid">') self.assertEqual(str(parse_html(html1)), "<input checked>") self.assertEqual(str(parse_html(html2)), "<input checked>") self.assertEqual(str(parse_html(html3)), "<input checked>") def test_non_boolean_attibutes(self): html1 = "<input value>" html2 = '<input value="">' html3 = '<input value="value">' self.assertHTMLEqual(html1, html2) self.assertHTMLNotEqual(html1, html3) self.assertEqual(str(parse_html(html1)), '<input value="">') self.assertEqual(str(parse_html(html2)), '<input value="">') def test_normalize_refs(self): pairs = [ ("&#39;", "&#x27;"), ("&#39;", "'"), ("&#x27;", "&#39;"), ("&#x27;", "'"), ("'", "&#39;"), ("'", "&#x27;"), ("&amp;", "&#38;"), ("&amp;", "&#x26;"), ("&amp;", "&"), ("&#38;", "&amp;"), ("&#38;", "&#x26;"), ("&#38;", "&"), ("&#x26;", "&amp;"), ("&#x26;", "&#38;"), ("&#x26;", "&"), ("&", "&amp;"), ("&", "&#38;"), ("&", "&#x26;"), ] for pair in pairs: with self.subTest(repr(pair)): self.assertHTMLEqual(*pair) def test_complex_examples(self): self.assertHTMLEqual( """<tr><th><label for="id_first_name">First name:</label></th> <td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""", # NOQA """ <tr><th> <label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" value="John" id="id_first_name" /> </td></tr> <tr><th> <label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" value="Lennon" id="id_last_name" /> </td></tr> <tr><th> <label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /> </td></tr> """, ) self.assertHTMLEqual( """<!DOCTYPE html> <html> <head> <link rel="stylesheet"> <title>Document</title> <meta attribute="value"> </head> <body> <p> This is a valid paragraph <div> this is a div AFTER the p</div> </body> </html>""", """ <html> <head> <link rel="stylesheet"> <title>Document</title> <meta attribute="value"> </head> <body> <p> This is a valid paragraph <!-- browsers would close the p tag here --> <div> this is a div AFTER the p</div> </p> <!-- this is invalid HTML parsing, but it should make no difference in most cases --> </body> </html>""", ) def test_html_contain(self): # equal html contains each other dom1 = parse_html("<p>foo") dom2 = parse_html("<p>foo</p>") self.assertIn(dom1, dom2) self.assertIn(dom2, dom1) dom2 = parse_html("<div><p>foo</p></div>") self.assertIn(dom1, dom2) self.assertNotIn(dom2, dom1) self.assertNotIn("<p>foo</p>", dom2) self.assertIn("foo", dom2) # when a root element is used ... dom1 = parse_html("<p>foo</p><p>bar</p>") dom2 = parse_html("<p>foo</p><p>bar</p>") self.assertIn(dom1, dom2) dom1 = parse_html("<p>foo</p>") self.assertIn(dom1, dom2) dom1 = parse_html("<p>bar</p>") self.assertIn(dom1, dom2) dom1 = parse_html("<div><p>foo</p><p>bar</p></div>") self.assertIn(dom2, dom1) def test_count(self): # equal html contains each other one time dom1 = parse_html("<p>foo") dom2 = parse_html("<p>foo</p>") self.assertEqual(dom1.count(dom2), 1) self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo</p><p>bar</p>") self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo foo</p><p>foo</p>") self.assertEqual(dom2.count("foo"), 3) dom2 = parse_html('<p class="bar">foo</p>') self.assertEqual(dom2.count("bar"), 0) self.assertEqual(dom2.count("class"), 0) self.assertEqual(dom2.count("p"), 0) self.assertEqual(dom2.count("o"), 2) dom2 = parse_html("<p>foo</p><p>foo</p>") self.assertEqual(dom2.count(dom1), 2) dom2 = parse_html('<div><p>foo<input type=""></p><p>foo</p></div>') self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<div><div><p>foo</p></div></div>") self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo<p>foo</p></p>") self.assertEqual(dom2.count(dom1), 1) dom2 = parse_html("<p>foo<p>bar</p></p>") self.assertEqual(dom2.count(dom1), 0) # HTML with a root element contains the same HTML with no root element. dom1 = parse_html("<p>foo</p><p>bar</p>") dom2 = parse_html("<div><p>foo</p><p>bar</p></div>") self.assertEqual(dom2.count(dom1), 1) # Target of search is a sequence of child elements and appears more # than once. dom2 = parse_html("<div><p>foo</p><p>bar</p><p>foo</p><p>bar</p></div>") self.assertEqual(dom2.count(dom1), 2) # Searched HTML has additional children. dom1 = parse_html("<a/><b/>") dom2 = parse_html("<a/><b/><c/>") self.assertEqual(dom2.count(dom1), 1) # No match found in children. dom1 = parse_html("<b/><a/>") self.assertEqual(dom2.count(dom1), 0) # Target of search found among children and grandchildren. dom1 = parse_html("<b/><b/>") dom2 = parse_html("<a><b/><b/></a><b/><b/>") self.assertEqual(dom2.count(dom1), 2) def test_root_element_escaped_html(self): html = "&lt;br&gt;" parsed = parse_html(html) self.assertEqual(str(parsed), html) def test_parsing_errors(self): with self.assertRaises(AssertionError): self.assertHTMLEqual("<p>", "") with self.assertRaises(AssertionError): self.assertHTMLEqual("", "<p>") error_msg = ( "First argument is not valid HTML:\n" "('Unexpected end tag `div` (Line 1, Column 6)', (1, 6))" ) with self.assertRaisesMessage(AssertionError, error_msg): self.assertHTMLEqual("< div></ div>", "<div></div>") with self.assertRaises(HTMLParseError): parse_html("</p>") def test_escaped_html_errors(self): msg = "<p>\n<foo>\n</p> != <p>\n&lt;foo&gt;\n</p>\n" with self.assertRaisesMessage(AssertionError, msg): self.assertHTMLEqual("<p><foo></p>", "<p>&lt;foo&gt;</p>") with self.assertRaisesMessage(AssertionError, msg): self.assertHTMLEqual("<p><foo></p>", "<p>&#60;foo&#62;</p>") def test_contains_html(self): response = HttpResponse( """<body> This is a form: <form method="get"> <input type="text" name="Hello" /> </form></body>""" ) self.assertNotContains(response, "<input name='Hello' type='text'>") self.assertContains(response, '<form method="get">') self.assertContains(response, "<input name='Hello' type='text'>", html=True) self.assertNotContains(response, '<form method="get">', html=True) invalid_response = HttpResponse("""<body <bad>>""") with self.assertRaises(AssertionError): self.assertContains(invalid_response, "<p></p>") with self.assertRaises(AssertionError): self.assertContains(response, '<p "whats" that>') def test_unicode_handling(self): response = HttpResponse( '<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>' ) self.assertContains( response, '<p class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</p>', html=True, ) class JSONEqualTests(SimpleTestCase): def test_simple_equal(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr1": "foo", "attr2":"baz"}' self.assertJSONEqual(json1, json2) def test_simple_equal_unordered(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr2":"baz", "attr1": "foo"}' self.assertJSONEqual(json1, json2) def test_simple_equal_raise(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONEqual(json1, json2) def test_equal_parsing_errors(self): invalid_json = '{"attr1": "foo, "attr2":"baz"}' valid_json = '{"attr1": "foo", "attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONEqual(invalid_json, valid_json) with self.assertRaises(AssertionError): self.assertJSONEqual(valid_json, invalid_json) def test_simple_not_equal(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr2":"baz"}' self.assertJSONNotEqual(json1, json2) def test_simple_not_equal_raise(self): json1 = '{"attr1": "foo", "attr2":"baz"}' json2 = '{"attr1": "foo", "attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONNotEqual(json1, json2) def test_not_equal_parsing_errors(self): invalid_json = '{"attr1": "foo, "attr2":"baz"}' valid_json = '{"attr1": "foo", "attr2":"baz"}' with self.assertRaises(AssertionError): self.assertJSONNotEqual(invalid_json, valid_json) with self.assertRaises(AssertionError): self.assertJSONNotEqual(valid_json, invalid_json) class XMLEqualTests(SimpleTestCase): def test_simple_equal(self): xml1 = "<elem attr1='a' attr2='b' />" xml2 = "<elem attr1='a' attr2='b' />" self.assertXMLEqual(xml1, xml2) def test_simple_equal_unordered(self): xml1 = "<elem attr1='a' attr2='b' />" xml2 = "<elem attr2='b' attr1='a' />" self.assertXMLEqual(xml1, xml2) def test_simple_equal_raise(self): xml1 = "<elem attr1='a' />" xml2 = "<elem attr2='b' attr1='a' />" with self.assertRaises(AssertionError): self.assertXMLEqual(xml1, xml2) def test_simple_equal_raises_message(self): xml1 = "<elem attr1='a' />" xml2 = "<elem attr2='b' attr1='a' />" msg = """{xml1} != {xml2} - <elem attr1='a' /> + <elem attr2='b' attr1='a' /> ? ++++++++++ """.format( xml1=repr(xml1), xml2=repr(xml2) ) with self.assertRaisesMessage(AssertionError, msg): self.assertXMLEqual(xml1, xml2) def test_simple_not_equal(self): xml1 = "<elem attr1='a' attr2='c' />" xml2 = "<elem attr1='a' attr2='b' />" self.assertXMLNotEqual(xml1, xml2) def test_simple_not_equal_raise(self): xml1 = "<elem attr1='a' attr2='b' />" xml2 = "<elem attr2='b' attr1='a' />" with self.assertRaises(AssertionError): self.assertXMLNotEqual(xml1, xml2) def test_parsing_errors(self): xml_unvalid = "<elem attr1='a attr2='b' />" xml2 = "<elem attr2='b' attr1='a' />" with self.assertRaises(AssertionError): self.assertXMLNotEqual(xml_unvalid, xml2) def test_comment_root(self): xml1 = "<?xml version='1.0'?><!-- comment1 --><elem attr1='a' attr2='b' />" xml2 = "<?xml version='1.0'?><!-- comment2 --><elem attr2='b' attr1='a' />" self.assertXMLEqual(xml1, xml2) def test_simple_equal_with_leading_or_trailing_whitespace(self): xml1 = "<elem>foo</elem> \t\n" xml2 = " \t\n<elem>foo</elem>" self.assertXMLEqual(xml1, xml2) def test_simple_not_equal_with_whitespace_in_the_middle(self): xml1 = "<elem>foo</elem><elem>bar</elem>" xml2 = "<elem>foo</elem> <elem>bar</elem>" self.assertXMLNotEqual(xml1, xml2) def test_doctype_root(self): xml1 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example1.dtd"><root />' xml2 = '<?xml version="1.0"?><!DOCTYPE root SYSTEM "example2.dtd"><root />' self.assertXMLEqual(xml1, xml2) def test_processing_instruction(self): xml1 = ( '<?xml version="1.0"?>' '<?xml-model href="http://www.example1.com"?><root />' ) xml2 = ( '<?xml version="1.0"?>' '<?xml-model href="http://www.example2.com"?><root />' ) self.assertXMLEqual(xml1, xml2) self.assertXMLEqual( '<?xml-stylesheet href="style1.xslt" type="text/xsl"?><root />', '<?xml-stylesheet href="style2.xslt" type="text/xsl"?><root />', ) class SkippingExtraTests(TestCase): fixtures = ["should_not_be_loaded.json"] # HACK: This depends on internals of our TestCase subclasses def __call__(self, result=None): # Detect fixture loading by counting SQL queries, should be zero with self.assertNumQueries(0): super().__call__(result) @unittest.skip("Fixture loading should not be performed for skipped tests.") def test_fixtures_are_skipped(self): pass class AssertRaisesMsgTest(SimpleTestCase): def test_assert_raises_message(self): msg = "'Expected message' not found in 'Unexpected message'" # context manager form of assertRaisesMessage() with self.assertRaisesMessage(AssertionError, msg): with self.assertRaisesMessage(ValueError, "Expected message"): raise ValueError("Unexpected message") # callable form def func(): raise ValueError("Unexpected message") with self.assertRaisesMessage(AssertionError, msg): self.assertRaisesMessage(ValueError, "Expected message", func) def test_special_re_chars(self): """assertRaisesMessage shouldn't interpret RE special chars.""" def func1(): raise ValueError("[.*x+]y?") with self.assertRaisesMessage(ValueError, "[.*x+]y?"): func1() class AssertWarnsMessageTests(SimpleTestCase): def test_context_manager(self): with self.assertWarnsMessage(UserWarning, "Expected message"): warnings.warn("Expected message", UserWarning) def test_context_manager_failure(self): msg = "Expected message' not found in 'Unexpected message'" with self.assertRaisesMessage(AssertionError, msg): with self.assertWarnsMessage(UserWarning, "Expected message"): warnings.warn("Unexpected message", UserWarning) def test_callable(self): def func(): warnings.warn("Expected message", UserWarning) self.assertWarnsMessage(UserWarning, "Expected message", func) def test_special_re_chars(self): def func1(): warnings.warn("[.*x+]y?", UserWarning) with self.assertWarnsMessage(UserWarning, "[.*x+]y?"): func1() class AssertFieldOutputTests(SimpleTestCase): def test_assert_field_output(self): error_invalid = ["Enter a valid email address."] self.assertFieldOutput( EmailField, {"[email protected]": "[email protected]"}, {"aaa": error_invalid} ) with self.assertRaises(AssertionError): self.assertFieldOutput( EmailField, {"[email protected]": "[email protected]"}, {"aaa": error_invalid + ["Another error"]}, ) with self.assertRaises(AssertionError): self.assertFieldOutput( EmailField, {"[email protected]": "Wrong output"}, {"aaa": error_invalid} ) with self.assertRaises(AssertionError): self.assertFieldOutput( EmailField, {"[email protected]": "[email protected]"}, {"aaa": ["Come on, gimme some well formatted data, dude."]}, ) def test_custom_required_message(self): class MyCustomField(IntegerField): default_error_messages = { "required": "This is really required.", } self.assertFieldOutput(MyCustomField, {}, {}, empty_value=None) @override_settings(ROOT_URLCONF="test_utils.urls") class AssertURLEqualTests(SimpleTestCase): def test_equal(self): valid_tests = ( ("http://example.com/?", "http://example.com/"), ("http://example.com/?x=1&", "http://example.com/?x=1"), ("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), ("http://example.com/?x=1&y=2", "http://example.com/?y=2&x=1"), ( "http://example.com/?x=1&y=2&a=1&a=2", "http://example.com/?a=1&a=2&y=2&x=1", ), ("/path/to/?x=1&y=2&z=3", "/path/to/?z=3&y=2&x=1"), ("?x=1&y=2&z=3", "?z=3&y=2&x=1"), ("/test_utils/no_template_used/", reverse_lazy("no_template_used")), ) for url1, url2 in valid_tests: with self.subTest(url=url1): self.assertURLEqual(url1, url2) def test_not_equal(self): invalid_tests = ( # Protocol must be the same. ("http://example.com/", "https://example.com/"), ("http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1"), ("http://example.com/?x=1&y=bar&x=2", "https://example.com/?y=bar&x=2&x=1"), # Parameters of the same name must be in the same order. ("/path/to?a=1&a=2", "/path/to/?a=2&a=1"), ) for url1, url2 in invalid_tests: with self.subTest(url=url1), self.assertRaises(AssertionError): self.assertURLEqual(url1, url2) def test_message(self): msg = ( "Expected 'http://example.com/?x=1&x=2' to equal " "'https://example.com/?x=2&x=1'" ) with self.assertRaisesMessage(AssertionError, msg): self.assertURLEqual( "http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1" ) def test_msg_prefix(self): msg = ( "Prefix: Expected 'http://example.com/?x=1&x=2' to equal " "'https://example.com/?x=2&x=1'" ) with self.assertRaisesMessage(AssertionError, msg): self.assertURLEqual( "http://example.com/?x=1&x=2", "https://example.com/?x=2&x=1", msg_prefix="Prefix: ", ) class TestForm(Form): field = CharField() def clean_field(self): value = self.cleaned_data.get("field", "") if value == "invalid": raise ValidationError("invalid value") return value def clean(self): if self.cleaned_data.get("field") == "invalid_non_field": raise ValidationError("non-field error") return self.cleaned_data @classmethod def _get_cleaned_form(cls, field_value): form = cls({"field": field_value}) form.full_clean() return form @classmethod def valid(cls): return cls._get_cleaned_form("valid") @classmethod def invalid(cls, nonfield=False): return cls._get_cleaned_form("invalid_non_field" if nonfield else "invalid") class TestFormset(formset_factory(TestForm)): @classmethod def _get_cleaned_formset(cls, field_value): formset = cls( { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-field": field_value, } ) formset.full_clean() return formset @classmethod def valid(cls): return cls._get_cleaned_formset("valid") @classmethod def invalid(cls, nonfield=False, nonform=False): if nonform: formset = cls({}, error_messages={"missing_management_form": "error"}) formset.full_clean() return formset return cls._get_cleaned_formset("invalid_non_field" if nonfield else "invalid") class AssertFormErrorTests(SimpleTestCase): def test_single_error(self): self.assertFormError(TestForm.invalid(), "field", "invalid value") def test_error_list(self): self.assertFormError(TestForm.invalid(), "field", ["invalid value"]) def test_empty_errors_valid_form(self): self.assertFormError(TestForm.valid(), "field", []) def test_empty_errors_valid_form_non_field_errors(self): self.assertFormError(TestForm.valid(), None, []) def test_field_not_in_form(self): msg = ( "The form <TestForm bound=True, valid=False, fields=(field)> does not " "contain the field 'other_field'." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(TestForm.invalid(), "other_field", "invalid value") msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.invalid(), "other_field", "invalid value", msg_prefix=msg_prefix, ) def test_field_with_no_errors(self): msg = ( "The errors of field 'field' on form <TestForm bound=True, valid=True, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError(TestForm.valid(), "field", "invalid value") self.assertIn("[] != ['invalid value']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.valid(), "field", "invalid value", msg_prefix=msg_prefix ) def test_field_with_different_error(self): msg = ( "The errors of field 'field' on form <TestForm bound=True, valid=False, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError(TestForm.invalid(), "field", "other error") self.assertIn("['invalid value'] != ['other error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.invalid(), "field", "other error", msg_prefix=msg_prefix ) def test_unbound_form(self): msg = ( "The form <TestForm bound=False, valid=Unknown, fields=(field)> is not " "bound, it will never have any errors." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormError(TestForm(), "field", []) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError(TestForm(), "field", [], msg_prefix=msg_prefix) def test_empty_errors_invalid_form(self): msg = ( "The errors of field 'field' on form <TestForm bound=True, valid=False, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError(TestForm.invalid(), "field", []) self.assertIn("['invalid value'] != []", str(ctx.exception)) def test_non_field_errors(self): self.assertFormError(TestForm.invalid(nonfield=True), None, "non-field error") def test_different_non_field_errors(self): msg = ( "The non-field errors of form <TestForm bound=True, valid=False, " "fields=(field)> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormError( TestForm.invalid(nonfield=True), None, "other non-field error" ) self.assertIn( "['non-field error'] != ['other non-field error']", str(ctx.exception) ) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormError( TestForm.invalid(nonfield=True), None, "other non-field error", msg_prefix=msg_prefix, ) class AssertFormSetErrorTests(SimpleTestCase): def test_rename_assertformseterror_deprecation_warning(self): msg = "assertFormsetError() is deprecated in favor of assertFormSetError()." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): self.assertFormsetError() @ignore_warnings(category=RemovedInDjango51Warning) def test_deprecated_assertformseterror(self): self.assertFormsetError(TestFormset.invalid(), 0, "field", "invalid value") def test_single_error(self): self.assertFormSetError(TestFormset.invalid(), 0, "field", "invalid value") def test_error_list(self): self.assertFormSetError(TestFormset.invalid(), 0, "field", ["invalid value"]) def test_empty_errors_valid_formset(self): self.assertFormSetError(TestFormset.valid(), 0, "field", []) def test_multiple_forms(self): formset = TestFormset( { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-0-field": "valid", "form-1-field": "invalid", } ) formset.full_clean() self.assertFormSetError(formset, 0, "field", []) self.assertFormSetError(formset, 1, "field", ["invalid value"]) def test_field_not_in_form(self): msg = ( "The form 0 of formset <TestFormset: bound=True valid=False total_forms=1> " "does not contain the field 'other_field'." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError( TestFormset.invalid(), 0, "other_field", "invalid value" ) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), 0, "other_field", "invalid value", msg_prefix=msg_prefix, ) def test_field_with_no_errors(self): msg = ( "The errors of field 'field' on form 0 of formset <TestFormset: bound=True " "valid=True total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.valid(), 0, "field", "invalid value") self.assertIn("[] != ['invalid value']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.valid(), 0, "field", "invalid value", msg_prefix=msg_prefix ) def test_field_with_different_error(self): msg = ( "The errors of field 'field' on form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), 0, "field", "other error") self.assertIn("['invalid value'] != ['other error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), 0, "field", "other error", msg_prefix=msg_prefix ) def test_unbound_formset(self): msg = ( "The formset <TestFormset: bound=False valid=Unknown total_forms=1> is not " "bound, it will never have any errors." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError(TestFormset(), 0, "field", []) def test_empty_errors_invalid_formset(self): msg = ( "The errors of field 'field' on form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), 0, "field", []) self.assertIn("['invalid value'] != []", str(ctx.exception)) def test_non_field_errors(self): self.assertFormSetError( TestFormset.invalid(nonfield=True), 0, None, "non-field error" ) def test_different_non_field_errors(self): msg = ( "The non-field errors of form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError( TestFormset.invalid(nonfield=True), 0, None, "other non-field error" ) self.assertIn( "['non-field error'] != ['other non-field error']", str(ctx.exception) ) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(nonfield=True), 0, None, "other non-field error", msg_prefix=msg_prefix, ) def test_no_non_field_errors(self): msg = ( "The non-field errors of form 0 of formset <TestFormset: bound=True " "valid=False total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), 0, None, "non-field error") self.assertIn("[] != ['non-field error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), 0, None, "non-field error", msg_prefix=msg_prefix ) def test_non_form_errors(self): self.assertFormSetError(TestFormset.invalid(nonform=True), None, None, "error") def test_different_non_form_errors(self): msg = ( "The non-form errors of formset <TestFormset: bound=True valid=False " "total_forms=0> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError( TestFormset.invalid(nonform=True), None, None, "other error" ) self.assertIn("['error'] != ['other error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(nonform=True), None, None, "other error", msg_prefix=msg_prefix, ) def test_no_non_form_errors(self): msg = ( "The non-form errors of formset <TestFormset: bound=True valid=False " "total_forms=1> don't match." ) with self.assertRaisesMessage(AssertionError, msg) as ctx: self.assertFormSetError(TestFormset.invalid(), None, None, "error") self.assertIn("[] != ['error']", str(ctx.exception)) msg_prefix = "Custom prefix" with self.assertRaisesMessage(AssertionError, f"{msg_prefix}: {msg}"): self.assertFormSetError( TestFormset.invalid(), None, None, "error", msg_prefix=msg_prefix, ) def test_non_form_errors_with_field(self): msg = "You must use field=None with form_index=None." with self.assertRaisesMessage(ValueError, msg): self.assertFormSetError( TestFormset.invalid(nonform=True), None, "field", "error" ) def test_form_index_too_big(self): msg = ( "The formset <TestFormset: bound=True valid=False total_forms=1> only has " "1 form." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError(TestFormset.invalid(), 2, "field", "error") def test_form_index_too_big_plural(self): formset = TestFormset( { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-0-field": "valid", "form-1-field": "valid", } ) formset.full_clean() msg = ( "The formset <TestFormset: bound=True valid=True total_forms=2> only has 2 " "forms." ) with self.assertRaisesMessage(AssertionError, msg): self.assertFormSetError(formset, 2, "field", "error") class FirstUrls: urlpatterns = [path("first/", empty_response, name="first")] class SecondUrls: urlpatterns = [path("second/", empty_response, name="second")] class SetupTestEnvironmentTests(SimpleTestCase): def test_setup_test_environment_calling_more_than_once(self): with self.assertRaisesMessage( RuntimeError, "setup_test_environment() was already called" ): setup_test_environment() def test_allowed_hosts(self): for type_ in (list, tuple): with self.subTest(type_=type_): allowed_hosts = type_("*") with mock.patch("django.test.utils._TestState") as x: del x.saved_data with self.settings(ALLOWED_HOSTS=allowed_hosts): setup_test_environment() self.assertEqual(settings.ALLOWED_HOSTS, ["*", "testserver"]) class OverrideSettingsTests(SimpleTestCase): # #21518 -- If neither override_settings nor a setting_changed receiver # clears the URL cache between tests, then one of test_first or # test_second will fail. @override_settings(ROOT_URLCONF=FirstUrls) def test_urlconf_first(self): reverse("first") @override_settings(ROOT_URLCONF=SecondUrls) def test_urlconf_second(self): reverse("second") def test_urlconf_cache(self): with self.assertRaises(NoReverseMatch): reverse("first") with self.assertRaises(NoReverseMatch): reverse("second") with override_settings(ROOT_URLCONF=FirstUrls): self.client.get(reverse("first")) with self.assertRaises(NoReverseMatch): reverse("second") with override_settings(ROOT_URLCONF=SecondUrls): with self.assertRaises(NoReverseMatch): reverse("first") self.client.get(reverse("second")) self.client.get(reverse("first")) with self.assertRaises(NoReverseMatch): reverse("second") with self.assertRaises(NoReverseMatch): reverse("first") with self.assertRaises(NoReverseMatch): reverse("second") def test_override_media_root(self): """ Overriding the MEDIA_ROOT setting should be reflected in the base_location attribute of django.core.files.storage.default_storage. """ self.assertEqual(default_storage.base_location, "") with self.settings(MEDIA_ROOT="test_value"): self.assertEqual(default_storage.base_location, "test_value") def test_override_media_url(self): """ Overriding the MEDIA_URL setting should be reflected in the base_url attribute of django.core.files.storage.default_storage. """ self.assertEqual(default_storage.base_location, "") with self.settings(MEDIA_URL="/test_value/"): self.assertEqual(default_storage.base_url, "/test_value/") def test_override_file_upload_permissions(self): """ Overriding the FILE_UPLOAD_PERMISSIONS setting should be reflected in the file_permissions_mode attribute of django.core.files.storage.default_storage. """ self.assertEqual(default_storage.file_permissions_mode, 0o644) with self.settings(FILE_UPLOAD_PERMISSIONS=0o777): self.assertEqual(default_storage.file_permissions_mode, 0o777) def test_override_file_upload_directory_permissions(self): """ Overriding the FILE_UPLOAD_DIRECTORY_PERMISSIONS setting should be reflected in the directory_permissions_mode attribute of django.core.files.storage.default_storage. """ self.assertIsNone(default_storage.directory_permissions_mode) with self.settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777): self.assertEqual(default_storage.directory_permissions_mode, 0o777) def test_override_database_routers(self): """ Overriding DATABASE_ROUTERS should update the base router. """ test_routers = [object()] with self.settings(DATABASE_ROUTERS=test_routers): self.assertEqual(router.routers, test_routers) def test_override_static_url(self): """ Overriding the STATIC_URL setting should be reflected in the base_url attribute of django.contrib.staticfiles.storage.staticfiles_storage. """ with self.settings(STATIC_URL="/test/"): self.assertEqual(staticfiles_storage.base_url, "/test/") def test_override_static_root(self): """ Overriding the STATIC_ROOT setting should be reflected in the location attribute of django.contrib.staticfiles.storage.staticfiles_storage. """ with self.settings(STATIC_ROOT="/tmp/test"): self.assertEqual(staticfiles_storage.location, os.path.abspath("/tmp/test")) def test_override_staticfiles_storage(self): """ Overriding the STORAGES setting should be reflected in the value of django.contrib.staticfiles.storage.staticfiles_storage. """ new_class = "ManifestStaticFilesStorage" new_storage = "django.contrib.staticfiles.storage." + new_class with self.settings( STORAGES={STATICFILES_STORAGE_ALIAS: {"BACKEND": new_storage}} ): self.assertEqual(staticfiles_storage.__class__.__name__, new_class) def test_override_staticfiles_finders(self): """ Overriding the STATICFILES_FINDERS setting should be reflected in the return value of django.contrib.staticfiles.finders.get_finders. """ current = get_finders() self.assertGreater(len(list(current)), 1) finders = ["django.contrib.staticfiles.finders.FileSystemFinder"] with self.settings(STATICFILES_FINDERS=finders): self.assertEqual(len(list(get_finders())), len(finders)) def test_override_staticfiles_dirs(self): """ Overriding the STATICFILES_DIRS setting should be reflected in the locations attribute of the django.contrib.staticfiles.finders.FileSystemFinder instance. """ finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") test_path = "/tmp/test" expected_location = ("", test_path) self.assertNotIn(expected_location, finder.locations) with self.settings(STATICFILES_DIRS=[test_path]): finder = get_finder("django.contrib.staticfiles.finders.FileSystemFinder") self.assertIn(expected_location, finder.locations) @skipUnlessDBFeature("supports_transactions") class TestBadSetUpTestData(TestCase): """ An exception in setUpTestData() shouldn't leak a transaction which would cascade across the rest of the test suite. """ class MyException(Exception): pass @classmethod def setUpClass(cls): try: super().setUpClass() except cls.MyException: cls._in_atomic_block = connection.in_atomic_block @classmethod def tearDownClass(Cls): # override to avoid a second cls._rollback_atomics() which would fail. # Normal setUpClass() methods won't have exception handling so this # method wouldn't typically be run. pass @classmethod def setUpTestData(cls): # Simulate a broken setUpTestData() method. raise cls.MyException() def test_failure_in_setUpTestData_should_rollback_transaction(self): # setUpTestData() should call _rollback_atomics() so that the # transaction doesn't leak. self.assertFalse(self._in_atomic_block) @skipUnlessDBFeature("supports_transactions") class CaptureOnCommitCallbacksTests(TestCase): databases = {"default", "other"} callback_called = False def enqueue_callback(self, using="default"): def hook(): self.callback_called = True transaction.on_commit(hook, using=using) def test_no_arguments(self): with self.captureOnCommitCallbacks() as callbacks: self.enqueue_callback() self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, False) callbacks[0]() self.assertIs(self.callback_called, True) def test_using(self): with self.captureOnCommitCallbacks(using="other") as callbacks: self.enqueue_callback(using="other") self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, False) callbacks[0]() self.assertIs(self.callback_called, True) def test_different_using(self): with self.captureOnCommitCallbacks(using="default") as callbacks: self.enqueue_callback(using="other") self.assertEqual(callbacks, []) def test_execute(self): with self.captureOnCommitCallbacks(execute=True) as callbacks: self.enqueue_callback() self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, True) def test_pre_callback(self): def pre_hook(): pass transaction.on_commit(pre_hook, using="default") with self.captureOnCommitCallbacks() as callbacks: self.enqueue_callback() self.assertEqual(len(callbacks), 1) self.assertNotEqual(callbacks[0], pre_hook) def test_with_rolled_back_savepoint(self): with self.captureOnCommitCallbacks() as callbacks: try: with transaction.atomic(): self.enqueue_callback() raise IntegrityError except IntegrityError: # Inner transaction.atomic() has been rolled back. pass self.assertEqual(callbacks, []) def test_execute_recursive(self): with self.captureOnCommitCallbacks(execute=True) as callbacks: transaction.on_commit(self.enqueue_callback) self.assertEqual(len(callbacks), 2) self.assertIs(self.callback_called, True) def test_execute_tree(self): """ A visualisation of the callback tree tested. Each node is expected to be visited only once: └─branch_1 ├─branch_2 │ ├─leaf_1 │ └─leaf_2 └─leaf_3 """ branch_1_call_counter = 0 branch_2_call_counter = 0 leaf_1_call_counter = 0 leaf_2_call_counter = 0 leaf_3_call_counter = 0 def leaf_1(): nonlocal leaf_1_call_counter leaf_1_call_counter += 1 def leaf_2(): nonlocal leaf_2_call_counter leaf_2_call_counter += 1 def leaf_3(): nonlocal leaf_3_call_counter leaf_3_call_counter += 1 def branch_1(): nonlocal branch_1_call_counter branch_1_call_counter += 1 transaction.on_commit(branch_2) transaction.on_commit(leaf_3) def branch_2(): nonlocal branch_2_call_counter branch_2_call_counter += 1 transaction.on_commit(leaf_1) transaction.on_commit(leaf_2) with self.captureOnCommitCallbacks(execute=True) as callbacks: transaction.on_commit(branch_1) self.assertEqual(branch_1_call_counter, 1) self.assertEqual(branch_2_call_counter, 1) self.assertEqual(leaf_1_call_counter, 1) self.assertEqual(leaf_2_call_counter, 1) self.assertEqual(leaf_3_call_counter, 1) self.assertEqual(callbacks, [branch_1, branch_2, leaf_3, leaf_1, leaf_2]) def test_execute_robust(self): class MyException(Exception): pass def hook(): self.callback_called = True raise MyException("robust callback") with self.assertLogs("django.test", "ERROR") as cm: with self.captureOnCommitCallbacks(execute=True) as callbacks: transaction.on_commit(hook, robust=True) self.assertEqual(len(callbacks), 1) self.assertIs(self.callback_called, True) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Error calling CaptureOnCommitCallbacksTests.test_execute_robust.<locals>." "hook in on_commit() (robust callback).", ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertIsInstance(raised_exception, MyException) self.assertEqual(str(raised_exception), "robust callback") class DisallowedDatabaseQueriesTests(SimpleTestCase): def test_disallowed_database_connections(self): expected_message = ( "Database connections to 'default' are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to " "ensure proper test isolation or add 'default' to " "test_utils.tests.DisallowedDatabaseQueriesTests.databases to " "silence this failure." ) with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): connection.connect() with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): connection.temporary_connection() def test_disallowed_database_queries(self): expected_message = ( "Database queries to 'default' are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to " "ensure proper test isolation or add 'default' to " "test_utils.tests.DisallowedDatabaseQueriesTests.databases to " "silence this failure." ) with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): Car.objects.first() def test_disallowed_database_chunked_cursor_queries(self): expected_message = ( "Database queries to 'default' are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to " "ensure proper test isolation or add 'default' to " "test_utils.tests.DisallowedDatabaseQueriesTests.databases to " "silence this failure." ) with self.assertRaisesMessage(DatabaseOperationForbidden, expected_message): next(Car.objects.iterator()) class AllowedDatabaseQueriesTests(SimpleTestCase): databases = {"default"} def test_allowed_database_queries(self): Car.objects.first() def test_allowed_database_chunked_cursor_queries(self): next(Car.objects.iterator(), None) class DatabaseAliasTests(SimpleTestCase): def setUp(self): self.addCleanup(setattr, self.__class__, "databases", self.databases) def test_no_close_match(self): self.__class__.databases = {"void"} message = ( "test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is " "not defined in settings.DATABASES." ) with self.assertRaisesMessage(ImproperlyConfigured, message): self._validate_databases() def test_close_match(self): self.__class__.databases = {"defualt"} message = ( "test_utils.tests.DatabaseAliasTests.databases refers to 'defualt' which " "is not defined in settings.DATABASES. Did you mean 'default'?" ) with self.assertRaisesMessage(ImproperlyConfigured, message): self._validate_databases() def test_match(self): self.__class__.databases = {"default", "other"} self.assertEqual(self._validate_databases(), frozenset({"default", "other"})) def test_all(self): self.__class__.databases = "__all__" self.assertEqual(self._validate_databases(), frozenset(connections)) @isolate_apps("test_utils", attr_name="class_apps") class IsolatedAppsTests(SimpleTestCase): def test_installed_apps(self): self.assertEqual( [app_config.label for app_config in self.class_apps.get_app_configs()], ["test_utils"], ) def test_class_decoration(self): class ClassDecoration(models.Model): pass self.assertEqual(ClassDecoration._meta.apps, self.class_apps) @isolate_apps("test_utils", kwarg_name="method_apps") def test_method_decoration(self, method_apps): class MethodDecoration(models.Model): pass self.assertEqual(MethodDecoration._meta.apps, method_apps) def test_context_manager(self): with isolate_apps("test_utils") as context_apps: class ContextManager(models.Model): pass self.assertEqual(ContextManager._meta.apps, context_apps) @isolate_apps("test_utils", kwarg_name="method_apps") def test_nested(self, method_apps): class MethodDecoration(models.Model): pass with isolate_apps("test_utils") as context_apps: class ContextManager(models.Model): pass with isolate_apps("test_utils") as nested_context_apps: class NestedContextManager(models.Model): pass self.assertEqual(MethodDecoration._meta.apps, method_apps) self.assertEqual(ContextManager._meta.apps, context_apps) self.assertEqual(NestedContextManager._meta.apps, nested_context_apps) class DoNothingDecorator(TestContextDecorator): def enable(self): pass def disable(self): pass class TestContextDecoratorTests(SimpleTestCase): @mock.patch.object(DoNothingDecorator, "disable") def test_exception_in_setup(self, mock_disable): """An exception is setUp() is reraised after disable() is called.""" class ExceptionInSetUp(unittest.TestCase): def setUp(self): raise NotImplementedError("reraised") decorator = DoNothingDecorator() decorated_test_class = decorator.__call__(ExceptionInSetUp)() self.assertFalse(mock_disable.called) with self.assertRaisesMessage(NotImplementedError, "reraised"): decorated_test_class.setUp() decorated_test_class.doCleanups() self.assertTrue(mock_disable.called) def test_cleanups_run_after_tearDown(self): calls = [] class SaveCallsDecorator(TestContextDecorator): def enable(self): calls.append("enable") def disable(self): calls.append("disable") class AddCleanupInSetUp(unittest.TestCase): def setUp(self): calls.append("setUp") self.addCleanup(lambda: calls.append("cleanup")) decorator = SaveCallsDecorator() decorated_test_class = decorator.__call__(AddCleanupInSetUp)() decorated_test_class.setUp() decorated_test_class.tearDown() decorated_test_class.doCleanups() self.assertEqual(calls, ["enable", "setUp", "cleanup", "disable"])
7849b9455cc8498aa95a3022c31be92db7a1543bca1c53292ca1cb63211ec7ed
import datetime import os import re import unittest import zoneinfo from unittest import mock from urllib.parse import parse_qsl, urljoin, urlparse from django.contrib import admin from django.contrib.admin import AdminSite, ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import ADDITION, DELETION, LogEntry from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth import REDIRECT_FIELD_NAME, get_permission_codename from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.db import connection from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import ( TestCase, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.utils import override_script_prefix from django.urls import NoReverseMatch, resolve, reverse from django.utils import formats, translation from django.utils.cache import get_max_age from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import urlencode from . import customadmin from .admin import CityAdmin, site, site2 from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, Bookmark, Box, Category, Chapter, ChapterXtra1, ChapterXtra2, Character, Child, Choice, City, Collector, Color, ComplexSortedPerson, CoverLetter, CustomArticle, CyclicOne, CyclicTwo, DooHickey, Employee, EmptyModel, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gallery, Grommet, Inquisition, Language, Link, MainPrepopulated, Media, ModelWithStringPrimaryKey, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PluggableSearchPerson, Podcast, Post, PrePopulatedPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recommendation, Recommender, RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Restaurant, RowLevelChangePermissionModel, SecretHideout, Section, ShortMessage, Simple, Song, State, Story, SuperSecretHideout, SuperVillain, Telegram, TitleTranslation, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, WorkHour, ) ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." MULTIPART_ENCTYPE = 'enctype="multipart/form-data"' def make_aware_datetimes(dt, iana_key): """Makes one aware datetime for each supported time zone provider.""" yield dt.replace(tzinfo=zoneinfo.ZoneInfo(iana_key)) class AdminFieldExtractionMixin: """ Helper methods for extracting data from AdminForm. """ def get_admin_form_fields(self, response): """ Return a list of AdminFields for the AdminForm in the response. """ fields = [] for fieldset in response.context["adminform"]: for field_line in fieldset: fields.extend(field_line) return fields def get_admin_readonly_fields(self, response): """ Return the readonly fields for the response's AdminForm. """ return [f for f in self.get_admin_form_fields(response) if f.is_readonly] def get_admin_readonly_field(self, response, field_name): """ Return the readonly field for the given field_name. """ admin_readonly_fields = self.get_admin_readonly_fields(response) for field in admin_readonly_fields: if field.field["name"] == field_name: return field @override_settings(ROOT_URLCONF="admin_views.urls", USE_I18N=True, LANGUAGE_CODE="en") class AdminViewBasicTestCase(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, title="Article 1", ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, title="Article 2", ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.color1 = Color.objects.create(value="Red", warm=True) cls.color2 = Color.objects.create(value="Orange", warm=True) cls.color3 = Color.objects.create(value="Blue", warm=False) cls.color4 = Color.objects.create(value="Green", warm=False) cls.fab1 = Fabric.objects.create(surface="x") cls.fab2 = Fabric.objects.create(surface="y") cls.fab3 = Fabric.objects.create(surface="plain") cls.b1 = Book.objects.create(name="Book 1") cls.b2 = Book.objects.create(name="Book 2") cls.pro1 = Promo.objects.create(name="Promo 1", book=cls.b1) cls.pro1 = Promo.objects.create(name="Promo 2", book=cls.b2) cls.chap1 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b1 ) cls.chap2 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b1 ) cls.chap3 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b2 ) cls.chap4 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b2 ) cls.cx1 = ChapterXtra1.objects.create(chap=cls.chap1, xtra="ChapterXtra1 1") cls.cx2 = ChapterXtra1.objects.create(chap=cls.chap3, xtra="ChapterXtra1 2") Actor.objects.create(name="Palin", age=27) # Post data for edit inline cls.inline_post_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": cls.a1.pk, # there is no title in database, give one here or formset will fail. "article_set-0-title": "Norske bostaver æøå skaper problemer", "article_set-0-content": "&lt;p&gt;Middle content&lt;/p&gt;", "article_set-0-date_0": "2008-03-18", "article_set-0-date_1": "11:54:58", "article_set-0-section": cls.s1.pk, "article_set-1-id": cls.a2.pk, "article_set-1-title": "Need a title.", "article_set-1-content": "&lt;p&gt;Oldest content&lt;/p&gt;", "article_set-1-date_0": "2000-03-18", "article_set-1-date_1": "11:54:58", "article_set-2-id": cls.a3.pk, "article_set-2-title": "Need a title.", "article_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "article_set-2-date_0": "2009-03-18", "article_set-2-date_1": "11:54:58", "article_set-3-id": "", "article_set-3-title": "", "article_set-3-content": "", "article_set-3-date_0": "", "article_set-3-date_1": "", "article_set-4-id": "", "article_set-4-title": "", "article_set-4-content": "", "article_set-4-date_0": "", "article_set-4-date_1": "", "article_set-5-id": "", "article_set-5-title": "", "article_set-5-content": "", "article_set-5-date_0": "", "article_set-5-date_1": "", } def setUp(self): self.client.force_login(self.superuser) def assertContentBefore(self, response, text1, text2, failing_msg=None): """ Testing utility asserting that text1 appears before text2 in response content. """ self.assertEqual(response.status_code, 200) self.assertLess( response.content.index(text1.encode()), response.content.index(text2.encode()), (failing_msg or "") + "\nResponse:\n" + response.content.decode(response.charset), ) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(self): """ If you leave off the trailing slash, app should redirect and add it. """ add_url = reverse("admin:admin_views_article_add") response = self.client.get(add_url[:-1]) self.assertRedirects(response, add_url, status_code=301) def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): response = self.client.get( reverse("admin:admin_views_section_add"), {"name": "My Section"} ) self.assertContains( response, 'value="My Section"', msg_prefix="Couldn't find an input with the right value in the response", ) def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """ GET on the change_view (when passing a string as the PK argument for a model with an integer PK field) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(quote("abc/<b>"),)), follow=True, ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["section with ID “abc/<b>” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_edit_GET_old_url_redirect(self): """ The change URL changed in Django 1.9, but the old one still redirects. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)).replace( "change/", "" ) ) self.assertRedirects( response, reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) def test_basic_inheritance_GET_string_PK(self): """ GET on the change_view (for inherited models) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_supervillain_change", args=("abc",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["super villain with ID “abc” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_add_POST(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "Another Section", # inline data "article_set-TOTAL_FORMS": "3", "article_set-INITIAL_FORMS": "0", "article_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_section_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_popup_add_POST(self): """HTTP response from a popup is properly escaped.""" post_data = { IS_POPUP_VAR: "1", "title": "title with a new\nline", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post(reverse("admin:admin_views_article_add"), post_data) self.assertContains(response, "title with a new\\nline") def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ url = reverse("admin:admin_views_section_change", args=(self.s1.pk,)) response = self.client.post(url, self.inline_post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as(self): """ Test "save as". """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-3-section": "1", "article_set-4-section": "1", "article_set-5-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as_delete_inline(self): """ Should be able to "Save as new" while also deleting an inline. """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-2-DELETE": "1", "article_set-3-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # started with 3 articles, one was deleted. self.assertEqual(Section.objects.latest("id").article_set.count(), 2) def test_change_list_column_field_classes(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) # callables display the callable name. self.assertContains(response, "column-callable_year") self.assertContains(response, "field-callable_year") # lambdas display as "lambda" + index that they appear in list_display. self.assertContains(response, "column-lambda8") self.assertContains(response, "field-lambda8") def test_change_list_sorting_callable(self): """ Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 2} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_property(self): """ Sort on a list_display field that is a property (column 10 is a property in Article model). """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 10} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on property are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on property are out of order.", ) def test_change_list_sorting_callable_query_expression(self): """Query expressions may be used for admin_order_field.""" tests = [ ("order_by_expression", 9), ("order_by_f_expression", 12), ("order_by_orderby_expression", 13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_callable_query_expression_reverse(self): tests = [ ("order_by_expression", -9), ("order_by_f_expression", -12), ("order_by_orderby_expression", -13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_model(self): """ Ensure we can sort on a list_display field that is a Model method (column 3 is 'model_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-3"} ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on Model method are out of order.", ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on Model method are out of order.", ) def test_change_list_sorting_model_admin(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method (column 4 is 'modeladmin_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "4"} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_model_admin_reverse(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method in reverse order (i.e. admin_order_field uses the '-' prefix) (column 6 is 'model_year_reverse' in ArticleAdmin) """ td = '<td class="field-model_property_year">%s</td>' td_2000, td_2008, td_2009 = td % 2000, td % 2008, td % 2009 response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "6"} ) self.assertContentBefore( response, td_2009, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2000, "Results of sorting on ModelAdmin method are out of order.", ) # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-6"} ) self.assertContentBefore( response, td_2000, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2009, "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_multiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) p2 = Person.objects.create(name="Chris", gender=2, alive=True) p3 = Person.objects.create(name="Bob", gender=1, alive=True) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) # Sort by name, gender response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "1.2"} ) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "-2.1"} ) self.assertContentBefore(response, link2, link3) self.assertContentBefore(response, link3, link1) def test_change_list_sorting_preserve_queryset_ordering(self): """ If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.get_queryset()`. Refs #11868, #7309. """ p1 = Person.objects.create(name="Amy", gender=1, alive=True, age=80) p2 = Person.objects.create(name="Bob", gender=1, alive=True, age=70) p3 = Person.objects.create(name="Chris", gender=2, alive=False, age=60) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) response = self.client.get(reverse("admin:admin_views_person_changelist"), {}) self.assertContentBefore(response, link3, link2) self.assertContentBefore(response, link2, link1) def test_change_list_sorting_model_meta(self): # Test ordering on Model Meta is respected l1 = Language.objects.create(iso="ur", name="Urdu") l2 = Language.objects.create(iso="ar", name="Arabic") link1 = reverse("admin:admin_views_language_change", args=(quote(l1.pk),)) link2 = reverse("admin:admin_views_language_change", args=(quote(l2.pk),)) response = self.client.get(reverse("admin:admin_views_language_changelist"), {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get( reverse("admin:admin_views_language_changelist"), {"o": "-1"} ) self.assertContentBefore(response, link1, link2) def test_change_list_sorting_override_model_admin(self): # Test ordering on Model Admin is respected, and overrides Model Meta dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_podcast_change", args=(p2.pk,)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) def test_multiple_sort_same_field(self): # The changelist displays the correct columns if two columns correspond # to the same ordering field. dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(quote(p1.pk),)) link2 = reverse("admin:admin_views_podcast_change", args=(quote(p2.pk),)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) p1 = ComplexSortedPerson.objects.create(name="Bob", age=10) p2 = ComplexSortedPerson.objects.create(name="Amy", age=20) link1 = reverse("admin:admin_views_complexsortedperson_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_complexsortedperson_change", args=(p2.pk,)) response = self.client.get( reverse("admin:admin_views_complexsortedperson_changelist"), {} ) # Should have 5 columns (including action checkbox col) self.assertContains(response, '<th scope="col"', count=5) self.assertContains(response, "Name") self.assertContains(response, "Colored name") # Check order self.assertContentBefore(response, "Name", "Colored name") # Check sorting - should be by name self.assertContentBefore(response, link2, link1) def test_sort_indicators_admin_order(self): """ The admin shows default sort indicators for all kinds of 'ordering' fields: field names, method on the model admin and model itself, and other callables. See #17252. """ models = [ (AdminOrderedField, "adminorderedfield"), (AdminOrderedModelMethod, "adminorderedmodelmethod"), (AdminOrderedAdminMethod, "adminorderedadminmethod"), (AdminOrderedCallable, "adminorderedcallable"), ] for model, url in models: model.objects.create(stuff="The Last Item", order=3) model.objects.create(stuff="The First Item", order=1) model.objects.create(stuff="The Middle Item", order=2) response = self.client.get( reverse("admin:admin_views_%s_changelist" % url), {} ) # Should have 3 columns including action checkbox col. self.assertContains(response, '<th scope="col"', count=3, msg_prefix=url) # Check if the correct column was selected. 2 is the index of the # 'order' column in the model admin's 'list_display' with 0 being # the implicit 'action_checkbox' and 1 being the column 'stuff'. self.assertEqual( response.context["cl"].get_ordering_field_columns(), {2: "asc"} ) # Check order of records. self.assertContentBefore(response, "The First Item", "The Middle Item") self.assertContentBefore(response, "The Middle Item", "The Last Item") def test_has_related_field_in_list_display_fk(self): """Joins shouldn't be performed for <FK>_id fields in list display.""" state = State.objects.create(name="Karnataka") City.objects.create(state=state, name="Bangalore") response = self.client.get(reverse("admin:admin_views_city_changelist"), {}) response.context["cl"].list_display = ["id", "name", "state"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["id", "name", "state_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_has_related_field_in_list_display_o2o(self): """Joins shouldn't be performed for <O2O>_id fields in list display.""" media = Media.objects.create(name="Foo") Vodcast.objects.create(media=media) response = self.client.get(reverse("admin:admin_views_vodcast_changelist"), {}) response.context["cl"].list_display = ["media"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["media_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_limited_filter(self): """ Admin changelist filters do not contain objects excluded via limit_choices_to. """ response = self.client.get(reverse("admin:admin_views_thing_changelist")) self.assertContains( response, '<div id="changelist-filter">', msg_prefix="Expected filter not found in changelist view", ) self.assertNotContains( response, '<a href="?color__id__exact=3">Blue</a>', msg_prefix="Changelist filter not correctly limited by limit_choices_to", ) def test_relation_spanning_filters(self): changelist_url = reverse("admin:admin_views_chapterxtra1_changelist") response = self.client.get(changelist_url) self.assertContains(response, '<div id="changelist-filter">') filters = { "chap__id__exact": { "values": [c.id for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.id == value, }, "chap__title": { "values": [c.title for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.title == value, }, "chap__book__id__exact": { "values": [b.id for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.id == value, }, "chap__book__name": { "values": [b.name for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.name == value, }, "chap__book__promo__id__exact": { "values": [p.id for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( id=value ).exists(), }, "chap__book__promo__name": { "values": [p.name for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( name=value ).exists(), }, # A forward relation (book) after a reverse relation (promo). "guest_author__promo__book__id__exact": { "values": [p.id for p in Book.objects.all()], "test": lambda obj, value: obj.guest_author.promo_set.filter( book=value ).exists(), }, } for filter_path, params in filters.items(): for value in params["values"]: query_string = urlencode({filter_path: value}) # ensure filter link exists self.assertContains(response, '<a href="?%s"' % query_string) # ensure link works filtered_response = self.client.get( "%s?%s" % (changelist_url, query_string) ) self.assertEqual(filtered_response.status_code, 200) # ensure changelist contains only valid objects for obj in filtered_response.context["cl"].queryset.all(): self.assertTrue(params["test"](obj, value)) def test_incorrect_lookup_parameters(self): """Ensure incorrect lookup parameters are handled gracefully.""" changelist_url = reverse("admin:admin_views_thing_changelist") response = self.client.get(changelist_url, {"notarealfield": "5"}) self.assertRedirects(response, "%s?e=1" % changelist_url) # Spanning relationships through a nonexistent related object (Refs #16716) response = self.client.get(changelist_url, {"notarealfield__whatever": "5"}) self.assertRedirects(response, "%s?e=1" % changelist_url) response = self.client.get( changelist_url, {"color__id__exact": "StringNotInteger!"} ) self.assertRedirects(response, "%s?e=1" % changelist_url) # Regression test for #18530 response = self.client.get(changelist_url, {"pub_date__gte": "foo"}) self.assertRedirects(response, "%s?e=1" % changelist_url) def test_isnull_lookups(self): """Ensure is_null is handled correctly.""" Article.objects.create( title="I Could Go Anywhere", content="Versatile", date=datetime.datetime.now(), ) changelist_url = reverse("admin:admin_views_article_changelist") response = self.client.get(changelist_url) self.assertContains(response, "4 articles") response = self.client.get(changelist_url, {"section__isnull": "false"}) self.assertContains(response, "3 articles") response = self.client.get(changelist_url, {"section__isnull": "0"}) self.assertContains(response, "3 articles") response = self.client.get(changelist_url, {"section__isnull": "true"}) self.assertContains(response, "1 article") response = self.client.get(changelist_url, {"section__isnull": "1"}) self.assertContains(response, "1 article") def test_logout_and_password_change_URLs(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains( response, '<form id="logout-form" method="post" action="%s">' % reverse("admin:logout"), ) self.assertContains( response, '<a href="%s">' % reverse("admin:password_change") ) def test_named_group_field_choices_change_list(self): """ Ensures the admin changelist shows correct values in the relevant column for rows corresponding to instances of a model in which a named group has been used in the choices option of a field. """ link1 = reverse("admin:admin_views_fabric_change", args=(self.fab1.pk,)) link2 = reverse("admin:admin_views_fabric_change", args=(self.fab2.pk,)) response = self.client.get(reverse("admin:admin_views_fabric_changelist")) fail_msg = ( "Changelist table isn't showing the right human-readable values " "set by a model field 'choices' option named group." ) self.assertContains( response, '<a href="%s">Horizontal</a>' % link1, msg_prefix=fail_msg, html=True, ) self.assertContains( response, '<a href="%s">Vertical</a>' % link2, msg_prefix=fail_msg, html=True, ) def test_named_group_field_choices_filter(self): """ Ensures the filter UI shows correctly when at least one named group has been used in the choices option of a model field. """ response = self.client.get(reverse("admin:admin_views_fabric_changelist")) fail_msg = ( "Changelist filter isn't showing options contained inside a model " "field 'choices' option named group." ) self.assertContains(response, '<div id="changelist-filter">') self.assertContains( response, '<a href="?surface__exact=x">Horizontal</a>', msg_prefix=fail_msg, html=True, ) self.assertContains( response, '<a href="?surface__exact=y">Vertical</a>', msg_prefix=fail_msg, html=True, ) def test_change_list_null_boolean_display(self): Post.objects.create(public=None) response = self.client.get(reverse("admin:admin_views_post_changelist")) self.assertContains(response, "icon-unknown.svg") def test_display_decorator_with_boolean_and_empty_value(self): msg = ( "The boolean and empty_value arguments to the @display decorator " "are mutually exclusive." ) with self.assertRaisesMessage(ValueError, msg): class BookAdmin(admin.ModelAdmin): @admin.display(boolean=True, empty_value="(Missing)") def is_published(self, obj): return obj.publish_date is not None def test_i18n_language_non_english_default(self): """ Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English but the selected language is English. See #13388 and #3594 for more details. """ with self.settings(LANGUAGE_CODE="fr"), translation.override("en-us"): response = self.client.get(reverse("admin:jsi18n")) self.assertNotContains(response, "Choisir une heure") def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), translation.override("none"): response = self.client.get(reverse("admin:jsi18n")) self.assertContains(response, "Choisir une heure") def test_jsi18n_with_context(self): response = self.client.get(reverse("admin-extra-context:jsi18n")) self.assertEqual(response.status_code, 200) def test_jsi18n_format_fallback(self): """ The JavaScript i18n view doesn't return localized date/time formats when the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="ru"), translation.override("none"): response = self.client.get(reverse("admin:jsi18n")) self.assertNotContains(response, "%d.%m.%Y %H:%M:%S") self.assertContains(response, "%Y-%m-%d %H:%M:%S") def test_disallowed_filtering(self): with self.assertLogs("django.security.DisallowedModelAdminLookup", "ERROR"): response = self.client.get( "%s?owner__email__startswith=fuzzy" % reverse("admin:admin_views_album_changelist") ) self.assertEqual(response.status_code, 400) # Filters are allowed if explicitly included in list_filter response = self.client.get( "%s?color__value__startswith=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) response = self.client.get( "%s?color__value=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) # Filters should be allowed if they involve a local field without the # need to allow them in list_filter or date_hierarchy. response = self.client.get( "%s?age__gt=30" % reverse("admin:admin_views_person_changelist") ) self.assertEqual(response.status_code, 200) e1 = Employee.objects.create( name="Anonymous", gender=1, age=22, alive=True, code="123" ) e2 = Employee.objects.create( name="Visitor", gender=2, age=19, alive=True, code="124" ) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e1) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e2) response = self.client.get(reverse("admin:admin_views_workhour_changelist")) self.assertContains(response, "employee__person_ptr__exact") response = self.client.get( "%s?employee__person_ptr__exact=%d" % (reverse("admin:admin_views_workhour_changelist"), e1.pk) ) self.assertEqual(response.status_code, 200) def test_disallowed_to_field(self): url = reverse("admin:admin_views_section_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "missing_field"}) self.assertEqual(response.status_code, 400) # Specifying a field that is not referred by any other model registered # to this admin site should raise an exception. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get( reverse("admin:admin_views_section_changelist"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) # Primary key should always be allowed, even if the referenced model # isn't registered. response = self.client.get( reverse("admin:admin_views_notreferenced_changelist"), {TO_FIELD_VAR: "id"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced by another model though a m2m should be # allowed. response = self.client.get( reverse("admin:admin_views_recipe_changelist"), {TO_FIELD_VAR: "rname"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced through a reverse m2m relationship # should be allowed. response = self.client.get( reverse("admin:admin_views_ingredient_changelist"), {TO_FIELD_VAR: "iname"} ) self.assertEqual(response.status_code, 200) # Specifying a field that is not referred by any other model directly # registered to this admin site but registered through inheritance # should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyparent_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # Specifying a field that is only referred to by a inline of a # registered model should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyinline_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # #25622 - Specifying a field of a model only referred by a generic # relation should raise DisallowedModelAdminToField. url = reverse("admin:admin_views_referencedbygenrel_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "object_id"}) self.assertEqual(response.status_code, 400) # We also want to prevent the add, change, and delete views from # leaking a disallowed field value. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post( reverse("admin:admin_views_section_add"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) section = Section.objects.create() url = reverse("admin:admin_views_section_change", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) url = reverse("admin:admin_views_section_delete", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) def test_allowed_filtering_15103(self): """ Regressions test for ticket 15103 - filtering on fields defined in a ForeignKey 'limit_choices_to' should be allowed, otherwise raw_id_fields can break. """ # Filters should be allowed if they are defined on a ForeignKey # pointing to this model. url = "%s?leader__name=Palin&leader__age=27" % reverse( "admin:admin_views_inquisition_changelist" ) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_popup_dismiss_related(self): """ Regression test for ticket 20664 - ensure the pk is properly quoted. """ actor = Actor.objects.create(name="Palin", age=27) response = self.client.get( "%s?%s" % (reverse("admin:admin_views_actor_changelist"), IS_POPUP_VAR) ) self.assertContains(response, 'data-popup-opener="%s"' % actor.pk) def test_hide_change_password(self): """ Tests if the "change password" link in the admin is hidden if the User does not have a usable password set. (against 9bea85795705d015cdadc82c68b99196a8554f5c) """ user = User.objects.get(username="super") user.set_unusable_password() user.save() self.client.force_login(user) response = self.client.get(reverse("admin:index")) self.assertNotContains( response, reverse("admin:password_change"), msg_prefix=( 'The "change password" link should not be displayed if a user does not ' "have a usable password." ), ) def test_change_view_with_show_delete_extra_context(self): """ The 'show_delete' context variable in the admin's change view controls the display of the delete button. """ instance = UndeletableObject.objects.create(name="foo") response = self.client.get( reverse("admin:admin_views_undeletableobject_change", args=(instance.pk,)) ) self.assertNotContains(response, "deletelink") def test_change_view_logs_m2m_field_changes(self): """Changes to ManyToManyFields are included in the object's history.""" pizza = ReadablePizza.objects.create(name="Cheese") cheese = Topping.objects.create(name="cheese") post_data = {"name": pizza.name, "toppings": [cheese.pk]} response = self.client.post( reverse("admin:admin_views_readablepizza_change", args=(pizza.pk,)), post_data, ) self.assertRedirects( response, reverse("admin:admin_views_readablepizza_changelist") ) pizza_ctype = ContentType.objects.get_for_model( ReadablePizza, for_concrete_model=False ) log = LogEntry.objects.filter( content_type=pizza_ctype, object_id=pizza.pk ).first() self.assertEqual(log.get_change_message(), "Changed Toppings.") def test_allows_attributeerror_to_bubble_up(self): """ AttributeErrors are allowed to bubble when raised inside a change list view. Requires a model to be created so there's something to display. Refs: #16655, #18593, and #18747 """ Simple.objects.create() with self.assertRaises(AttributeError): self.client.get(reverse("admin:admin_views_simple_changelist")) def test_changelist_with_no_change_url(self): """ ModelAdmin.changelist_view shouldn't result in a NoReverseMatch if url for change_view is removed from get_urls (#20934). """ o = UnchangeableObject.objects.create() response = self.client.get( reverse("admin:admin_views_unchangeableobject_changelist") ) # Check the format of the shown object -- shouldn't contain a change link self.assertContains( response, '<th class="field-__str__">%s</th>' % o, html=True ) def test_invalid_appindex_url(self): """ #21056 -- URL reversing shouldn't work for nonexistent apps. """ good_url = "/test_admin/admin/admin_views/" confirm_good_url = reverse( "admin:app_list", kwargs={"app_label": "admin_views"} ) self.assertEqual(good_url, confirm_good_url) with self.assertRaises(NoReverseMatch): reverse("admin:app_list", kwargs={"app_label": "this_should_fail"}) with self.assertRaises(NoReverseMatch): reverse("admin:app_list", args=("admin_views2",)) def test_resolve_admin_views(self): index_match = resolve("/test_admin/admin4/") list_match = resolve("/test_admin/admin4/auth/user/") self.assertIs(index_match.func.admin_site, customadmin.simple_site) self.assertIsInstance( list_match.func.model_admin, customadmin.CustomPwdTemplateUserAdmin ) def test_adminsite_display_site_url(self): """ #13749 - Admin should display link to front-end site 'View site' """ url = reverse("admin:index") response = self.client.get(url) self.assertEqual(response.context["site_url"], "/my-site-url/") self.assertContains(response, '<a href="/my-site-url/">View site</a>') def test_date_hierarchy_empty_queryset(self): self.assertIs(Question.objects.exists(), False) response = self.client.get(reverse("admin:admin_views_answer2_changelist")) self.assertEqual(response.status_code, 200) @override_settings(TIME_ZONE="America/Sao_Paulo", USE_TZ=True) def test_date_hierarchy_timezone_dst(self): # This datetime doesn't exist in this timezone due to DST. for date in make_aware_datetimes( datetime.datetime(2016, 10, 16, 15), "America/Sao_Paulo" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=16") self.assertContains(response, "question__expires__month=10") self.assertContains(response, "question__expires__year=2016") @override_settings(TIME_ZONE="America/Los_Angeles", USE_TZ=True) def test_date_hierarchy_local_date_differ_from_utc(self): # This datetime is 2017-01-01 in UTC. for date in make_aware_datetimes( datetime.datetime(2016, 12, 31, 16), "America/Los_Angeles" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=31") self.assertContains(response, "question__expires__month=12") self.assertContains(response, "question__expires__year=2016") def test_sortable_by_columns_subset(self): expected_sortable_fields = ("date", "callable_year") expected_not_sortable_fields = ( "content", "model_year", "modeladmin_year", "model_year_reversed", "section", ) response = self.client.get(reverse("admin6:admin_views_article_changelist")) for field_name in expected_sortable_fields: self.assertContains( response, '<th scope="col" class="sortable column-%s">' % field_name ) for field_name in expected_not_sortable_fields: self.assertContains( response, '<th scope="col" class="column-%s">' % field_name ) def test_get_sortable_by_columns_subset(self): response = self.client.get(reverse("admin6:admin_views_actor_changelist")) self.assertContains(response, '<th scope="col" class="sortable column-age">') self.assertContains(response, '<th scope="col" class="column-name">') def test_sortable_by_no_column(self): expected_not_sortable_fields = ("title", "book") response = self.client.get(reverse("admin6:admin_views_chapter_changelist")) for field_name in expected_not_sortable_fields: self.assertContains( response, '<th scope="col" class="column-%s">' % field_name ) self.assertNotContains(response, '<th scope="col" class="sortable column') def test_get_sortable_by_no_column(self): response = self.client.get(reverse("admin6:admin_views_color_changelist")) self.assertContains(response, '<th scope="col" class="column-value">') self.assertNotContains(response, '<th scope="col" class="sortable column') def test_app_index_context(self): response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains( response, "<title>Admin_Views administration | Django site admin</title>", ) self.assertEqual(response.context["title"], "Admin_Views administration") self.assertEqual(response.context["app_label"], "admin_views") # Models are sorted alphabetically by default. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models)) def test_app_index_context_reordered(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertContains( response, "<title>Admin_Views administration | Django site admin</title>", ) # Models are in reverse order. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models, reverse=True)) def test_change_view_subtitle_per_object(self): response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "<title>Article 1 | Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") self.assertContains(response, "<h2>Article 1</h2>") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "<title>Article 2 | Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") self.assertContains(response, "<h2>Article 2</h2>") def test_view_subtitle_per_object(self): viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True, ) viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", Article._meta)), ) self.client.force_login(viewuser) response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "<title>Article 1 | View article | Django site admin</title>", ) self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<h2>Article 1</h2>") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "<title>Article 2 | View article | Django site admin</title>", ) self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<h2>Article 2</h2>") def test_formset_kwargs_can_be_overridden(self): response = self.client.get(reverse("admin:admin_views_city_add")) self.assertContains(response, "overridden_name") def test_render_views_no_subtitle(self): tests = [ reverse("admin:index"), reverse("admin:password_change"), reverse("admin:app_list", args=("admin_views",)), reverse("admin:admin_views_article_delete", args=(self.a1.pk,)), reverse("admin:admin_views_article_history", args=(self.a1.pk,)), ] for url in tests: with self.subTest(url=url): with self.assertNoLogs("django.template", "DEBUG"): self.client.get(url) # Login must be after logout. with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:logout")) self.client.get(reverse("admin:login")) def test_render_delete_selected_confirmation_no_subtitle(self): post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": self.a1.pk, } with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:admin_views_article_changelist"), post_data) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ] ) def test_password_change_helptext(self): response = self.client.get(reverse("admin:password_change")) self.assertContains( response, '<div class="help" id="id_new_password1_helptext">' ) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ], TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", # Put this app's and the shared tests templates dirs in DIRS to # take precedence over the admin's templates dir. "DIRS": [ os.path.join(os.path.dirname(__file__), "templates"), os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminCustomTemplateTests(AdminViewBasicTestCase): def test_custom_model_admin_templates(self): # Test custom change list template with custom extra context response = self.client.get( reverse("admin:admin_views_customarticle_changelist") ) self.assertContains(response, "var hello = 'Hello!';") self.assertTemplateUsed(response, "custom_admin/change_list.html") # Test custom add form template response = self.client.get(reverse("admin:admin_views_customarticle_add")) self.assertTemplateUsed(response, "custom_admin/add_form.html") # Add an article so we can test delete, change, and history views post = self.client.post( reverse("admin:admin_views_customarticle_add"), { "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", }, ) self.assertRedirects( post, reverse("admin:admin_views_customarticle_changelist") ) self.assertEqual(CustomArticle.objects.count(), 1) article_pk = CustomArticle.objects.all()[0].pk # Test custom delete, change, and object history templates # Test custom change form template response = self.client.get( reverse("admin:admin_views_customarticle_change", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/change_form.html") response = self.client.get( reverse("admin:admin_views_customarticle_delete", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/delete_confirmation.html") response = self.client.post( reverse("admin:admin_views_customarticle_changelist"), data={ "index": 0, "action": ["delete_selected"], "_selected_action": ["1"], }, ) self.assertTemplateUsed( response, "custom_admin/delete_selected_confirmation.html" ) response = self.client.get( reverse("admin:admin_views_customarticle_history", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/object_history.html") # A custom popup response template may be specified by # ModelAdmin.popup_response_template. response = self.client.post( reverse("admin:admin_views_customarticle_add") + "?%s=1" % IS_POPUP_VAR, { "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", IS_POPUP_VAR: "1", }, ) self.assertEqual(response.template_name, "custom_admin/popup_response.html") def test_extended_bodyclass_template_change_form(self): """ The admin/change_form.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "bodyclass_consistency_check ") def test_change_password_template(self): user = User.objects.get(username="super") response = self.client.get( reverse("admin:auth_user_password_change", args=(user.id,)) ) # The auth/user/change_password.html template uses super in the # bodyclass block. self.assertContains(response, "bodyclass_consistency_check ") # When a site has multiple passwords in the browser's password manager, # a browser pop up asks which user the new password is for. To prevent # this, the username is added to the change password form. self.assertContains( response, '<input type="text" name="username" value="super" class="hidden">' ) # help text for passwords has an id. self.assertContains( response, '<div class="help" id="id_password1_helptext"><ul><li>' "Your password can’t be too similar to your other personal information." "</li><li>Your password can’t be entirely numeric.</li></ul></div>", ) self.assertContains( response, '<div class="help" id="id_password2_helptext">' "Enter the same password as before, for verification.</div>", ) def test_extended_bodyclass_template_index(self): """ The admin/index.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:index")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_change_list(self): """ The admin/change_list.html' template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_login(self): """ The admin/login.html template uses block.super in the bodyclass block. """ self.client.logout() response = self.client.get(reverse("admin:login")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_delete_confirmation(self): """ The admin/delete_confirmation.html template uses block.super in the bodyclass block. """ group = Group.objects.create(name="foogroup") response = self.client.get(reverse("admin:auth_group_delete", args=(group.id,))) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_delete_selected_confirmation(self): """ The admin/delete_selected_confirmation.html template uses block.super in bodyclass block. """ group = Group.objects.create(name="foogroup") post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": group.id, } response = self.client.post(reverse("admin:auth_group_changelist"), post_data) self.assertEqual(response.context["site_header"], "Django administration") self.assertContains(response, "bodyclass_consistency_check ") def test_filter_with_custom_template(self): """ A custom template can be used to render an admin filter. """ response = self.client.get(reverse("admin:admin_views_color2_changelist")) self.assertTemplateUsed(response, "custom_filter_template.html") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewFormUrlTest(TestCase): current_app = "admin3" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_change_form_URL_has_correct_value(self): """ change_view has form_url in response.context """ response = self.client.get( reverse( "admin:admin_views_section_change", args=(self.s1.pk,), current_app=self.current_app, ) ) self.assertIn( "form_url", response.context, msg="form_url not present in response.context" ) self.assertEqual(response.context["form_url"], "pony") def test_initial_data_can_be_overridden(self): """ The behavior for setting initial form data can be overridden in the ModelAdmin class. Usually, the initial value is set via the GET params. """ response = self.client.get( reverse("admin:admin_views_restaurant_add", current_app=self.current_app), {"name": "test_value"}, ) # this would be the usual behaviour self.assertNotContains(response, 'value="test_value"') # this is the overridden behaviour self.assertContains(response, 'value="overridden_value"') @override_settings(ROOT_URLCONF="admin_views.urls") class AdminJavaScriptTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_js_minified_only_if_debug_is_false(self): """ The minified versions of the JS files are only used when DEBUG is False. """ with override_settings(DEBUG=False): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertNotContains(response, "vendor/jquery/jquery.js") self.assertContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") with override_settings(DEBUG=True): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "vendor/jquery/jquery.js") self.assertNotContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") @override_settings(ROOT_URLCONF="admin_views.urls") class SaveAsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_as_duplication(self): """'save as' creates a new person""" post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), post_data ) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) new_person = Person.objects.latest("id") self.assertRedirects( response, reverse("admin:admin_views_person_change", args=(new_person.pk,)) ) def test_save_as_continue_false(self): """ Saving a new object using "Save as new" redirects to the changelist instead of the change view when ModelAdmin.save_as_continue=False. """ post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} url = reverse( "admin:admin_views_person_change", args=(self.per1.pk,), current_app=site2.name, ) response = self.client.post(url, post_data) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) self.assertRedirects( response, reverse("admin:admin_views_person_changelist", current_app=site2.name), ) def test_save_as_new_with_validation_errors(self): """ When you click "Save as new" and have a validation error, you only see the "Save as new" button and not the other save buttons, and that only the "Save as" button is visible. """ response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), { "_saveasnew": "", "gender": "invalid", "_addanother": "fail", }, ) self.assertContains(response, "Please correct the errors below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_validation_errors_with_inlines(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "Child", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "_invalid", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_inlines_with_validation_errors(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "_invalid", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "Father", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) @override_settings(ROOT_URLCONF="admin_views.urls") class CustomModelAdminTest(AdminViewBasicTestCase): def test_custom_admin_site_login_form(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) login = self.client.post( reverse("admin2:login"), { REDIRECT_FIELD_NAME: reverse("admin2:index"), "username": "customform", "password": "secret", }, follow=True, ) self.assertIsInstance(login, TemplateResponse) self.assertContains(login, "custom form error") self.assertContains(login, "path/to/media.css") def test_custom_admin_site_login_template(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/login.html") self.assertContains(response, "Hello from a custom login template") def test_custom_admin_site_logout_template(self): response = self.client.post(reverse("admin2:logout")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/logout.html") self.assertContains(response, "Hello from a custom logout template") def test_custom_admin_site_index_view_and_template(self): response = self.client.get(reverse("admin2:index")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/index.html") self.assertContains(response, "Hello from a custom index template *bar*") def test_custom_admin_site_app_index_view_and_template(self): response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/app_index.html") self.assertContains(response, "Hello from a custom app_index template") def test_custom_admin_site_password_change_template(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains( response, "Hello from a custom password change form template" ) def test_custom_admin_site_password_change_with_extra_context(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains(response, "eggs") def test_custom_admin_site_password_change_done_template(self): response = self.client.get(reverse("admin2:password_change_done")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_done.html") self.assertContains( response, "Hello from a custom password change done template" ) def test_custom_admin_site_view(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:my_view")) self.assertEqual(response.content, b"Django is a magical pony!") def test_pwd_change_custom_template(self): self.client.force_login(self.superuser) su = User.objects.get(username="super") response = self.client.get( reverse("admin4:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 200) def get_perm(Model, codename): """Return the permission object, for the Model""" ct = ContentType.objects.get_for_model(Model, for_concrete_model=False) return Permission.objects.get(content_type=ct, codename=codename) @override_settings( ROOT_URLCONF="admin_views.urls", # Test with the admin's documented list of required context processors. TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.nostaffuser = User.objects.create_user( username="nostaff", password="secret" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, another_section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) # Setup permissions, for our users who can add, change, and delete. opts = Article._meta # User who can view Articles cls.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", opts)) ) # User who can add Articles cls.adduser.user_permissions.add( get_perm(Article, get_permission_codename("add", opts)) ) # User who can change Articles cls.changeuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) cls.nostaffuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) # User who can delete Articles cls.deleteuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", opts)) ) cls.deleteuser.user_permissions.add( get_perm(Section, get_permission_codename("delete", Section._meta)) ) # login POST dicts cls.index_url = reverse("admin:index") cls.super_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "super", "password": "secret", } cls.super_email_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "[email protected]", "password": "secret", } cls.super_email_bad_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "[email protected]", "password": "notsecret", } cls.adduser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "adduser", "password": "secret", } cls.changeuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "changeuser", "password": "secret", } cls.deleteuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "deleteuser", "password": "secret", } cls.nostaff_login = { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "nostaff", "password": "secret", } cls.joepublic_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "joepublic", "password": "secret", } cls.viewuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "viewuser", "password": "secret", } cls.no_username_login = { REDIRECT_FIELD_NAME: cls.index_url, "password": "secret", } def test_login(self): """ Make sure only staff members can log in. Successful posts to the login page will redirect to the original url. Unsuccessful attempts will continue to render the login page with a 200 status code. """ login_url = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) # Super User response = self.client.get(self.index_url) self.assertRedirects(response, login_url) login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Test if user enters email address response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # only correct passwords get a username hint login = self.client.post(login_url, self.super_email_bad_login) self.assertContains(login, ERROR_MESSAGE) new_user = User(username="jondoe", password="secret", email="[email protected]") new_user.save() # check to ensure if there are multiple email addresses a user doesn't get a 500 login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # View User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.viewuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Add User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.adduser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Change User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.changeuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Delete User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.deleteuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Regular User should not be able to login. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Requests without username should not return 500 errors. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.no_username_login) self.assertEqual(login.status_code, 200) self.assertFormError( login.context["form"], "username", ["This field is required."] ) def test_login_redirect_for_direct_get(self): """ Login redirect should be to the admin index page when going directly to /admin/login/. """ response = self.client.get(reverse("admin:login")) self.assertEqual(response.status_code, 200) self.assertEqual(response.context[REDIRECT_FIELD_NAME], reverse("admin:index")) def test_login_has_permission(self): # Regular User should not be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.joepublic_login ) self.assertContains(login, "permission denied") # User with permissions should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.nostaff_login ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) # Staff should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "deleteuser", "password": "secret", }, ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) def test_login_successfully_redirects_to_original_URL(self): response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) query_string = "the-answer=42" redirect_url = "%s?%s" % (self.index_url, query_string) new_next = {REDIRECT_FIELD_NAME: redirect_url} post_data = self.super_login.copy() post_data.pop(REDIRECT_FIELD_NAME) login = self.client.post( "%s?%s" % (reverse("admin:login"), urlencode(new_next)), post_data ) self.assertRedirects(login, redirect_url) def test_double_login_is_not_allowed(self): """Regression test for #19327""" login_url = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with non-admin user fails login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with admin user while already logged in login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) def test_login_page_notice_for_non_staff_users(self): """ A logged-in non-staff user trying to access the admin index should be presented with the login page and a hint indicating that the current user doesn't have access to it. """ hint_template = "You are authenticated as {}" # Anonymous user should not be shown the hint response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertNotContains(response, hint_template.format(""), status_code=200) # Non-staff user should be shown the hint self.client.force_login(self.nostaffuser) response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertContains( response, hint_template.format(self.nostaffuser.username), status_code=200 ) def test_add_view(self): """Test add view restricts access and actually adds items.""" add_dict = { "title": "Døm ikke", "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } # Change User should not have access to add articles self.client.force_login(self.changeuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.post(reverse("admin:logout")) # View User should not have access to add articles self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) # Now give the user permission to add but not change. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.context["title"], "Add article") self.assertContains(response, "<title>Add article | Django site admin</title>") self.assertContains( response, '<input type="submit" value="Save and view" name="_continue">' ) post = self.client.post( reverse("admin:admin_views_article_add"), add_dict, follow=False ) self.assertEqual(post.status_code, 302) self.assertEqual(Article.objects.count(), 4) article = Article.objects.latest("pk") response = self.client.get( reverse("admin:admin_views_article_change", args=(article.pk,)) ) self.assertContains( response, '<li class="success">The article “Døm ikke” was added successfully.</li>', ) article.delete() self.client.post(reverse("admin:logout")) # Add user may login and POST to add view, then redirect to admin root self.client.force_login(self.adduser) addpage = self.client.get(reverse("admin:admin_views_article_add")) change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse( "admin:admin_views_article_changelist" ) self.assertNotContains( addpage, change_list_link, msg_prefix=( "User restricted to add permission is given link to change list view " "in breadcrumbs." ), ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "Greetings from a created object") self.client.post(reverse("admin:logout")) # The addition was logged correctly addition_log = LogEntry.objects.all()[0] new_article = Article.objects.last() article_ct = ContentType.objects.get_for_model(Article) self.assertEqual(addition_log.user_id, self.adduser.pk) self.assertEqual(addition_log.content_type_id, article_ct.pk) self.assertEqual(addition_log.object_id, str(new_article.pk)) self.assertEqual(addition_log.object_repr, "Døm ikke") self.assertEqual(addition_log.action_flag, ADDITION) self.assertEqual(addition_log.get_change_message(), "Added.") # Super can add too, but is redirected to the change list view self.client.force_login(self.superuser) addpage = self.client.get(reverse("admin:admin_views_article_add")) self.assertContains( addpage, change_list_link, msg_prefix=( "Unrestricted user is not given link to change list view in " "breadcrumbs." ), ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, reverse("admin:admin_views_article_changelist")) self.assertEqual(Article.objects.count(), 5) self.client.post(reverse("admin:logout")) # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error self.client.force_login(self.joepublicuser) # Check and make sure that if user expires, data still persists self.client.force_login(self.superuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) @mock.patch("django.contrib.admin.options.InlineModelAdmin.has_change_permission") def test_add_view_with_view_only_inlines(self, has_change_permission): """User with add permission to a section but view-only for inlines.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("add", Section._meta)) ) self.client.force_login(self.viewuser) # Valid POST creates a new section. data = { "name": "New obj", "article_set-TOTAL_FORMS": 0, "article_set-INITIAL_FORMS": 0, } response = self.client.post(reverse("admin:admin_views_section_add"), data) self.assertRedirects(response, reverse("admin:index")) self.assertEqual(Section.objects.latest("id").name, data["name"]) # InlineModelAdmin.has_change_permission()'s obj argument is always # None during object add. self.assertEqual( [obj for (request, obj), _ in has_change_permission.call_args_list], [None, None], ) def test_change_view(self): """Change view should restrict access and allow users to edit items.""" change_dict = { "title": "Ikke fordømt", "content": "<p>edited article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) article_changelist_url = reverse("admin:admin_views_article_changelist") # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get(article_changelist_url) self.assertEqual(response.status_code, 403) response = self.client.get(article_change_url) self.assertEqual(response.status_code, 403) post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view articles but not make changes. self.client.force_login(self.viewuser) response = self.client.get(article_changelist_url) self.assertContains( response, "<title>Select article to view | Django site admin</title>", ) self.assertContains(response, "<h1>Select article to view</h1>") self.assertEqual(response.context["title"], "Select article to view") response = self.client.get(article_change_url) self.assertContains(response, "<title>View article | Django site admin</title>") self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<label>Extra form field:</label>") self.assertContains( response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close' "</a>", ) self.assertEqual(response.context["title"], "View article") post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.assertEqual( Article.objects.get(pk=self.a1.pk).content, "<p>Middle content</p>" ) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get(article_changelist_url) self.assertEqual(response.context["title"], "Select article to change") self.assertContains( response, "<title>Select article to change | Django site admin</title>", ) self.assertContains(response, "<h1>Select article to change</h1>") response = self.client.get(article_change_url) self.assertEqual(response.context["title"], "Change article") self.assertContains( response, "<title>Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") post = self.client.post(article_change_url, change_dict) self.assertRedirects(post, article_changelist_url) self.assertEqual( Article.objects.get(pk=self.a1.pk).content, "<p>edited article</p>" ) # one error in form should produce singular error message, multiple # errors plural. change_dict["title"] = "" post = self.client.post(article_change_url, change_dict) self.assertContains( post, "Please correct the error below.", msg_prefix=( "Singular error message not found in response to post with one error" ), ) change_dict["content"] = "" post = self.client.post(article_change_url, change_dict) self.assertContains( post, "Please correct the errors below.", msg_prefix=( "Plural error message not found in response to post with multiple " "errors" ), ) self.client.post(reverse("admin:logout")) # Test redirection when using row-level change permissions. Refs #11513. r1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") r2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") r3 = RowLevelChangePermissionModel.objects.create(id=3, name="odd id mult 3") r6 = RowLevelChangePermissionModel.objects.create(id=6, name="even id mult 3") change_url_1 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r1.pk,) ) change_url_2 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r2.pk,) ) change_url_3 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r3.pk,) ) change_url_6 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r6.pk,) ) logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1) self.assertEqual(response.status_code, 403) response = self.client.post(change_url_1, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertEqual(response.status_code, 403) response = self.client.get(change_url_2) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_2, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertRedirects(response, self.index_url) response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {"name": "changed"}) self.assertEqual(response.status_code, 403) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=3).name, "odd id mult 3", ) response = self.client.get(change_url_6) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_6, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=6).name, "changed" ) self.assertRedirects(response, self.index_url) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_1, {"name": "changed"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertContains(response, "login-form") response = self.client.get(change_url_2, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_2, {"name": "changed again"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_change_view_without_object_change_permission(self): """ The object should be read-only if the user has permission to view it and change objects of that type but not to change the current object. """ change_url = reverse("admin9:admin_views_article_change", args=(self.a1.pk,)) self.client.force_login(self.viewuser) response = self.client.get(change_url) self.assertEqual(response.context["title"], "View article") self.assertContains(response, "<title>View article | Django site admin</title>") self.assertContains(response, "<h1>View article</h1>") self.assertContains( response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close' "</a>", ) def test_change_view_save_as_new(self): """ 'Save as new' should raise PermissionDenied for users without the 'add' permission. """ change_dict_save_as_new = { "_saveasnew": "Save as new", "title": "Ikke fordømt", "content": "<p>edited article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) # Add user can perform "Save as new". article_count = Article.objects.count() self.client.force_login(self.adduser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), article_count + 1) self.client.logout() # Change user cannot perform "Save as new" (no 'add' permission). article_count = Article.objects.count() self.client.force_login(self.changeuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), article_count) # User with both add and change permissions should be redirected to the # change page for the newly created object. article_count = Article.objects.count() self.client.force_login(self.superuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(Article.objects.count(), article_count + 1) new_article = Article.objects.latest("id") self.assertRedirects( post, reverse("admin:admin_views_article_change", args=(new_article.pk,)) ) def test_change_view_with_view_only_inlines(self): """ User with change permission to a section but view-only for inlines. """ self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # Valid POST changes the name. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 3, "article_set-INITIAL_FORMS": 3, } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) def test_change_view_with_view_only_last_inline(self): self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("view", Section._meta)) ) self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # The last inline is not marked as empty. self.assertContains(response, 'id="article_set-2"') def test_change_view_with_view_and_add_inlines(self): """User has view and add permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) # Valid POST creates a new article. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-3-id": [""], "article_set-3-title": ["A title"], "article_set-3-content": ["Added content"], "article_set-3-date_0": ["2008-3-18"], "article_set-3-date_1": ["11:54:58"], "article_set-3-section": [str(self.s1.pk)], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) self.assertEqual(Article.objects.count(), 4) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) def test_change_view_with_view_and_delete_inlines(self): """User has view and delete permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } # Inline POST details are ignored without delete permission. response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 3) # Deletion successful when delete permission is added. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", Article._meta)) ) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 2) def test_delete_view(self): """Delete view should restrict access and actually delete items.""" delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_article_delete", args=(self.a1.pk,)) # add user should not be able to delete articles self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # view user should not be able to delete articles self.client.force_login(self.viewuser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # Delete user can delete self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Articles: 3</li>") # test response contains link to related Article self.assertContains(response, "admin_views/article/%s/" % self.a1.pk) response = self.client.get(delete_url) self.assertContains(response, "admin_views/article/%s/" % self.a1.pk) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Articles: 1</li>") post = self.client.post(delete_url, delete_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Greetings from a deleted object") article_ct = ContentType.objects.get_for_model(Article) logged = LogEntry.objects.get(content_type=article_ct, action_flag=DELETION) self.assertEqual(logged.object_id, str(self.a1.pk)) def test_delete_view_with_no_default_permissions(self): """ The delete view allows users to delete collected objects without a 'delete' permission (ReadOnlyPizza.Meta.default_permissions is empty). """ pizza = ReadOnlyPizza.objects.create(name="Double Cheese") delete_url = reverse("admin:admin_views_readonlypizza_delete", args=(pizza.pk,)) self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertContains(response, "admin_views/readonlypizza/%s/" % pizza.pk) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Read only pizzas: 1</li>") post = self.client.post(delete_url, {"post": "yes"}) self.assertRedirects( post, reverse("admin:admin_views_readonlypizza_changelist") ) self.assertEqual(ReadOnlyPizza.objects.count(), 0) def test_delete_view_nonexistent_obj(self): self.client.force_login(self.deleteuser) url = reverse("admin:admin_views_article_delete", args=("nonexistent",)) response = self.client.get(url, follow=True) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["article with ID “nonexistent” doesn’t exist. Perhaps it was deleted?"], ) def test_history_view(self): """History view should restrict access.""" # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view all items self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 200) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 200) # Test redirection when using row-level change permissions. Refs #11513. rl1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") rl2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl1.pk,), ) response = self.client.get(url) self.assertEqual(response.status_code, 403) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl2.pk,), ) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl1.pk,), ) response = self.client.get(url, follow=True) self.assertContains(response, "login-form") url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl2.pk,), ) response = self.client.get(url, follow=True) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_history_view_bad_url(self): self.client.force_login(self.changeuser) response = self.client.get( reverse("admin:admin_views_article_history", args=("foo",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["article with ID “foo” doesn’t exist. Perhaps it was deleted?"], ) def test_conditionally_show_add_section_link(self): """ The foreign key widget should only show the "add related" button if the user has permission to add that related item. """ self.client.force_login(self.adduser) # The user can't add sections yet, so they shouldn't see the "add section" link. url = reverse("admin:admin_views_article_add") add_link_text = "add_id_section" response = self.client.get(url) self.assertNotContains(response, add_link_text) # Allow the user to add sections too. Now they can see the "add section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("add", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertContains(response, add_link_text) def test_conditionally_show_change_section_link(self): """ The foreign key widget should only show the "change related" button if the user has permission to change that related item. """ def get_change_related(response): return ( response.context["adminform"] .form.fields["section"] .widget.can_change_related ) self.client.force_login(self.adduser) # The user can't change sections yet, so they shouldn't see the # "change section" link. url = reverse("admin:admin_views_article_add") change_link_text = "change_id_section" response = self.client.get(url) self.assertFalse(get_change_related(response)) self.assertNotContains(response, change_link_text) # Allow the user to change sections too. Now they can see the # "change section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("change", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertTrue(get_change_related(response)) self.assertContains(response, change_link_text) def test_conditionally_show_delete_section_link(self): """ The foreign key widget should only show the "delete related" button if the user has permission to delete that related item. """ def get_delete_related(response): return ( response.context["adminform"] .form.fields["sub_section"] .widget.can_delete_related ) self.client.force_login(self.adduser) # The user can't delete sections yet, so they shouldn't see the # "delete section" link. url = reverse("admin:admin_views_article_add") delete_link_text = "delete_id_sub_section" response = self.client.get(url) self.assertFalse(get_delete_related(response)) self.assertNotContains(response, delete_link_text) # Allow the user to delete sections too. Now they can see the # "delete section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("delete", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertTrue(get_delete_related(response)) self.assertContains(response, delete_link_text) def test_disabled_permissions_when_logged_in(self): self.client.force_login(self.superuser) superuser = User.objects.get(username="super") superuser.is_active = False superuser.save() response = self.client.get(self.index_url, follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, "Log out") response = self.client.get(reverse("secure_view"), follow=True) self.assertContains(response, 'id="login-form"') def test_disabled_staff_permissions_when_logged_in(self): self.client.force_login(self.superuser) superuser = User.objects.get(username="super") superuser.is_staff = False superuser.save() response = self.client.get(self.index_url, follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, "Log out") response = self.client.get(reverse("secure_view"), follow=True) self.assertContains(response, 'id="login-form"') def test_app_list_permissions(self): """ If a user has no module perms, the app list returns a 404. """ opts = Article._meta change_user = User.objects.get(username="changeuser") permission = get_perm(Article, get_permission_codename("change", opts)) self.client.force_login(self.changeuser) # the user has no module permissions change_user.user_permissions.remove(permission) response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(response.status_code, 404) # the user now has module permissions change_user.user_permissions.add(permission) response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(response.status_code, 200) def test_shortcut_view_only_available_to_staff(self): """ Only admin users should be able to use the admin shortcut view. """ model_ctype = ContentType.objects.get_for_model(ModelWithStringPrimaryKey) obj = ModelWithStringPrimaryKey.objects.create(string_pk="foo") shortcut_url = reverse("admin:view_on_site", args=(model_ctype.pk, obj.pk)) # Not logged in: we should see the login page. response = self.client.get(shortcut_url, follow=True) self.assertTemplateUsed(response, "admin/login.html") # Logged in? Redirect. self.client.force_login(self.superuser) response = self.client.get(shortcut_url, follow=False) # Can't use self.assertRedirects() because User.get_absolute_url() is silly. self.assertEqual(response.status_code, 302) # Domain may depend on contrib.sites tests also run self.assertRegex(response.url, "http://(testserver|example.com)/dummy/foo/") def test_has_module_permission(self): """ has_module_permission() returns True for all users who have any permission for that module (add, change, or delete), so that the module is displayed on the admin index page. """ self.client.force_login(self.superuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.viewuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.adduser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.changeuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.deleteuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") def test_overriding_has_module_permission(self): """ If has_module_permission() always returns False, the module shouldn't be displayed on the admin index page for any users. """ articles = Article._meta.verbose_name_plural.title() sections = Section._meta.verbose_name_plural.title() index_url = reverse("admin7:index") self.client.force_login(self.superuser) response = self.client.get(index_url) self.assertContains(response, sections) self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.viewuser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.adduser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.changeuser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.deleteuser) response = self.client.get(index_url) self.assertNotContains(response, articles) # The app list displays Sections but not Articles as the latter has # ModelAdmin.has_module_permission() = False. self.client.force_login(self.superuser) response = self.client.get(reverse("admin7:app_list", args=("admin_views",))) self.assertContains(response, sections) self.assertNotContains(response, articles) def test_post_save_message_no_forbidden_links_visible(self): """ Post-save message shouldn't contain a link to the change form if the user doesn't have the change permission. """ self.client.force_login(self.adduser) # Emulate Article creation for user with add-only permission. post_data = { "title": "Fun & games", "content": "Some content", "date_0": "2015-10-31", "date_1": "16:35:00", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_article_add"), post_data, follow=True ) self.assertContains( response, '<li class="success">The article “Fun &amp; games” was added successfully.' "</li>", html=True, ) @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewProxyModelPermissionsTests(TestCase): """Tests for proxy models permissions in the admin.""" @classmethod def setUpTestData(cls): cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) # Setup permissions. opts = UserProxy._meta cls.viewuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("view", opts)) ) cls.adduser.user_permissions.add( get_perm(UserProxy, get_permission_codename("add", opts)) ) cls.changeuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("change", opts)) ) cls.deleteuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("delete", opts)) ) # UserProxy instances. cls.user_proxy = UserProxy.objects.create( username="user_proxy", password="secret" ) def test_add(self): self.client.force_login(self.adduser) url = reverse("admin:admin_views_userproxy_add") data = { "username": "can_add", "password": "secret", "date_joined_0": "2019-01-15", "date_joined_1": "16:59:10", } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertTrue(UserProxy.objects.filter(username="can_add").exists()) def test_view(self): self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_userproxy_changelist")) self.assertContains(response, "<h1>Select user proxy to view</h1>") response = self.client.get( reverse("admin:admin_views_userproxy_change", args=(self.user_proxy.pk,)) ) self.assertContains(response, "<h1>View user proxy</h1>") self.assertContains(response, '<div class="readonly">user_proxy</div>') def test_change(self): self.client.force_login(self.changeuser) data = { "password": self.user_proxy.password, "username": self.user_proxy.username, "date_joined_0": self.user_proxy.date_joined.strftime("%Y-%m-%d"), "date_joined_1": self.user_proxy.date_joined.strftime("%H:%M:%S"), "first_name": "first_name", } url = reverse("admin:admin_views_userproxy_change", args=(self.user_proxy.pk,)) response = self.client.post(url, data) self.assertRedirects( response, reverse("admin:admin_views_userproxy_changelist") ) self.assertEqual( UserProxy.objects.get(pk=self.user_proxy.pk).first_name, "first_name" ) def test_delete(self): self.client.force_login(self.deleteuser) url = reverse("admin:admin_views_userproxy_delete", args=(self.user_proxy.pk,)) response = self.client.post(url, {"post": "yes"}, follow=True) self.assertEqual(response.status_code, 200) self.assertFalse(UserProxy.objects.filter(pk=self.user_proxy.pk).exists()) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewsNoUrlTest(TestCase): """Regression test for #17333""" @classmethod def setUpTestData(cls): # User who can change Reports cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.changeuser.user_permissions.add( get_perm(Report, get_permission_codename("change", Report._meta)) ) def test_no_standard_modeladmin_urls(self): """Admin index views don't break when user's ModelAdmin removes standard urls""" self.client.force_login(self.changeuser) r = self.client.get(reverse("admin:index")) # we shouldn't get a 500 error caused by a NoReverseMatch self.assertEqual(r.status_code, 200) self.client.post(reverse("admin:logout")) @skipUnlessDBFeature("can_defer_constraint_checks") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewDeletedObjectsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.v1 = Villain.objects.create(name="Adam") cls.v2 = Villain.objects.create(name="Sue") cls.sv1 = SuperVillain.objects.create(name="Bob") cls.pl1 = Plot.objects.create( name="World Domination", team_leader=cls.v1, contact=cls.v2 ) cls.pl2 = Plot.objects.create( name="World Peace", team_leader=cls.v2, contact=cls.v2 ) cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) cls.pd1 = PlotDetails.objects.create(details="almost finished", plot=cls.pl1) cls.sh1 = SecretHideout.objects.create( location="underground bunker", villain=cls.v1 ) cls.sh2 = SecretHideout.objects.create( location="floating castle", villain=cls.sv1 ) cls.ssh1 = SuperSecretHideout.objects.create( location="super floating castle!", supervillain=cls.sv1 ) cls.cy1 = CyclicOne.objects.create(pk=1, name="I am recursive", two_id=1) cls.cy2 = CyclicTwo.objects.create(pk=1, name="I am recursive too", one_id=1) def setUp(self): self.client.force_login(self.superuser) def test_nesting(self): """ Objects should be nested to display the relationships that cause them to be scheduled for deletion. """ pattern = re.compile( r'<li>Plot: <a href="%s">World Domination</a>\s*<ul>\s*' r'<li>Plot details: <a href="%s">almost finished</a>' % ( reverse("admin:admin_views_plot_change", args=(self.pl1.pk,)), reverse("admin:admin_views_plotdetails_change", args=(self.pd1.pk,)), ) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertRegex(response.content.decode(), pattern) def test_cyclic(self): """ Cyclic relationships should still cause each object to only be listed once. """ one = '<li>Cyclic one: <a href="%s">I am recursive</a>' % ( reverse("admin:admin_views_cyclicone_change", args=(self.cy1.pk,)), ) two = '<li>Cyclic two: <a href="%s">I am recursive too</a>' % ( reverse("admin:admin_views_cyclictwo_change", args=(self.cy2.pk,)), ) response = self.client.get( reverse("admin:admin_views_cyclicone_delete", args=(self.cy1.pk,)) ) self.assertContains(response, one, 1) self.assertContains(response, two, 1) def test_perms_needed(self): self.client.logout() delete_user = User.objects.get(username="deleteuser") delete_user.user_permissions.add( get_perm(Plot, get_permission_codename("delete", Plot._meta)) ) self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_plot_delete", args=(self.pl1.pk,)) ) self.assertContains( response, "your account doesn't have permission to delete the following types of " "objects", ) self.assertContains(response, "<li>plot details</li>") def test_protected(self): q = Question.objects.create(question="Why?") a1 = Answer.objects.create(question=q, answer="Because.") a2 = Answer.objects.create(question=q, answer="Yes.") response = self.client.get( reverse("admin:admin_views_question_delete", args=(q.pk,)) ) self.assertContains( response, "would require deleting the following protected related objects" ) self.assertContains( response, '<li>Answer: <a href="%s">Because.</a></li>' % reverse("admin:admin_views_answer_change", args=(a1.pk,)), ) self.assertContains( response, '<li>Answer: <a href="%s">Yes.</a></li>' % reverse("admin:admin_views_answer_change", args=(a2.pk,)), ) def test_post_delete_protected(self): """ A POST request to delete protected objects should display the page which says the deletion is prohibited. """ q = Question.objects.create(question="Why?") Answer.objects.create(question=q, answer="Because.") response = self.client.post( reverse("admin:admin_views_question_delete", args=(q.pk,)), {"post": "yes"} ) self.assertEqual(Question.objects.count(), 1) self.assertContains( response, "would require deleting the following protected related objects" ) def test_restricted(self): album = Album.objects.create(title="Amaryllis") song = Song.objects.create(album=album, name="Unity") response = self.client.get( reverse("admin:admin_views_album_delete", args=(album.pk,)) ) self.assertContains( response, "would require deleting the following protected related objects", ) self.assertContains( response, '<li>Song: <a href="%s">Unity</a></li>' % reverse("admin:admin_views_song_change", args=(song.pk,)), ) def test_post_delete_restricted(self): album = Album.objects.create(title="Amaryllis") Song.objects.create(album=album, name="Unity") response = self.client.post( reverse("admin:admin_views_album_delete", args=(album.pk,)), {"post": "yes"}, ) self.assertEqual(Album.objects.count(), 1) self.assertContains( response, "would require deleting the following protected related objects", ) def test_not_registered(self): should_contain = """<li>Secret hideout: underground bunker""" response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertContains(response, should_contain, 1) def test_multiple_fkeys_to_same_model(self): """ If a deleted object has two relationships from another model, both of those should be followed in looking for related objects to delete. """ should_contain = '<li>Plot: <a href="%s">World Domination</a>' % reverse( "admin:admin_views_plot_change", args=(self.pl1.pk,) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertContains(response, should_contain) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v2.pk,)) ) self.assertContains(response, should_contain) def test_multiple_fkeys_to_same_instance(self): """ If a deleted object has two relationships pointing to it from another object, the other object should still only be listed once. """ should_contain = '<li>Plot: <a href="%s">World Peace</a></li>' % reverse( "admin:admin_views_plot_change", args=(self.pl2.pk,) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v2.pk,)) ) self.assertContains(response, should_contain, 1) def test_inheritance(self): """ In the case of an inherited model, if either the child or parent-model instance is deleted, both instances are listed for deletion, as well as any relationships they have. """ should_contain = [ '<li>Villain: <a href="%s">Bob</a>' % reverse("admin:admin_views_villain_change", args=(self.sv1.pk,)), '<li>Super villain: <a href="%s">Bob</a>' % reverse("admin:admin_views_supervillain_change", args=(self.sv1.pk,)), "<li>Secret hideout: floating castle", "<li>Super secret hideout: super floating castle!", ] response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.sv1.pk,)) ) for should in should_contain: self.assertContains(response, should, 1) response = self.client.get( reverse("admin:admin_views_supervillain_delete", args=(self.sv1.pk,)) ) for should in should_contain: self.assertContains(response, should, 1) def test_generic_relations(self): """ If a deleted object has GenericForeignKeys pointing to it, those objects should be listed for deletion. """ plot = self.pl3 tag = FunkyTag.objects.create(content_object=plot, name="hott") should_contain = '<li>Funky tag: <a href="%s">hott' % reverse( "admin:admin_views_funkytag_change", args=(tag.id,) ) response = self.client.get( reverse("admin:admin_views_plot_delete", args=(plot.pk,)) ) self.assertContains(response, should_contain) def test_generic_relations_with_related_query_name(self): """ If a deleted object has GenericForeignKey with GenericRelation(related_query_name='...') pointing to it, those objects should be listed for deletion. """ bookmark = Bookmark.objects.create(name="djangoproject") tag = FunkyTag.objects.create(content_object=bookmark, name="django") tag_url = reverse("admin:admin_views_funkytag_change", args=(tag.id,)) should_contain = '<li>Funky tag: <a href="%s">django' % tag_url response = self.client.get( reverse("admin:admin_views_bookmark_delete", args=(bookmark.pk,)) ) self.assertContains(response, should_contain) def test_delete_view_uses_get_deleted_objects(self): """The delete view uses ModelAdmin.get_deleted_objects().""" book = Book.objects.create(name="Test Book") response = self.client.get( reverse("admin2:admin_views_book_delete", args=(book.pk,)) ) # BookAdmin.get_deleted_objects() returns custom text. self.assertContains(response, "a deletable object") @override_settings(ROOT_URLCONF="admin_views.urls") class TestGenericRelations(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.v1 = Villain.objects.create(name="Adam") cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) def setUp(self): self.client.force_login(self.superuser) def test_generic_content_object_in_list_display(self): FunkyTag.objects.create(content_object=self.pl3, name="hott") response = self.client.get(reverse("admin:admin_views_funkytag_changelist")) self.assertContains(response, "%s</td>" % self.pl3) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewStringPrimaryKeyTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.pk = ( "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 " r"""-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" ) cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk) content_type_pk = ContentType.objects.get_for_model( ModelWithStringPrimaryKey ).pk user_pk = cls.superuser.pk LogEntry.objects.log_action( user_pk, content_type_pk, cls.pk, cls.pk, 2, change_message="Changed something", ) def setUp(self): self.client.force_login(self.superuser) def test_get_history_view(self): """ Retrieving the history for an object using urlencoded form of primary key should work. Refs #12349, #18550. """ response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_history", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) self.assertContains(response, "Changed something") def test_get_change_view(self): "Retrieving the object using urlencoded form of primary key should work" response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) def test_changelist_to_changeform_link(self): """ Link to the changeform of the object in changelist should use reverse() and be quoted. """ response = self.client.get( reverse("admin:admin_views_modelwithstringprimarykey_changelist") ) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding pk_final_url = escape(iri_to_uri(quote(self.pk))) change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", pk_final_url) should_contain = '<th class="field-__str__"><a href="%s">%s</a></th>' % ( change_url, escape(self.pk), ) self.assertContains(response, should_contain) def test_recentactions_link(self): """ The link from the recent actions list referring to the changeform of the object should be quoted. """ response = self.client.get(reverse("admin:index")) link = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(self.pk),) ) should_contain = """<a href="%s">%s</a>""" % (escape(link), escape(self.pk)) self.assertContains(response, should_contain) def test_deleteconfirmation_link(self): """ " The link from the delete confirmation page referring back to the changeform of the object should be quoted. """ url = reverse( "admin:admin_views_modelwithstringprimarykey_delete", args=(quote(self.pk),) ) response = self.client.get(url) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", escape(iri_to_uri(quote(self.pk)))) should_contain = '<a href="%s">%s</a>' % (change_url, escape(self.pk)) self.assertContains(response, should_contain) def test_url_conflicts_with_add(self): "A model with a primary key that ends with add or is `add` should be visible" add_model = ModelWithStringPrimaryKey.objects.create( pk="i have something to add" ) add_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(add_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) add_model2 = ModelWithStringPrimaryKey.objects.create(pk="add") add_url = reverse("admin:admin_views_modelwithstringprimarykey_add") change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(add_model2.pk),), ) self.assertNotEqual(add_url, change_url) def test_url_conflicts_with_delete(self): "A model with a primary key that ends with delete should be visible" delete_model = ModelWithStringPrimaryKey(pk="delete") delete_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(delete_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) def test_url_conflicts_with_history(self): "A model with a primary key that ends with history should be visible" history_model = ModelWithStringPrimaryKey(pk="history") history_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(history_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) def test_shortcut_view_with_escaping(self): "'View on site should' work properly with char fields" model = ModelWithStringPrimaryKey(pk="abc_123") model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(model.pk),), ) ) should_contain = '/%s/" class="viewsitelink">' % model.pk self.assertContains(response, should_contain) def test_change_view_history_link(self): """Object history button link should work and contain the pk value quoted.""" url = reverse( "admin:%s_modelwithstringprimarykey_change" % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),), ) response = self.client.get(url) self.assertEqual(response.status_code, 200) expected_link = reverse( "admin:%s_modelwithstringprimarykey_history" % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),), ) self.assertContains( response, '<a href="%s" class="historylink"' % escape(expected_link) ) def test_redirect_on_add_view_continue_button(self): """As soon as an object is added using "Save and continue editing" button, the user should be redirected to the object's change_view. In case primary key is a string containing some special characters like slash or underscore, these characters must be escaped (see #22266) """ response = self.client.post( reverse("admin:admin_views_modelwithstringprimarykey_add"), { "string_pk": "123/history", "_continue": "1", # Save and continue editing }, ) self.assertEqual(response.status_code, 302) # temporary redirect self.assertIn("/123_2Fhistory/", response.headers["location"]) # PK is quoted @override_settings(ROOT_URLCONF="admin_views.urls") class SecureViewTests(TestCase): """ Test behavior of a view protected by the staff_member_required decorator. """ def test_secure_view_shows_login_if_not_logged_in(self): secure_url = reverse("secure_view") response = self.client.get(secure_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), secure_url) ) response = self.client.get(secure_url, follow=True) self.assertTemplateUsed(response, "admin/login.html") self.assertEqual(response.context[REDIRECT_FIELD_NAME], secure_url) def test_staff_member_required_decorator_works_with_argument(self): """ Staff_member_required decorator works with an argument (redirect_field_name). """ secure_url = "/test_admin/admin/secure-view2/" response = self.client.get(secure_url) self.assertRedirects( response, "%s?myfield=%s" % (reverse("admin:login"), secure_url) ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewUnicodeTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.b1 = Book.objects.create(name="Lærdommer") cls.p1 = Promo.objects.create(name="<Promo for Lærdommer>", book=cls.b1) cls.chap1 = Chapter.objects.create( title="Norske bostaver æøå skaper problemer", content="<p>Svært frustrerende med UnicodeDecodeErro</p>", book=cls.b1, ) cls.chap2 = Chapter.objects.create( title="Kjærlighet", content="<p>La kjærligheten til de lidende seire.</p>", book=cls.b1, ) cls.chap3 = Chapter.objects.create( title="Kjærlighet", content="<p>Noe innhold</p>", book=cls.b1 ) cls.chap4 = ChapterXtra1.objects.create( chap=cls.chap1, xtra="<Xtra(1) Norske bostaver æøå skaper problemer>" ) cls.chap5 = ChapterXtra1.objects.create( chap=cls.chap2, xtra="<Xtra(1) Kjærlighet>" ) cls.chap6 = ChapterXtra1.objects.create( chap=cls.chap3, xtra="<Xtra(1) Kjærlighet>" ) cls.chap7 = ChapterXtra2.objects.create( chap=cls.chap1, xtra="<Xtra(2) Norske bostaver æøå skaper problemer>" ) cls.chap8 = ChapterXtra2.objects.create( chap=cls.chap2, xtra="<Xtra(2) Kjærlighet>" ) cls.chap9 = ChapterXtra2.objects.create( chap=cls.chap3, xtra="<Xtra(2) Kjærlighet>" ) def setUp(self): self.client.force_login(self.superuser) def test_unicode_edit(self): """ A test to ensure that POST on edit_view handles non-ASCII characters. """ post_data = { "name": "Test lærdommer", # inline data "chapter_set-TOTAL_FORMS": "6", "chapter_set-INITIAL_FORMS": "3", "chapter_set-MAX_NUM_FORMS": "0", "chapter_set-0-id": self.chap1.pk, "chapter_set-0-title": "Norske bostaver æøå skaper problemer", "chapter_set-0-content": ( "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;" ), "chapter_set-1-id": self.chap2.id, "chapter_set-1-title": "Kjærlighet.", "chapter_set-1-content": ( "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;" ), "chapter_set-2-id": self.chap3.id, "chapter_set-2-title": "Need a title.", "chapter_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "chapter_set-3-id": "", "chapter_set-3-title": "", "chapter_set-3-content": "", "chapter_set-4-id": "", "chapter_set-4-title": "", "chapter_set-4-content": "", "chapter_set-5-id": "", "chapter_set-5-title": "", "chapter_set-5-content": "", } response = self.client.post( reverse("admin:admin_views_book_change", args=(self.b1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_unicode_delete(self): """ The delete_view handles non-ASCII characters """ delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_book_delete", args=(self.b1.pk,)) response = self.client.get(delete_url) self.assertEqual(response.status_code, 200) response = self.client.post(delete_url, delete_dict) self.assertRedirects(response, reverse("admin:admin_views_book_changelist")) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewListEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_inheritance(self): Podcast.objects.create( name="This Week in Django", release_date=datetime.date.today() ) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertEqual(response.status_code, 200) def test_inheritance_2(self): Vodcast.objects.create(name="This Week in Django", released=True) response = self.client.get(reverse("admin:admin_views_vodcast_changelist")) self.assertEqual(response.status_code, 200) def test_custom_pk(self): Language.objects.create(iso="en", name="English", english_name="English") response = self.client.get(reverse("admin:admin_views_language_changelist")) self.assertEqual(response.status_code, 200) def test_changelist_input_html(self): response = self.client.get(reverse("admin:admin_views_person_changelist")) # 2 inputs per object(the field and the hidden id field) = 6 # 4 management hidden fields = 4 # 4 action inputs (3 regular checkboxes, 1 checkbox to select all) # main form submit button = 1 # search field and search submit button = 2 # CSRF field = 2 # field to track 'select all' across paginated views = 1 # 6 + 4 + 4 + 1 + 2 + 2 + 1 = 20 inputs self.assertContains(response, "<input", count=21) # 1 select per object = 3 selects self.assertContains(response, "<select", count=4) def test_post_messages(self): # Ticket 12707: Saving inline editable should not show admin # action warnings data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data, follow=True ) self.assertEqual(len(response.context["messages"]), 1) def test_post_submission(self): data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) # test a filtered page data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per1.pk), "form-0-gender": "1", "form-0-alive": "checked", "form-1-id": str(self.per3.pk), "form-1-gender": "1", "form-1-alive": "checked", "_save": "Save", } self.client.post( reverse("admin:admin_views_person_changelist") + "?gender__exact=1", data ) self.assertIs(Person.objects.get(name="John Mauchly").alive, True) # test a searched page data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per1.pk), "form-0-gender": "1", "_save": "Save", } self.client.post( reverse("admin:admin_views_person_changelist") + "?q=john", data ) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) def test_non_field_errors(self): """ Non-field errors are displayed for each of the forms in the changelist's formset. """ fd1 = FoodDelivery.objects.create( reference="123", driver="bill", restaurant="thai" ) fd2 = FoodDelivery.objects.create( reference="456", driver="bill", restaurant="india" ) fd3 = FoodDelivery.objects.create( reference="789", driver="bill", restaurant="pizza" ) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-id": str(fd1.id), "form-0-reference": "123", "form-0-driver": "bill", "form-0-restaurant": "thai", # Same data as above: Forbidden because of unique_together! "form-1-id": str(fd2.id), "form-1-reference": "456", "form-1-driver": "bill", "form-1-restaurant": "thai", "form-2-id": str(fd3.id), "form-2-reference": "789", "form-2-driver": "bill", "form-2-restaurant": "pizza", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_fooddelivery_changelist"), data ) self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield"><li>Food delivery ' "with this Driver and Restaurant already exists.</li></ul></td></tr>", 1, html=True, ) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-id": str(fd1.id), "form-0-reference": "123", "form-0-driver": "bill", "form-0-restaurant": "thai", # Same data as above: Forbidden because of unique_together! "form-1-id": str(fd2.id), "form-1-reference": "456", "form-1-driver": "bill", "form-1-restaurant": "thai", # Same data also. "form-2-id": str(fd3.id), "form-2-reference": "789", "form-2-driver": "bill", "form-2-restaurant": "thai", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_fooddelivery_changelist"), data ) self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield"><li>Food delivery ' "with this Driver and Restaurant already exists.</li></ul></td></tr>", 2, html=True, ) def test_non_form_errors(self): # test if non-form errors are handled; ticket #12716 data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per2.pk), "form-0-alive": "1", "form-0-gender": "2", # The form processing understands this as a list_editable "Save" # and not an action "Go". "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data ) self.assertContains(response, "Grace is not a Zombie") def test_non_form_errors_is_errorlist(self): # test if non-form errors are correctly handled; ticket #12878 data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per2.pk), "form-0-alive": "1", "form-0-gender": "2", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data ) non_form_errors = response.context["cl"].formset.non_form_errors() self.assertIsInstance(non_form_errors, ErrorList) self.assertEqual( str(non_form_errors), str(ErrorList(["Grace is not a Zombie"], error_class="nonform")), ) def test_list_editable_ordering(self): collector = Collector.objects.create(id=1, name="Frederick Clegg") Category.objects.create(id=1, order=1, collector=collector) Category.objects.create(id=2, order=2, collector=collector) Category.objects.create(id=3, order=0, collector=collector) Category.objects.create(id=4, order=0, collector=collector) # NB: The order values must be changed so that the items are reordered. data = { "form-TOTAL_FORMS": "4", "form-INITIAL_FORMS": "4", "form-MAX_NUM_FORMS": "0", "form-0-order": "14", "form-0-id": "1", "form-0-collector": "1", "form-1-order": "13", "form-1-id": "2", "form-1-collector": "1", "form-2-order": "1", "form-2-id": "3", "form-2-collector": "1", "form-3-order": "0", "form-3-id": "4", "form-3-collector": "1", # The form processing understands this as a list_editable "Save" # and not an action "Go". "_save": "Save", } response = self.client.post( reverse("admin:admin_views_category_changelist"), data ) # Successful post will redirect self.assertEqual(response.status_code, 302) # The order values have been applied to the right objects self.assertEqual(Category.objects.get(id=1).order, 14) self.assertEqual(Category.objects.get(id=2).order, 13) self.assertEqual(Category.objects.get(id=3).order, 1) self.assertEqual(Category.objects.get(id=4).order, 0) def test_list_editable_pagination(self): """ Pagination works for list_editable items. """ UnorderedObject.objects.create(id=1, name="Unordered object #1") UnorderedObject.objects.create(id=2, name="Unordered object #2") UnorderedObject.objects.create(id=3, name="Unordered object #3") response = self.client.get( reverse("admin:admin_views_unorderedobject_changelist") ) self.assertContains(response, "Unordered object #3") self.assertContains(response, "Unordered object #2") self.assertNotContains(response, "Unordered object #1") response = self.client.get( reverse("admin:admin_views_unorderedobject_changelist") + "?p=2" ) self.assertNotContains(response, "Unordered object #3") self.assertNotContains(response, "Unordered object #2") self.assertContains(response, "Unordered object #1") def test_list_editable_action_submit(self): # List editable changes should not be executed if the action "Go" button is # used to submit the form. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": "1", "form-1-gender": "2", "form-1-id": "2", "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": "3", "index": "0", "_selected_action": ["3"], "action": ["", "delete_selected"], } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, True) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 1) def test_list_editable_action_choices(self): # List editable changes should be executed if the "Save" button is # used to submit the form - any action choices should be ignored. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", "_selected_action": ["1"], "action": ["", "delete_selected"], } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) def test_list_editable_popup(self): """ Fields should not be list-editable in popups. """ response = self.client.get(reverse("admin:admin_views_person_changelist")) self.assertNotEqual(response.context["cl"].list_editable, ()) response = self.client.get( reverse("admin:admin_views_person_changelist") + "?%s" % IS_POPUP_VAR ) self.assertEqual(response.context["cl"].list_editable, ()) def test_pk_hidden_fields(self): """ hidden pk fields aren't displayed in the table body and their corresponding human-readable value is displayed instead. The hidden pk fields are displayed but separately (not in the table) and only once. """ story1 = Story.objects.create( title="The adventures of Guido", content="Once upon a time in Djangoland..." ) story2 = Story.objects.create( title="Crouching Tiger, Hidden Python", content="The Python was sneaking into...", ) response = self.client.get(reverse("admin:admin_views_story_changelist")) # Only one hidden field, in a separate place than the table. self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) self.assertContains( response, '<div class="hiddenfields">\n' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n' "</div>" % (story2.id, story1.id), html=True, ) self.assertContains(response, '<td class="field-id">%d</td>' % story1.id, 1) self.assertContains(response, '<td class="field-id">%d</td>' % story2.id, 1) def test_pk_hidden_fields_with_list_display_links(self): """Similarly as test_pk_hidden_fields, but when the hidden pk fields are referenced in list_display_links. Refs #12475. """ story1 = OtherStory.objects.create( title="The adventures of Guido", content="Once upon a time in Djangoland...", ) story2 = OtherStory.objects.create( title="Crouching Tiger, Hidden Python", content="The Python was sneaking into...", ) link1 = reverse("admin:admin_views_otherstory_change", args=(story1.pk,)) link2 = reverse("admin:admin_views_otherstory_change", args=(story2.pk,)) response = self.client.get(reverse("admin:admin_views_otherstory_changelist")) # Only one hidden field, in a separate place than the table. self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) self.assertContains( response, '<div class="hiddenfields">\n' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n' "</div>" % (story2.id, story1.id), html=True, ) self.assertContains( response, '<th class="field-id"><a href="%s">%d</a></th>' % (link1, story1.id), 1, ) self.assertContains( response, '<th class="field-id"><a href="%s">%d</a></th>' % (link2, story2.id), 1, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminSearchTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="John Doe", gender=1) Person.objects.create(name='John O"Hara', gender=1) Person.objects.create(name="John O'Hara", gender=1) cls.t1 = Recommender.objects.create() cls.t2 = Recommendation.objects.create(the_recommender=cls.t1) cls.t3 = Recommender.objects.create() cls.t4 = Recommendation.objects.create(the_recommender=cls.t3) cls.tt1 = TitleTranslation.objects.create(title=cls.t1, text="Bar") cls.tt2 = TitleTranslation.objects.create(title=cls.t2, text="Foo") cls.tt3 = TitleTranslation.objects.create(title=cls.t3, text="Few") cls.tt4 = TitleTranslation.objects.create(title=cls.t4, text="Bas") def setUp(self): self.client.force_login(self.superuser) def test_search_on_sibling_models(self): "A search that mentions sibling models" response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned 1 object self.assertContains(response, "\n1 recommendation\n") def test_with_fk_to_field(self): """ The to_field GET parameter is preserved when a search is performed. Refs #10918. """ response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_VAR ) self.assertContains(response, "\n1 user\n") self.assertContains( response, '<input type="hidden" name="%s" value="id">' % TO_FIELD_VAR, html=True, ) def test_exact_matches(self): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned one object self.assertContains(response, "\n1 recommendation\n") response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=ba" ) # confirm the search returned zero objects self.assertContains(response, "\n0 recommendations\n") def test_beginning_matches(self): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) # confirm the search returned one object self.assertContains(response, "\n1 person\n") self.assertContains(response, "Guido") response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=uido" ) # confirm the search returned zero objects self.assertContains(response, "\n0 persons\n") self.assertNotContains(response, "Guido") def test_pluggable_search(self): PluggableSearchPerson.objects.create(name="Bob", age=10) PluggableSearchPerson.objects.create(name="Amy", age=20) response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=Bob" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Bob") response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=20" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Amy") def test_reset_link(self): """ Test presence of reset link in search bar ("1 result (_x total_)"). """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count # + 1 for total count with self.assertNumQueries(5): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) self.assertContains( response, """<span class="small quiet">1 result (<a href="?">6 total</a>)</span>""", html=True, ) def test_no_total_count(self): """ #8408 -- "Show all" should be displayed instead of the total count if ModelAdmin.show_full_result_count is False. """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count with self.assertNumQueries(4): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) self.assertContains( response, """<span class="small quiet">1 result (<a href="?">Show all</a>)</span>""", html=True, ) self.assertTrue(response.context["cl"].show_admin_actions) def test_search_with_spaces(self): url = reverse("admin:admin_views_person_changelist") + "?q=%s" tests = [ ('"John Doe"', 1), ("'John Doe'", 1), ("John Doe", 0), ('"John Doe" John', 1), ("'John Doe' John", 1), ("John Doe John", 0), ('"John Do"', 1), ("'John Do'", 1), ("'John O'Hara'", 0), ("'John O\\'Hara'", 1), ('"John O"Hara"', 0), ('"John O\\"Hara"', 1), ] for search, hits in tests: with self.subTest(search=search): response = self.client.get(url % search) self.assertContains(response, "\n%s person" % hits) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInheritedInlinesTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_inline(self): """ Inline models which inherit from a common parent are correctly handled. """ foo_user = "foo username" bar_user = "bar username" name_re = re.compile(b'name="(.*?)"') # test the add case response = self.client.get(reverse("admin:admin_views_persona_add")) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) # test the add case post_data = { "name": "Test Name", # inline data "accounts-TOTAL_FORMS": "1", "accounts-INITIAL_FORMS": "0", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": foo_user, "accounts-2-TOTAL_FORMS": "1", "accounts-2-INITIAL_FORMS": "0", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": bar_user, } response = self.client.post(reverse("admin:admin_views_persona_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, foo_user) self.assertEqual(BarAccount.objects.all()[0].username, bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) persona_id = Persona.objects.all()[0].id foo_id = FooAccount.objects.all()[0].id bar_id = BarAccount.objects.all()[0].id # test the edit case response = self.client.get( reverse("admin:admin_views_persona_change", args=(persona_id,)) ) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) post_data = { "name": "Test Name", "accounts-TOTAL_FORMS": "2", "accounts-INITIAL_FORMS": "1", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": "%s-1" % foo_user, "accounts-0-account_ptr": str(foo_id), "accounts-0-persona": str(persona_id), "accounts-2-TOTAL_FORMS": "2", "accounts-2-INITIAL_FORMS": "1", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": "%s-1" % bar_user, "accounts-2-0-account_ptr": str(bar_id), "accounts-2-0-persona": str(persona_id), } response = self.client.post( reverse("admin:admin_views_persona_change", args=(persona_id,)), post_data ) self.assertEqual(response.status_code, 302) self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, "%s-1" % foo_user) self.assertEqual(BarAccount.objects.all()[0].username, "%s-1" % bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) @override_settings(ROOT_URLCONF="admin_views.urls") class TestCustomChangeList(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_custom_changelist(self): """ Validate that a custom ChangeList class can be used (#9749) """ # Insert some data post_data = {"name": "First Gadget"} response = self.client.post(reverse("admin:admin_views_gadget_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere # Hit the page once to get messages out of the queue message list response = self.client.get(reverse("admin:admin_views_gadget_changelist")) # Data is still not visible on the page response = self.client.get(reverse("admin:admin_views_gadget_changelist")) self.assertNotContains(response, "First Gadget") @override_settings(ROOT_URLCONF="admin_views.urls") class TestInlineNotEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_GET_parent_add(self): """ InlineModelAdmin broken? """ response = self.client.get(reverse("admin:admin_views_parent_add")) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomQuerysetTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.pks = [EmptyModel.objects.create().id for i in range(3)] def setUp(self): self.client.force_login(self.superuser) self.super_login = { REDIRECT_FIELD_NAME: reverse("admin:index"), "username": "super", "password": "secret", } def test_changelist_view(self): response = self.client.get(reverse("admin:admin_views_emptymodel_changelist")) for i in self.pks: if i > 1: self.assertContains(response, "Primary key = %s" % i) else: self.assertNotContains(response, "Primary key = %s" % i) def test_changelist_view_count_queries(self): # create 2 Person objects Person.objects.create(name="person1", gender=1) Person.objects.create(name="person2", gender=2) changelist_url = reverse("admin:admin_views_person_changelist") # 5 queries are expected: 1 for the session, 1 for the user, # 2 for the counts and 1 for the objects on the page with self.assertNumQueries(5): resp = self.client.get(changelist_url) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"q": "not_in_name"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 0 selected") self.assertEqual(resp.context["selection_note_all"], "All 0 selected") with self.assertNumQueries(5): extra = {"q": "person"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"gender__exact": "1"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 1 selected") self.assertEqual(resp.context["selection_note_all"], "1 selected") def test_change_view(self): for i in self.pks: url = reverse("admin:admin_views_emptymodel_change", args=(i,)) response = self.client.get(url, follow=True) if i > 1: self.assertEqual(response.status_code, 200) else: self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["empty model with ID “1” doesn’t exist. Perhaps it was deleted?"], ) def test_add_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(CoverLetter.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "author": "Candidate, Best", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_coverletter_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name pk = CoverLetter.objects.all()[0].pk self.assertContains( response, '<li class="success">The cover letter “<a href="%s">' "Candidate, Best</a>” was added successfully.</li>" % reverse("admin:admin_views_coverletter_change", args=(pk,)), html=True, ) # model has no __str__ method self.assertEqual(ShortMessage.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "content": "What's this SMS thing?", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_shortmessage_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(ShortMessage.objects.count(), 1) # Message should contain non-ugly model verbose name sm = ShortMessage.objects.all()[0] self.assertContains( response, '<li class="success">The short message “<a href="%s">' "%s</a>” was added successfully.</li>" % (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm), html=True, ) def test_add_model_modeladmin_only_qs(self): # Test for #14529. only() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(Telegram.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "title": "Urgent telegram", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_telegram_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(Telegram.objects.count(), 1) # Message should contain non-ugly model verbose name pk = Telegram.objects.all()[0].pk self.assertContains( response, '<li class="success">The telegram “<a href="%s">' "Urgent telegram</a>” was added successfully.</li>" % reverse("admin:admin_views_telegram_change", args=(pk,)), html=True, ) # model has no __str__ method self.assertEqual(Paper.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_paper_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(Paper.objects.count(), 1) # Message should contain non-ugly model verbose name p = Paper.objects.all()[0] self.assertContains( response, '<li class="success">The paper “<a href="%s">' "%s</a>” was added successfully.</li>" % (reverse("admin:admin_views_paper_change", args=(p.pk,)), p), html=True, ) def test_edit_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method cl = CoverLetter.objects.create(author="John Doe") self.assertEqual(CoverLetter.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_coverletter_change", args=(cl.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "author": "John Doe II", "_save": "Save", } url = reverse("admin:admin_views_coverletter_change", args=(cl.pk,)) response = self.client.post(url, post_data, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name. Instance # representation is set by model's __str__() self.assertContains( response, '<li class="success">The cover letter “<a href="%s">' "John Doe II</a>” was changed successfully.</li>" % reverse("admin:admin_views_coverletter_change", args=(cl.pk,)), html=True, ) # model has no __str__ method sm = ShortMessage.objects.create(content="This is expensive") self.assertEqual(ShortMessage.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "content": "Too expensive", "_save": "Save", } url = reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)) response = self.client.post(url, post_data, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(ShortMessage.objects.count(), 1) # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by __str__(). self.assertContains( response, '<li class="success">The short message “<a href="%s">' "%s</a>” was changed successfully.</li>" % (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm), html=True, ) def test_edit_model_modeladmin_only_qs(self): # Test for #14529. only() is used in ModelAdmin.get_queryset() # model has __str__ method t = Telegram.objects.create(title="First Telegram") self.assertEqual(Telegram.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_telegram_change", args=(t.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "title": "Telegram without typo", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_telegram_change", args=(t.pk,)), post_data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(Telegram.objects.count(), 1) # Message should contain non-ugly model verbose name. The instance # representation is set by model's __str__() self.assertContains( response, '<li class="success">The telegram “<a href="%s">' "Telegram without typo</a>” was changed successfully.</li>" % reverse("admin:admin_views_telegram_change", args=(t.pk,)), html=True, ) # model has no __str__ method p = Paper.objects.create(title="My Paper Title") self.assertEqual(Paper.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_paper_change", args=(p.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_paper_change", args=(p.pk,)), post_data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(Paper.objects.count(), 1) # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by __str__(). self.assertContains( response, '<li class="success">The paper “<a href="%s">' "%s</a>” was changed successfully.</li>" % (reverse("admin:admin_views_paper_change", args=(p.pk,)), p), html=True, ) def test_history_view_custom_qs(self): """ Custom querysets are considered for the admin history view. """ self.client.post(reverse("admin:login"), self.super_login) FilteredManager.objects.create(pk=1) FilteredManager.objects.create(pk=2) response = self.client.get( reverse("admin:admin_views_filteredmanager_changelist") ) self.assertContains(response, "PK=1") self.assertContains(response, "PK=2") self.assertEqual( self.client.get( reverse("admin:admin_views_filteredmanager_history", args=(1,)) ).status_code, 200, ) self.assertEqual( self.client.get( reverse("admin:admin_views_filteredmanager_history", args=(2,)) ).status_code, 200, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInlineFileUploadTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) file1 = tempfile.NamedTemporaryFile(suffix=".file1") file1.write(b"a" * (2**21)) filename = file1.name file1.close() cls.gallery = Gallery.objects.create(name="Test Gallery") cls.picture = Picture.objects.create( name="Test Picture", image=filename, gallery=cls.gallery, ) def setUp(self): self.client.force_login(self.superuser) def test_form_has_multipart_enctype(self): response = self.client.get( reverse("admin:admin_views_gallery_change", args=(self.gallery.id,)) ) self.assertIs(response.context["has_file_field"], True) self.assertContains(response, MULTIPART_ENCTYPE) def test_inline_file_upload_edit_validation_error_post(self): """ Inline file uploads correctly display prior data (#10002). """ post_data = { "name": "Test Gallery", "pictures-TOTAL_FORMS": "2", "pictures-INITIAL_FORMS": "1", "pictures-MAX_NUM_FORMS": "0", "pictures-0-id": str(self.picture.id), "pictures-0-gallery": str(self.gallery.id), "pictures-0-name": "Test Picture", "pictures-0-image": "", "pictures-1-id": "", "pictures-1-gallery": str(self.gallery.id), "pictures-1-name": "Test Picture 2", "pictures-1-image": "", } response = self.client.post( reverse("admin:admin_views_gallery_change", args=(self.gallery.id,)), post_data, ) self.assertContains(response, b"Currently") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInlineTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.collector = Collector.objects.create(pk=1, name="John Fowles") def setUp(self): self.post_data = { "name": "Test Name", "widget_set-TOTAL_FORMS": "3", "widget_set-INITIAL_FORMS": "0", "widget_set-MAX_NUM_FORMS": "0", "widget_set-0-id": "", "widget_set-0-owner": "1", "widget_set-0-name": "", "widget_set-1-id": "", "widget_set-1-owner": "1", "widget_set-1-name": "", "widget_set-2-id": "", "widget_set-2-owner": "1", "widget_set-2-name": "", "doohickey_set-TOTAL_FORMS": "3", "doohickey_set-INITIAL_FORMS": "0", "doohickey_set-MAX_NUM_FORMS": "0", "doohickey_set-0-owner": "1", "doohickey_set-0-code": "", "doohickey_set-0-name": "", "doohickey_set-1-owner": "1", "doohickey_set-1-code": "", "doohickey_set-1-name": "", "doohickey_set-2-owner": "1", "doohickey_set-2-code": "", "doohickey_set-2-name": "", "grommet_set-TOTAL_FORMS": "3", "grommet_set-INITIAL_FORMS": "0", "grommet_set-MAX_NUM_FORMS": "0", "grommet_set-0-code": "", "grommet_set-0-owner": "1", "grommet_set-0-name": "", "grommet_set-1-code": "", "grommet_set-1-owner": "1", "grommet_set-1-name": "", "grommet_set-2-code": "", "grommet_set-2-owner": "1", "grommet_set-2-name": "", "whatsit_set-TOTAL_FORMS": "3", "whatsit_set-INITIAL_FORMS": "0", "whatsit_set-MAX_NUM_FORMS": "0", "whatsit_set-0-owner": "1", "whatsit_set-0-index": "", "whatsit_set-0-name": "", "whatsit_set-1-owner": "1", "whatsit_set-1-index": "", "whatsit_set-1-name": "", "whatsit_set-2-owner": "1", "whatsit_set-2-index": "", "whatsit_set-2-name": "", "fancydoodad_set-TOTAL_FORMS": "3", "fancydoodad_set-INITIAL_FORMS": "0", "fancydoodad_set-MAX_NUM_FORMS": "0", "fancydoodad_set-0-doodad_ptr": "", "fancydoodad_set-0-owner": "1", "fancydoodad_set-0-name": "", "fancydoodad_set-0-expensive": "on", "fancydoodad_set-1-doodad_ptr": "", "fancydoodad_set-1-owner": "1", "fancydoodad_set-1-name": "", "fancydoodad_set-1-expensive": "on", "fancydoodad_set-2-doodad_ptr": "", "fancydoodad_set-2-owner": "1", "fancydoodad_set-2-name": "", "fancydoodad_set-2-expensive": "on", "category_set-TOTAL_FORMS": "3", "category_set-INITIAL_FORMS": "0", "category_set-MAX_NUM_FORMS": "0", "category_set-0-order": "", "category_set-0-id": "", "category_set-0-collector": "1", "category_set-1-order": "", "category_set-1-id": "", "category_set-1-collector": "1", "category_set-2-order": "", "category_set-2-id": "", "category_set-2-collector": "1", } self.client.force_login(self.superuser) def test_simple_inline(self): "A simple model can be saved as inlines" # First add a new inline self.post_data["widget_set-0-name"] = "Widget 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1") widget_id = Widget.objects.all()[0].id # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="widget_set-0-id"') # No file or image fields, no enctype on the forms self.assertIs(response.context["has_file_field"], False) self.assertNotContains(response, MULTIPART_ENCTYPE) # Now resave that inline self.post_data["widget_set-INITIAL_FORMS"] = "1" self.post_data["widget_set-0-id"] = str(widget_id) self.post_data["widget_set-0-name"] = "Widget 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1") # Now modify that inline self.post_data["widget_set-INITIAL_FORMS"] = "1" self.post_data["widget_set-0-id"] = str(widget_id) self.post_data["widget_set-0-name"] = "Widget 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_explicit_autofield_inline(self): """ A model with an explicit autofield primary key can be saved as inlines. """ # First add a new inline self.post_data["grommet_set-0-name"] = "Grommet 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="grommet_set-0-code"') # Now resave that inline self.post_data["grommet_set-INITIAL_FORMS"] = "1" self.post_data["grommet_set-0-code"] = str(Grommet.objects.all()[0].code) self.post_data["grommet_set-0-name"] = "Grommet 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1") # Now modify that inline self.post_data["grommet_set-INITIAL_FORMS"] = "1" self.post_data["grommet_set-0-code"] = str(Grommet.objects.all()[0].code) self.post_data["grommet_set-0-name"] = "Grommet 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1 Updated") def test_char_pk_inline(self): "A model with a character PK can be saved as inlines. Regression for #10992" # First add a new inline self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="doohickey_set-0-code"') # Now resave that inline self.post_data["doohickey_set-INITIAL_FORMS"] = "1" self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1") # Now modify that inline self.post_data["doohickey_set-INITIAL_FORMS"] = "1" self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1 Updated") def test_integer_pk_inline(self): "A model with an integer PK can be saved as inlines. Regression for #10992" # First add a new inline self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="whatsit_set-0-index"') # Now resave that inline self.post_data["whatsit_set-INITIAL_FORMS"] = "1" self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1") # Now modify that inline self.post_data["whatsit_set-INITIAL_FORMS"] = "1" self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1 Updated") def test_inherited_inline(self): "An inherited model can be saved as inlines. Regression for #11042" # First add a new inline self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1") doodad_pk = FancyDoodad.objects.all()[0].pk # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="fancydoodad_set-0-doodad_ptr"') # Now resave that inline self.post_data["fancydoodad_set-INITIAL_FORMS"] = "1" self.post_data["fancydoodad_set-0-doodad_ptr"] = str(doodad_pk) self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1") # Now modify that inline self.post_data["fancydoodad_set-INITIAL_FORMS"] = "1" self.post_data["fancydoodad_set-0-doodad_ptr"] = str(doodad_pk) self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1 Updated") def test_ordered_inline(self): """ An inline with an editable ordering fields is updated correctly. """ # Create some objects with an initial ordering Category.objects.create(id=1, order=1, collector=self.collector) Category.objects.create(id=2, order=2, collector=self.collector) Category.objects.create(id=3, order=0, collector=self.collector) Category.objects.create(id=4, order=0, collector=self.collector) # NB: The order values must be changed so that the items are reordered. self.post_data.update( { "name": "Frederick Clegg", "category_set-TOTAL_FORMS": "7", "category_set-INITIAL_FORMS": "4", "category_set-MAX_NUM_FORMS": "0", "category_set-0-order": "14", "category_set-0-id": "1", "category_set-0-collector": "1", "category_set-1-order": "13", "category_set-1-id": "2", "category_set-1-collector": "1", "category_set-2-order": "1", "category_set-2-id": "3", "category_set-2-collector": "1", "category_set-3-order": "0", "category_set-3-id": "4", "category_set-3-collector": "1", "category_set-4-order": "", "category_set-4-id": "", "category_set-4-collector": "1", "category_set-5-order": "", "category_set-5-id": "", "category_set-5-collector": "1", "category_set-6-order": "", "category_set-6-id": "", "category_set-6-collector": "1", } ) collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) # Successful post will redirect self.assertEqual(response.status_code, 302) # The order values have been applied to the right objects self.assertEqual(self.collector.category_set.count(), 4) self.assertEqual(Category.objects.get(id=1).order, 14) self.assertEqual(Category.objects.get(id=2).order, 13) self.assertEqual(Category.objects.get(id=3).order, 1) self.assertEqual(Category.objects.get(id=4).order, 0) @override_settings(ROOT_URLCONF="admin_views.urls") class NeverCacheTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") def setUp(self): self.client.force_login(self.superuser) def test_admin_index(self): "Check the never-cache status of the main index" response = self.client.get(reverse("admin:index")) self.assertEqual(get_max_age(response), 0) def test_app_index(self): "Check the never-cache status of an application index" response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(get_max_age(response), 0) def test_model_index(self): "Check the never-cache status of a model index" response = self.client.get(reverse("admin:admin_views_fabric_changelist")) self.assertEqual(get_max_age(response), 0) def test_model_add(self): "Check the never-cache status of a model add page" response = self.client.get(reverse("admin:admin_views_fabric_add")) self.assertEqual(get_max_age(response), 0) def test_model_view(self): "Check the never-cache status of a model edit page" response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_model_history(self): "Check the never-cache status of a model history page" response = self.client.get( reverse("admin:admin_views_section_history", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_model_delete(self): "Check the never-cache status of a model delete page" response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_login(self): "Check the never-cache status of login views" self.client.logout() response = self.client.get(reverse("admin:index")) self.assertEqual(get_max_age(response), 0) def test_logout(self): "Check the never-cache status of logout view" response = self.client.post(reverse("admin:logout")) self.assertEqual(get_max_age(response), 0) def test_password_change(self): "Check the never-cache status of the password change view" self.client.logout() response = self.client.get(reverse("admin:password_change")) self.assertIsNone(get_max_age(response)) def test_password_change_done(self): "Check the never-cache status of the password change done view" response = self.client.get(reverse("admin:password_change_done")) self.assertIsNone(get_max_age(response)) def test_JS_i18n(self): "Check the never-cache status of the JavaScript i18n view" response = self.client.get(reverse("admin:jsi18n")) self.assertIsNone(get_max_age(response)) @override_settings(ROOT_URLCONF="admin_views.urls") class PrePopulatedTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_prepopulated_on(self): response = self.client.get(reverse("admin:admin_views_prepopulatedpost_add")) self.assertContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") self.assertContains( response, "&quot;dependency_ids&quot;: [&quot;#id_title&quot;]" ) self.assertContains( response, "&quot;id&quot;: &quot;#id_prepopulatedsubpost_set-0-subslug&quot;", ) def test_prepopulated_off(self): response = self.client.get( reverse("admin:admin_views_prepopulatedpost_change", args=(self.p1.pk,)) ) self.assertContains(response, "A Long Title") self.assertNotContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") self.assertNotContains( response, "&quot;dependency_ids&quot;: [&quot;#id_title&quot;]" ) self.assertNotContains( response, "&quot;id&quot;: &quot;#id_prepopulatedsubpost_set-0-subslug&quot;", ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_prepopulated_maxlength_localized(self): """ Regression test for #15938: if USE_THOUSAND_SEPARATOR is set, make sure that maxLength (in the JavaScript) is rendered without separators. """ response = self.client.get( reverse("admin:admin_views_prepopulatedpostlargeslug_add") ) self.assertContains(response, "&quot;maxLength&quot;: 1000") # instead of 1,000 def test_view_only_add_form(self): """ PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug' which is present in the add view, even if the ModelAdmin.has_change_permission() returns False. """ response = self.client.get(reverse("admin7:admin_views_prepopulatedpost_add")) self.assertContains(response, "data-prepopulated-fields=") self.assertContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") def test_view_only_change_form(self): """ PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug'. That doesn't break a view-only change view. """ response = self.client.get( reverse("admin7:admin_views_prepopulatedpost_change", args=(self.p1.pk,)) ) self.assertContains(response, 'data-prepopulated-fields="[]"') self.assertContains(response, '<div class="readonly">%s</div>' % self.p1.slug) @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) self.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def test_login_button_centered(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) button = self.selenium.find_element(By.CSS_SELECTOR, ".submit-row input") offset_left = button.get_property("offsetLeft") offset_right = button.get_property("offsetParent").get_property( "offsetWidth" ) - (offset_left + button.get_property("offsetWidth")) # Use assertAlmostEqual to avoid pixel rounding errors. self.assertAlmostEqual(offset_left, offset_right, delta=3) def test_prepopulated_fields(self): """ The JavaScript-automated prepopulated fields work with the main form and with stacked and tabular inlines. Refs #13068, #9264, #9983, #9784. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_mainprepopulated_add") ) self.wait_for(".select2") # Main form ---------------------------------------------------------- self.selenium.find_element(By.ID, "id_pubdate").send_keys("2012-02-18") self.select_option("#id_status", "option two") self.selenium.find_element(By.ID, "id_name").send_keys( " the mAin nÀMë and it's awεšomeıııİ" ) slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") slug3 = self.selenium.find_element(By.ID, "id_slug3").get_attribute("value") self.assertEqual(slug1, "the-main-name-and-its-awesomeiiii-2012-02-18") self.assertEqual(slug2, "option-two-the-main-name-and-its-awesomeiiii") self.assertEqual( slug3, "the-main-n\xe0m\xeb-and-its-aw\u03b5\u0161ome\u0131\u0131\u0131i" ) # Stacked inlines with fieldsets ------------------------------------- # Initial inline self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-pubdate" ).send_keys("2011-12-17") self.select_option("#id_relatedprepopulated_set-0-status", "option one") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-name" ).send_keys(" here is a sŤāÇkeð inline ! ") slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-slug2" ).get_attribute("value") self.assertEqual(slug1, "here-is-a-stacked-inline-2011-12-17") self.assertEqual(slug2, "option-one-here-is-a-stacked-inline") initial_select2_inputs = self.selenium.find_elements( By.CLASS_NAME, "select2-selection" ) # Inline formsets have empty/invisible forms. # Only the 4 visible select2 inputs are initialized. num_initial_select2_inputs = len(initial_select2_inputs) self.assertEqual(num_initial_select2_inputs, 4) # Add an inline self.selenium.find_elements(By.LINK_TEXT, "Add another Related prepopulated")[ 0 ].click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 2, ) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-pubdate" ).send_keys("1999-01-25") self.select_option("#id_relatedprepopulated_set-1-status", "option two") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-name" ).send_keys( " now you haVe anöther sŤāÇkeð inline with a very ... " "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog " "text... " ) slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-slug2" ).get_attribute("value") # 50 characters maximum for slug1 field self.assertEqual(slug1, "now-you-have-another-stacked-inline-with-a-very-lo") # 60 characters maximum for slug2 field self.assertEqual( slug2, "option-two-now-you-have-another-stacked-inline-with-a-very-l" ) # Tabular inlines ---------------------------------------------------- # Initial inline element = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-status" ) self.selenium.execute_script("window.scrollTo(0, %s);" % element.location["y"]) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-pubdate" ).send_keys("1234-12-07") self.select_option("#id_relatedprepopulated_set-2-0-status", "option two") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-name" ).send_keys("And now, with a tÃbűlaŘ inline !!!") slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-slug2" ).get_attribute("value") self.assertEqual(slug1, "and-now-with-a-tabular-inline-1234-12-07") self.assertEqual(slug2, "option-two-and-now-with-a-tabular-inline") # Add an inline # Button may be outside the browser frame. element = self.selenium.find_elements( By.LINK_TEXT, "Add another Related prepopulated" )[1] self.selenium.execute_script("window.scrollTo(0, %s);" % element.location["y"]) element.click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 4, ) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-pubdate" ).send_keys("1981-08-22") self.select_option("#id_relatedprepopulated_set-2-1-status", "option one") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-name" ).send_keys(r'tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters') slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-slug2" ).get_attribute("value") self.assertEqual(slug1, "tabular-inline-with-ignored-characters-1981-08-22") self.assertEqual(slug2, "option-one-tabular-inline-with-ignored-characters") # Add an inline without an initial inline. # The button is outside of the browser frame. self.selenium.execute_script("window.scrollTo(0, document.body.scrollHeight);") self.selenium.find_elements(By.LINK_TEXT, "Add another Related prepopulated")[ 2 ].click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 6, ) # Stacked Inlines without fieldsets ---------------------------------- # Initial inline. row_id = "id_relatedprepopulated_set-4-0-" self.selenium.find_element(By.ID, f"{row_id}pubdate").send_keys("2011-12-12") self.select_option(f"#{row_id}status", "option one") self.selenium.find_element(By.ID, f"{row_id}name").send_keys( " sŤāÇkeð inline ! " ) slug1 = self.selenium.find_element(By.ID, f"{row_id}slug1").get_attribute( "value" ) slug2 = self.selenium.find_element(By.ID, f"{row_id}slug2").get_attribute( "value" ) self.assertEqual(slug1, "stacked-inline-2011-12-12") self.assertEqual(slug2, "option-one") # Add inline. self.selenium.find_elements( By.LINK_TEXT, "Add another Related prepopulated", )[3].click() row_id = "id_relatedprepopulated_set-4-1-" self.selenium.find_element(By.ID, f"{row_id}pubdate").send_keys("1999-01-20") self.select_option(f"#{row_id}status", "option two") self.selenium.find_element(By.ID, f"{row_id}name").send_keys( " now you haVe anöther sŤāÇkeð inline with a very loooong " ) slug1 = self.selenium.find_element(By.ID, f"{row_id}slug1").get_attribute( "value" ) slug2 = self.selenium.find_element(By.ID, f"{row_id}slug2").get_attribute( "value" ) self.assertEqual(slug1, "now-you-have-another-stacked-inline-with-a-very-lo") self.assertEqual(slug2, "option-two") # Save and check that everything is properly stored in the database with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.assertEqual(MainPrepopulated.objects.count(), 1) MainPrepopulated.objects.get( name=" the mAin nÀMë and it's awεšomeıııİ", pubdate="2012-02-18", status="option two", slug1="the-main-name-and-its-awesomeiiii-2012-02-18", slug2="option-two-the-main-name-and-its-awesomeiiii", slug3="the-main-nàmë-and-its-awεšomeıııi", ) self.assertEqual(RelatedPrepopulated.objects.count(), 6) RelatedPrepopulated.objects.get( name=" here is a sŤāÇkeð inline ! ", pubdate="2011-12-17", status="option one", slug1="here-is-a-stacked-inline-2011-12-17", slug2="option-one-here-is-a-stacked-inline", ) RelatedPrepopulated.objects.get( # 75 characters in name field name=( " now you haVe anöther sŤāÇkeð inline with a very ... " "loooooooooooooooooo" ), pubdate="1999-01-25", status="option two", slug1="now-you-have-another-stacked-inline-with-a-very-lo", slug2="option-two-now-you-have-another-stacked-inline-with-a-very-l", ) RelatedPrepopulated.objects.get( name="And now, with a tÃbűlaŘ inline !!!", pubdate="1234-12-07", status="option two", slug1="and-now-with-a-tabular-inline-1234-12-07", slug2="option-two-and-now-with-a-tabular-inline", ) RelatedPrepopulated.objects.get( name=r'tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters', pubdate="1981-08-22", status="option one", slug1="tabular-inline-with-ignored-characters-1981-08-22", slug2="option-one-tabular-inline-with-ignored-characters", ) def test_populate_existing_object(self): """ The prepopulation works for existing objects too, as long as the original field is empty (#19082). """ from selenium.webdriver.common.by import By # Slugs are empty to start with. item = MainPrepopulated.objects.create( name=" this is the mAin nÀMë", pubdate="2012-02-18", status="option two", slug1="", slug2="", ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) object_url = self.live_server_url + reverse( "admin:admin_views_mainprepopulated_change", args=(item.id,) ) self.selenium.get(object_url) self.selenium.find_element(By.ID, "id_name").send_keys(" the best") # The slugs got prepopulated since they were originally empty slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") self.assertEqual(slug1, "this-is-the-main-name-the-best-2012-02-18") self.assertEqual(slug2, "option-two-this-is-the-main-name-the-best") # Save the object with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.get(object_url) self.selenium.find_element(By.ID, "id_name").send_keys(" hello") # The slugs got prepopulated didn't change since they were originally not empty slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") self.assertEqual(slug1, "this-is-the-main-name-the-best-2012-02-18") self.assertEqual(slug2, "option-two-this-is-the-main-name-the-best") def test_collapsible_fieldset(self): """ The 'collapse' class in fieldsets definition allows to show/hide the appropriate field section. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_add") ) self.assertFalse(self.selenium.find_element(By.ID, "id_title").is_displayed()) self.selenium.find_elements(By.LINK_TEXT, "Show")[0].click() self.assertTrue(self.selenium.find_element(By.ID, "id_title").is_displayed()) self.assertEqual( self.selenium.find_element(By.ID, "fieldsetcollapser0").text, "Hide" ) def test_selectbox_height_collapsible_fieldset(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin7:index"), ) url = self.live_server_url + reverse("admin7:admin_views_pizza_add") self.selenium.get(url) self.selenium.find_elements(By.LINK_TEXT, "Show")[0].click() from_filter_box = self.selenium.find_element(By.ID, "id_toppings_filter") from_box = self.selenium.find_element(By.ID, "id_toppings_from") to_filter_box = self.selenium.find_element(By.ID, "id_toppings_filter_selected") to_box = self.selenium.find_element(By.ID, "id_toppings_to") self.assertEqual( ( to_filter_box.get_property("offsetHeight") + to_box.get_property("offsetHeight") ), ( from_filter_box.get_property("offsetHeight") + from_box.get_property("offsetHeight") ), ) def test_selectbox_height_not_collapsible_fieldset(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin7:index"), ) url = self.live_server_url + reverse("admin7:admin_views_question_add") self.selenium.get(url) from_filter_box = self.selenium.find_element( By.ID, "id_related_questions_filter" ) from_box = self.selenium.find_element(By.ID, "id_related_questions_from") to_filter_box = self.selenium.find_element( By.ID, "id_related_questions_filter_selected" ) to_box = self.selenium.find_element(By.ID, "id_related_questions_to") self.assertEqual( ( to_filter_box.get_property("offsetHeight") + to_box.get_property("offsetHeight") ), ( from_filter_box.get_property("offsetHeight") + from_box.get_property("offsetHeight") ), ) def test_first_field_focus(self): """JavaScript-assisted auto-focus on first usable form field.""" from selenium.webdriver.common.by import By # First form field has a single widget self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) with self.wait_page_loaded(): self.selenium.get( self.live_server_url + reverse("admin:admin_views_picture_add") ) self.assertEqual( self.selenium.switch_to.active_element, self.selenium.find_element(By.ID, "id_name"), ) # First form field has a MultiWidget with self.wait_page_loaded(): self.selenium.get( self.live_server_url + reverse("admin:admin_views_reservation_add") ) self.assertEqual( self.selenium.switch_to.active_element, self.selenium.find_element(By.ID, "id_start_date_0"), ) def test_cancel_delete_confirmation(self): "Cancelling the deletion of an object takes the user back one page." from selenium.webdriver.common.by import By pizza = Pizza.objects.create(name="Double Cheese") url = reverse("admin:admin_views_pizza_change", args=(pizza.id,)) full_url = self.live_server_url + url self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get(full_url) self.selenium.find_element(By.CLASS_NAME, "deletelink").click() # Click 'cancel' on the delete page. self.selenium.find_element(By.CLASS_NAME, "cancel-link").click() # Wait until we're back on the change page. self.wait_for_text("#content h1", "Change pizza") self.assertEqual(self.selenium.current_url, full_url) self.assertEqual(Pizza.objects.count(), 1) def test_cancel_delete_related_confirmation(self): """ Cancelling the deletion of an object with relations takes the user back one page. """ from selenium.webdriver.common.by import By pizza = Pizza.objects.create(name="Double Cheese") topping1 = Topping.objects.create(name="Cheddar") topping2 = Topping.objects.create(name="Mozzarella") pizza.toppings.add(topping1, topping2) url = reverse("admin:admin_views_pizza_change", args=(pizza.id,)) full_url = self.live_server_url + url self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get(full_url) self.selenium.find_element(By.CLASS_NAME, "deletelink").click() # Click 'cancel' on the delete page. self.selenium.find_element(By.CLASS_NAME, "cancel-link").click() # Wait until we're back on the change page. self.wait_for_text("#content h1", "Change pizza") self.assertEqual(self.selenium.current_url, full_url) self.assertEqual(Pizza.objects.count(), 1) self.assertEqual(Topping.objects.count(), 2) def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select s1 = Section.objects.create(name="Test section") Article.objects.create( title="foo", content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=s1, ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_changelist") ) # Change popup self.selenium.find_element(By.ID, "change_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Change section") name_input = self.selenium.find_element(By.ID, "id_name") name_input.clear() name_input.send_keys("<i>edited section</i>") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Hide sidebar. toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "<i>edited section</i>") # Rendered select2 input. select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\n<i>edited section</i>") # Add popup self.selenium.find_element(By.ID, "add_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Add section") self.selenium.find_element(By.ID, "id_name").send_keys("new section") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "new section") select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\nnew section") def test_inline_uuid_pk_edit_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "change_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(select.first_selected_option.text, str(parent.id)) self.assertEqual( select.first_selected_option.get_attribute("value"), str(parent.id) ) def test_inline_uuid_pk_add_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_relatedwithuuidpkmodel_add") ) self.selenium.find_element(By.ID, "add_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) uuid_id = str(ParentWithUUIDPK.objects.first().id) self.assertEqual(select.first_selected_option.text, uuid_id) self.assertEqual(select.first_selected_option.get_attribute("value"), uuid_id) def test_inline_uuid_pk_delete_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Yes, I’m sure"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(ParentWithUUIDPK.objects.count(), 0) self.assertEqual(select.first_selected_option.text, "---------") self.assertEqual(select.first_selected_option.get_attribute("value"), "") def test_inline_with_popup_cancel_delete(self): """Clicking ""No, take me back" on a delete popup closes the window.""" from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//a[text()="No, take me back"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertEqual(len(self.selenium.window_handles), 1) def test_list_editable_raw_id_fields(self): from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") parent2 = ParentWithUUIDPK.objects.create(title="test2") RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_changelist", current_app=site2.name, ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "lookup_id_form-0-parent").click() self.wait_for_and_switch_to_popup() # Select "parent2" in the popup. self.selenium.find_element(By.LINK_TEXT, str(parent2.pk)).click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # The newly selected pk should appear in the raw id input. value = self.selenium.find_element(By.ID, "id_form-0-parent").get_attribute( "value" ) self.assertEqual(value, str(parent2.pk)) def test_input_element_font(self): """ Browsers' default stylesheets override the font of inputs. The admin adds additional CSS to handle this. """ from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) element = self.selenium.find_element(By.ID, "id_username") # Some browsers quotes the fonts, some don't. fonts = [ font.strip().strip('"') for font in element.value_of_css_property("font-family").split(",") ] self.assertEqual( fonts, [ "-apple-system", "BlinkMacSystemFont", "Segoe UI", "system-ui", "Roboto", "Helvetica Neue", "Arial", "sans-serif", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", ], ) def test_search_input_filtered_page(self): from selenium.webdriver.common.by import By Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="Grace Hopper", gender=1, alive=False) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) person_url = reverse("admin:admin_views_person_changelist") + "?q=Gui" self.selenium.get(self.live_server_url + person_url) self.assertGreater( self.selenium.find_element(By.ID, "searchbar").rect["width"], 50, ) def test_related_popup_index(self): """ Create a chain of 'self' related objects via popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) base_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() popup_window_test = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) popup_window_test2 = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.selenium.find_element(By.ID, "id_title").send_keys("test3") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test2) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test3").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test2").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(base_window) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) def test_related_popup_incorrect_close(self): """ Cleanup child popups when closing a parent popup. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() test_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) test2_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.assertEqual(len(self.selenium.window_handles), 4) self.selenium.switch_to.window(test2_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 2, 1) self.assertEqual(len(self.selenium.window_handles), 2) # Close final popup to clean up test. self.selenium.switch_to.window(test_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 1, 1) self.selenium.switch_to.window(self.selenium.window_handles[-1]) def test_hidden_fields_small_window(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) self.selenium.get(self.live_server_url + reverse("admin:admin_views_story_add")) field_title = self.selenium.find_element(By.CLASS_NAME, "field-title") current_size = self.selenium.get_window_size() try: self.selenium.set_window_size(1024, 768) self.assertIs(field_title.is_displayed(), False) self.selenium.set_window_size(767, 575) self.assertIs(field_title.is_displayed(), False) finally: self.selenium.set_window_size(current_size["width"], current_size["height"]) def test_updating_related_objects_updates_fk_selects_except_autocompletes(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select born_country_select_id = "id_born_country" living_country_select_id = "id_living_country" living_country_select2_textbox_id = "select2-id_living_country-container" favorite_country_to_vacation_select_id = "id_favorite_country_to_vacation" continent_select_id = "id_continent" def _get_HTML_inside_element_by_id(id_): return self.selenium.find_element(By.ID, id_).get_attribute("innerHTML") def _get_text_inside_element_by_selector(selector): return self.selenium.find_element(By.CSS_SELECTOR, selector).get_attribute( "innerText" ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_traveler_add") self.selenium.get(self.live_server_url + add_url) # Add new Country from the born_country select. self.selenium.find_element(By.ID, f"add_{born_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Argentina") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("South America") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> """, ) # Argentina isn't added to the living_country select nor selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id}"), "" ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "", ) # Argentina won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Add new Country from the living_country select. self.selenium.find_element(By.ID, f"add_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Spain") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Europe") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> <option value="2">Spain</option> """, ) # Spain is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Spain", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Spain", ) # Spain won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Edit second Country created from living_country select. favorite_select = Select( self.selenium.find_element(By.ID, living_country_select_id) ) favorite_select.select_by_visible_text("Spain") self.selenium.find_element(By.ID, f"change_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.clear() favorite_name_input.send_keys("Italy") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> <option value="2">Italy</option> """, ) # Italy is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Italy", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Italy", ) # favorite_country_to_vacation field has no options. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Add a new Asian country. self.selenium.find_element( By.ID, f"add_{favorite_country_to_vacation_select_id}" ).click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.send_keys("Qatar") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Asia") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Submit the new Traveler. self.selenium.find_element(By.CSS_SELECTOR, '[name="_save"]').click() traveler = Traveler.objects.get() self.assertEqual(traveler.born_country.name, "Argentina") self.assertEqual(traveler.living_country.name, "Italy") self.assertEqual(traveler.favorite_country_to_vacation.name, "Qatar") def test_redirect_on_add_view_add_another_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 2") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 2) def test_redirect_on_add_view_continue_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and continue editing"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input_value = name_input.get_attribute("value") self.assertEqual(name_input_value, "Test section 1") @override_settings(ROOT_URLCONF="admin_views.urls") class ReadonlyTest(AdminFieldExtractionMixin, TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_readonly_get(self): response = self.client.get(reverse("admin:admin_views_post_add")) self.assertNotContains(response, 'name="posted"') # 3 fields + 2 submit buttons + 5 inline management form fields, + 2 # hidden fields for inlines + 1 field for the inline + 2 empty form # + 1 logout form. self.assertContains(response, "<input", count=17) self.assertContains(response, formats.localize(datetime.date.today())) self.assertContains(response, "<label>Awesomeness level:</label>") self.assertContains(response, "Very awesome.") self.assertContains(response, "Unknown coolness.") self.assertContains(response, "foo") # Multiline text in a readonly field gets <br> tags self.assertContains(response, "Multiline<br>test<br>string") self.assertContains( response, '<div class="readonly">Multiline<br>html<br>content</div>', html=True, ) self.assertContains(response, "InlineMultiline<br>test<br>string") self.assertContains( response, formats.localize(datetime.date.today() - datetime.timedelta(days=7)), ) self.assertContains(response, '<div class="form-row field-coolness">') self.assertContains(response, '<div class="form-row field-awesomeness_level">') self.assertContains(response, '<div class="form-row field-posted">') self.assertContains(response, '<div class="form-row field-value">') self.assertContains(response, '<div class="form-row">') self.assertContains(response, '<div class="help"', 3) self.assertContains( response, '<div class="help" id="id_title_helptext">Some help text for the title ' "(with Unicode ŠĐĆŽćžšđ)</div>", html=True, ) self.assertContains( response, '<div class="help" id="id_content_helptext">Some help text for the content ' "(with Unicode ŠĐĆŽćžšđ)</div>", html=True, ) self.assertContains( response, '<div class="help">Some help text for the date (with Unicode ŠĐĆŽćžšđ)' "</div>", html=True, ) p = Post.objects.create( title="I worked on readonly_fields", content="Its good stuff" ) response = self.client.get( reverse("admin:admin_views_post_change", args=(p.pk,)) ) self.assertContains(response, "%d amount of cool" % p.pk) def test_readonly_text_field(self): p = Post.objects.create( title="Readonly test", content="test", readonly_content="test\r\n\r\ntest\r\n\r\ntest\r\n\r\ntest", ) Link.objects.create( url="http://www.djangoproject.com", post=p, readonly_link_content="test\r\nlink", ) response = self.client.get( reverse("admin:admin_views_post_change", args=(p.pk,)) ) # Checking readonly field. self.assertContains(response, "test<br><br>test<br><br>test<br><br>test") # Checking readonly field in inline. self.assertContains(response, "test<br>link") def test_readonly_post(self): data = { "title": "Django Got Readonly Fields", "content": "This is an incredible development.", "link_set-TOTAL_FORMS": "1", "link_set-INITIAL_FORMS": "0", "link_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_post_add"), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) p = Post.objects.get() self.assertEqual(p.posted, datetime.date.today()) data["posted"] = "10-8-1990" # some date that's not today response = self.client.post(reverse("admin:admin_views_post_add"), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) p = Post.objects.order_by("-id")[0] self.assertEqual(p.posted, datetime.date.today()) def test_readonly_manytomany(self): "Regression test for #13004" response = self.client.get(reverse("admin:admin_views_pizza_add")) self.assertEqual(response.status_code, 200) def test_user_password_change_limited_queryset(self): su = User.objects.filter(is_superuser=True)[0] response = self.client.get( reverse("admin2:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 404) def test_change_form_renders_correct_null_choice_value(self): """ Regression test for #17911. """ choice = Choice.objects.create(choice=None) response = self.client.get( reverse("admin:admin_views_choice_change", args=(choice.pk,)) ) self.assertContains( response, '<div class="readonly">No opinion</div>', html=True ) def _test_readonly_foreignkey_links(self, admin_site): """ ForeignKey readonly fields render as links if the target model is registered in admin. """ chapter = Chapter.objects.create( title="Chapter 1", content="content", book=Book.objects.create(name="Book 1"), ) language = Language.objects.create(iso="_40", name="Test") obj = ReadOnlyRelatedField.objects.create( chapter=chapter, language=language, user=self.superuser, ) response = self.client.get( reverse( f"{admin_site}:admin_views_readonlyrelatedfield_change", args=(obj.pk,) ), ) # Related ForeignKey object registered in admin. user_url = reverse(f"{admin_site}:auth_user_change", args=(self.superuser.pk,)) self.assertContains( response, '<div class="readonly"><a href="%s">super</a></div>' % user_url, html=True, ) # Related ForeignKey with the string primary key registered in admin. language_url = reverse( f"{admin_site}:admin_views_language_change", args=(quote(language.pk),), ) self.assertContains( response, '<div class="readonly"><a href="%s">_40</a></div>' % language_url, html=True, ) # Related ForeignKey object not registered in admin. self.assertContains( response, '<div class="readonly">Chapter 1</div>', html=True ) def test_readonly_foreignkey_links_default_admin_site(self): self._test_readonly_foreignkey_links("admin") def test_readonly_foreignkey_links_custom_admin_site(self): self._test_readonly_foreignkey_links("namespaced_admin") def test_readonly_manytomany_backwards_ref(self): """ Regression test for #16433 - backwards references for related objects broke if the related field is read-only due to the help_text attribute """ topping = Topping.objects.create(name="Salami") pizza = Pizza.objects.create(name="Americano") pizza.toppings.add(topping) response = self.client.get(reverse("admin:admin_views_topping_add")) self.assertEqual(response.status_code, 200) def test_readonly_manytomany_forwards_ref(self): topping = Topping.objects.create(name="Salami") pizza = Pizza.objects.create(name="Americano") pizza.toppings.add(topping) response = self.client.get( reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) ) self.assertContains(response, "<label>Toppings:</label>", html=True) self.assertContains(response, '<div class="readonly">Salami</div>', html=True) def test_readonly_onetoone_backwards_ref(self): """ Can reference a reverse OneToOneField in ModelAdmin.readonly_fields. """ v1 = Villain.objects.create(name="Adam") pl = Plot.objects.create(name="Test Plot", team_leader=v1, contact=v1) pd = PlotDetails.objects.create(details="Brand New Plot", plot=pl) response = self.client.get( reverse("admin:admin_views_plotproxy_change", args=(pl.pk,)) ) field = self.get_admin_readonly_field(response, "plotdetails") pd_url = reverse("admin:admin_views_plotdetails_change", args=(pd.pk,)) self.assertEqual(field.contents(), '<a href="%s">Brand New Plot</a>' % pd_url) # The reverse relation also works if the OneToOneField is null. pd.plot = None pd.save() response = self.client.get( reverse("admin:admin_views_plotproxy_change", args=(pl.pk,)) ) field = self.get_admin_readonly_field(response, "plotdetails") self.assertEqual(field.contents(), "-") # default empty value def test_readonly_field_overrides(self): """ Regression test for #22087 - ModelForm Meta overrides are ignored by AdminReadonlyField """ p = FieldOverridePost.objects.create(title="Test Post", content="Test Content") response = self.client.get( reverse("admin:admin_views_fieldoverridepost_change", args=(p.pk,)) ) self.assertContains( response, '<div class="help">Overridden help text for the date</div>', html=True, ) self.assertContains( response, '<label for="id_public">Overridden public label:</label>', html=True, ) self.assertNotContains( response, "Some help text for the date (with Unicode ŠĐĆŽćžšđ)" ) def test_correct_autoescaping(self): """ Make sure that non-field readonly elements are properly autoescaped (#24461) """ section = Section.objects.create(name="<a>evil</a>") response = self.client.get( reverse("admin:admin_views_section_change", args=(section.pk,)) ) self.assertNotContains(response, "<a>evil</a>", status_code=200) self.assertContains(response, "&lt;a&gt;evil&lt;/a&gt;", status_code=200) def test_label_suffix_translated(self): pizza = Pizza.objects.create(name="Americano") url = reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) with self.settings(LANGUAGE_CODE="fr"): response = self.client.get(url) self.assertContains(response, "<label>Toppings\u00A0:</label>", html=True) @override_settings(ROOT_URLCONF="admin_views.urls") class LimitChoicesToInAdminTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to_as_callable(self): """Test for ticket 2445 changes to admin.""" threepwood = Character.objects.create( username="threepwood", last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) marley = Character.objects.create( username="marley", last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) response = self.client.get(reverse("admin:admin_views_stumpjoke_add")) # The allowed option should appear twice; the limited option should not appear. self.assertContains(response, threepwood.username, count=2) self.assertNotContains(response, marley.username) @override_settings(ROOT_URLCONF="admin_views.urls") class RawIdFieldsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to(self): """Regression test for 14880""" actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") Inquisition.objects.create(expected=False, leader=actor, country="Spain") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_inquisition"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step also tests integers, strings and booleans in the # lookup query string; in model we define inquisition field to have a # limit_choices_to option that includes a filter on a string field # (inquisition__actor__name), a filter on an integer field # (inquisition__actor__age), and a filter on a boolean field # (inquisition__expected). response2 = self.client.get(popup_url) self.assertContains(response2, "Spain") self.assertNotContains(response2, "England") def test_limit_choices_to_isnull_false(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_defendant0"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=0 gets parsed correctly from the # lookup query string; in model we define defendant0 field to have a # limit_choices_to option that includes "actor__title__isnull=False". response2 = self.client.get(popup_url) self.assertContains(response2, "Kilbraken") self.assertNotContains(response2, "Palin") def test_limit_choices_to_isnull_true(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_defendant1"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=1 gets parsed correctly from the # lookup query string; in model we define defendant1 field to have a # limit_choices_to option that includes "actor__title__isnull=True". response2 = self.client.get(popup_url) self.assertNotContains(response2, "Kilbraken") self.assertContains(response2, "Palin") def test_list_display_method_same_name_as_reverse_accessor(self): """ Should be able to use a ModelAdmin method in list_display that has the same name as a reverse model field ("sketch" in this case). """ actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") response = self.client.get(reverse("admin:admin_views_inquisition_changelist")) self.assertContains(response, "list-display-sketch") @override_settings(ROOT_URLCONF="admin_views.urls") class UserAdminTest(TestCase): """ Tests user CRUD functionality. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", }, ) new_user = User.objects.get(username="newuser") self.assertRedirects( response, reverse("admin:auth_user_change", args=(new_user.pk,)) ) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_save_continue_editing_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_continue": "1", }, ) new_user = User.objects.get(username="newuser") new_user_url = reverse("admin:auth_user_change", args=(new_user.pk,)) self.assertRedirects(response, new_user_url, fetch_redirect_response=False) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) response = self.client.get(new_user_url) self.assertContains( response, '<li class="success">The user “<a href="%s">' "%s</a>” was added successfully. You may edit it again below.</li>" % (new_user_url, new_user), html=True, ) def test_password_mismatch(self): response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "mismatch", }, ) self.assertEqual(response.status_code, 200) self.assertFormError(response.context["adminform"], "password1", []) self.assertFormError( response.context["adminform"], "password2", ["The two password fields didn’t match."], ) def test_user_fk_add_popup(self): """ User addition through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains(response, reverse("admin:auth_user_add")) self.assertContains( response, 'class="related-widget-wrapper-link add-related" id="add_id_owner"', ) response = self.client.get( reverse("admin:auth_user_add") + "?%s=1" % IS_POPUP_VAR ) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { "username": "newuser", "password1": "newpassword", "password2": "newpassword", IS_POPUP_VAR: "1", "_save": "1", } response = self.client.post( reverse("admin:auth_user_add") + "?%s=1" % IS_POPUP_VAR, data, follow=True ) self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;") def test_user_fk_change_popup(self): """ User change through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains( response, reverse("admin:auth_user_change", args=("__fk__",)) ) self.assertContains( response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"', ) user = User.objects.get(username="changeuser") url = ( reverse("admin:auth_user_change", args=(user.pk,)) + "?%s=1" % IS_POPUP_VAR ) response = self.client.get(url) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "last_login_0": "2007-05-30", "last_login_1": "13:20:10", "date_joined_0": "2007-05-30", "date_joined_1": "13:20:10", IS_POPUP_VAR: "1", "_save": "1", } response = self.client.post(url, data, follow=True) self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;") self.assertContains(response, "&quot;action&quot;: &quot;change&quot;") def test_user_fk_delete_popup(self): """ User deletion through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains( response, reverse("admin:auth_user_delete", args=("__fk__",)) ) self.assertContains( response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"', ) user = User.objects.get(username="changeuser") url = ( reverse("admin:auth_user_delete", args=(user.pk,)) + "?%s=1" % IS_POPUP_VAR ) response = self.client.get(url) self.assertEqual(response.status_code, 200) data = { "post": "yes", IS_POPUP_VAR: "1", } response = self.client.post(url, data, follow=True) self.assertContains(response, "&quot;action&quot;: &quot;delete&quot;") def test_save_add_another_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_addanother": "1", }, ) new_user = User.objects.order_by("-id")[0] self.assertRedirects(response, reverse("admin:auth_user_add")) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_user_permission_performance(self): u = User.objects.all()[0] # Don't depend on a warm cache, see #17377. ContentType.objects.clear_cache() expected_num_queries = 10 if connection.features.uses_savepoints else 8 with self.assertNumQueries(expected_num_queries): response = self.client.get(reverse("admin:auth_user_change", args=(u.pk,))) self.assertEqual(response.status_code, 200) def test_form_url_present_in_context(self): u = User.objects.all()[0] response = self.client.get( reverse("admin3:auth_user_password_change", args=(u.pk,)) ) self.assertEqual(response.status_code, 200) self.assertEqual(response.context["form_url"], "pony") @override_settings(ROOT_URLCONF="admin_views.urls") class GroupAdminTest(TestCase): """ Tests group CRUD functionality. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): group_count = Group.objects.count() response = self.client.post( reverse("admin:auth_group_add"), { "name": "newgroup", }, ) Group.objects.order_by("-id")[0] self.assertRedirects(response, reverse("admin:auth_group_changelist")) self.assertEqual(Group.objects.count(), group_count + 1) def test_group_permission_performance(self): g = Group.objects.create(name="test_group") # Ensure no queries are skipped due to cached content type for Group. ContentType.objects.clear_cache() expected_num_queries = 8 if connection.features.uses_savepoints else 6 with self.assertNumQueries(expected_num_queries): response = self.client.get(reverse("admin:auth_group_change", args=(g.pk,))) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class CSSTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_field_prefix_css_classes(self): """ Fields have a CSS class name with a 'field-' prefix. """ response = self.client.get(reverse("admin:admin_views_post_add")) # The main form self.assertContains(response, 'class="form-row field-title"') self.assertContains(response, 'class="form-row field-content"') self.assertContains(response, 'class="form-row field-public"') self.assertContains(response, 'class="form-row field-awesomeness_level"') self.assertContains(response, 'class="form-row field-coolness"') self.assertContains(response, 'class="form-row field-value"') self.assertContains(response, 'class="form-row"') # The lambda function # The tabular inline self.assertContains(response, '<td class="field-url">') self.assertContains(response, '<td class="field-posted">') def test_index_css_classes(self): """ CSS class names are used for each app and model on the admin index pages (#17050). """ # General index page response = self.client.get(reverse("admin:index")) self.assertContains(response, '<div class="app-admin_views module') self.assertContains(response, '<tr class="model-actor">') self.assertContains(response, '<tr class="model-album">') # App index page response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains(response, '<div class="app-admin_views module') self.assertContains(response, '<tr class="model-actor">') self.assertContains(response, '<tr class="model-album">') def test_app_model_in_form_body_class(self): """ Ensure app and model tag are correctly read by change_form template """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_list_body_class(self): """ Ensure app and model tag are correctly read by change_list template """ response = self.client.get(reverse("admin:admin_views_section_changelist")) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_delete_confirmation_body_class(self): """ Ensure app and model tag are correctly read by delete_confirmation template """ response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_app_index_body_class(self): """ Ensure app and model tag are correctly read by app_index template """ response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains(response, '<body class=" dashboard app-admin_views') def test_app_model_in_delete_selected_confirmation_body_class(self): """ Ensure app and model tag are correctly read by delete_selected_confirmation template """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "delete_selected", "index": 0, } response = self.client.post( reverse("admin:admin_views_section_changelist"), action_data ) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_changelist_field_classes(self): """ Cells of the change list table should contain the field name in their class attribute. """ Podcast.objects.create(name="Django Dose", release_date=datetime.date.today()) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertContains(response, '<th class="field-name">') self.assertContains(response, '<td class="field-release_date nowrap">') self.assertContains(response, '<td class="action-checkbox">') try: import docutils except ImportError: docutils = None @unittest.skipUnless(docutils, "no docutils installed.") @override_settings(ROOT_URLCONF="admin_views.urls") @modify_settings( INSTALLED_APPS={"append": ["django.contrib.admindocs", "django.contrib.flatpages"]} ) class AdminDocsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_tags(self): response = self.client.get(reverse("django-admindocs-tags")) # The builtin tag group exists self.assertContains(response, "<h2>Built-in tags</h2>", count=2, html=True) # A builtin tag exists in both the index and detail self.assertContains( response, '<h3 id="built_in-autoescape">autoescape</h3>', html=True ) self.assertContains( response, '<li><a href="#built_in-autoescape">autoescape</a></li>', html=True, ) # An app tag exists in both the index and detail self.assertContains( response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>', html=True ) self.assertContains( response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>', html=True, ) # The admin list tag group exists self.assertContains(response, "<h2>admin_list</h2>", count=2, html=True) # An admin list tag exists in both the index and detail self.assertContains( response, '<h3 id="admin_list-admin_actions">admin_actions</h3>', html=True ) self.assertContains( response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>', html=True, ) def test_filters(self): response = self.client.get(reverse("django-admindocs-filters")) # The builtin filter group exists self.assertContains(response, "<h2>Built-in filters</h2>", count=2, html=True) # A builtin filter exists in both the index and detail self.assertContains(response, '<h3 id="built_in-add">add</h3>', html=True) self.assertContains( response, '<li><a href="#built_in-add">add</a></li>', html=True ) @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class ValidXHTMLTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_lang_name_present(self): with translation.override(None): response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertNotContains(response, ' lang=""') self.assertNotContains(response, ' xml:lang=""') @override_settings(ROOT_URLCONF="admin_views.urls", USE_THOUSAND_SEPARATOR=True) class DateHierarchyTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def assert_non_localized_year(self, response, year): """ The year is not localized with USE_THOUSAND_SEPARATOR (#15234). """ self.assertNotContains(response, formats.number_format(year)) def assert_contains_year_link(self, response, date): self.assertContains(response, '?release_date__year=%d"' % date.year) def assert_contains_month_link(self, response, date): self.assertContains( response, '?release_date__month=%d&amp;release_date__year=%d"' % (date.month, date.year), ) def assert_contains_day_link(self, response, date): self.assertContains( response, "?release_date__day=%d&amp;" 'release_date__month=%d&amp;release_date__year=%d"' % (date.day, date.month, date.year), ) def test_empty(self): """ No date hierarchy links display with empty changelist. """ response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertNotContains(response, "release_date__year=") self.assertNotContains(response, "release_date__month=") self.assertNotContains(response, "release_date__day=") def test_single(self): """ Single day-level date hierarchy appears for single object. """ DATE = datetime.date(2000, 6, 30) Podcast.objects.create(release_date=DATE) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) self.assert_contains_day_link(response, DATE) self.assert_non_localized_year(response, 2000) def test_within_month(self): """ day-level links appear for changelist within single month. """ DATES = ( datetime.date(2000, 6, 30), datetime.date(2000, 6, 15), datetime.date(2000, 6, 3), ) for date in DATES: Podcast.objects.create(release_date=date) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) for date in DATES: self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) def test_within_year(self): """ month-level links appear for changelist within single year. """ DATES = ( datetime.date(2000, 1, 30), datetime.date(2000, 3, 15), datetime.date(2000, 5, 3), ) for date in DATES: Podcast.objects.create(release_date=date) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) # no day-level links self.assertNotContains(response, "release_date__day=") for date in DATES: self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) def test_multiple_years(self): """ year-level links appear for year-spanning changelist. """ DATES = ( datetime.date(2001, 1, 30), datetime.date(2003, 3, 15), datetime.date(2005, 5, 3), ) for date in DATES: Podcast.objects.create(release_date=date) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) # no day/month-level links self.assertNotContains(response, "release_date__day=") self.assertNotContains(response, "release_date__month=") for date in DATES: self.assert_contains_year_link(response, date) # and make sure GET parameters still behave correctly for date in DATES: url = "%s?release_date__year=%d" % ( reverse("admin:admin_views_podcast_changelist"), date.year, ) response = self.client.get(url) self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) url = "%s?release_date__year=%d&release_date__month=%d" % ( reverse("admin:admin_views_podcast_changelist"), date.year, date.month, ) response = self.client.get(url) self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) def test_related_field(self): questions_data = ( # (posted data, number of answers), (datetime.date(2001, 1, 30), 0), (datetime.date(2003, 3, 15), 1), (datetime.date(2005, 5, 3), 2), ) for date, answer_count in questions_data: question = Question.objects.create(posted=date) for i in range(answer_count): question.answer_set.create() response = self.client.get(reverse("admin:admin_views_answer_changelist")) for date, answer_count in questions_data: link = '?question__posted__year=%d"' % date.year if answer_count > 0: self.assertContains(response, link) else: self.assertNotContains(response, link) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomSaveRelatedTests(TestCase): """ One can easily customize the way related objects are saved. Refs #16115. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_should_be_able_to_edit_related_objects_on_add_view(self): post = { "child_set-TOTAL_FORMS": "3", "child_set-INITIAL_FORMS": "0", "name": "Josh Stone", "child_set-0-name": "Paul", "child_set-1-name": "Catherine", } self.client.post(reverse("admin:admin_views_parent_add"), post) self.assertEqual(1, Parent.objects.count()) self.assertEqual(2, Child.objects.count()) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) def test_should_be_able_to_edit_related_objects_on_change_view(self): parent = Parent.objects.create(name="Josh Stone") paul = Child.objects.create(parent=parent, name="Paul") catherine = Child.objects.create(parent=parent, name="Catherine") post = { "child_set-TOTAL_FORMS": "5", "child_set-INITIAL_FORMS": "2", "name": "Josh Stone", "child_set-0-name": "Paul", "child_set-0-id": paul.id, "child_set-1-name": "Catherine", "child_set-1-id": catherine.id, } self.client.post( reverse("admin:admin_views_parent_change", args=(parent.id,)), post ) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) def test_should_be_able_to_edit_related_objects_on_changelist_view(self): parent = Parent.objects.create(name="Josh Rock") Child.objects.create(parent=parent, name="Paul") Child.objects.create(parent=parent, name="Catherine") post = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": parent.id, "form-0-name": "Josh Stone", "_save": "Save", } self.client.post(reverse("admin:admin_views_parent_changelist"), post) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewLogoutTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def test_logout(self): self.client.force_login(self.superuser) response = self.client.post(reverse("admin:logout")) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "registration/logged_out.html") self.assertEqual(response.request["PATH_INFO"], reverse("admin:logout")) self.assertFalse(response.context["has_permission"]) self.assertNotContains( response, "user-tools" ) # user-tools div shouldn't visible. def test_client_logout_url_can_be_used_to_login(self): response = self.client.post(reverse("admin:logout")) self.assertEqual( response.status_code, 302 ) # we should be redirected to the login page. # follow the redirect and test results. response = self.client.post(reverse("admin:logout"), follow=True) self.assertContains( response, '<input type="hidden" name="next" value="%s">' % reverse("admin:index"), ) self.assertTemplateUsed(response, "admin/login.html") self.assertEqual(response.request["PATH_INFO"], reverse("admin:login")) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminUserMessageTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def send_message(self, level): """ Helper that sends a post to the dummy test methods and asserts that a message with the level has appeared in the response. """ action_data = { ACTION_CHECKBOX_NAME: [1], "action": "message_%s" % level, "index": 0, } response = self.client.post( reverse("admin:admin_views_usermessenger_changelist"), action_data, follow=True, ) self.assertContains( response, '<li class="%s">Test %s</li>' % (level, level), html=True ) @override_settings(MESSAGE_LEVEL=10) # Set to DEBUG for this request def test_message_debug(self): self.send_message("debug") def test_message_info(self): self.send_message("info") def test_message_success(self): self.send_message("success") def test_message_warning(self): self.send_message("warning") def test_message_error(self): self.send_message("error") def test_message_extra_tags(self): action_data = { ACTION_CHECKBOX_NAME: [1], "action": "message_extra_tags", "index": 0, } response = self.client.post( reverse("admin:admin_views_usermessenger_changelist"), action_data, follow=True, ) self.assertContains( response, '<li class="extra_tag info">Test tags</li>', html=True ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminKeepChangeListFiltersTests(TestCase): admin_site = site @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) def setUp(self): self.client.force_login(self.superuser) def assertURLEqual(self, url1, url2, msg_prefix=""): """ Assert that two URLs are equal despite the ordering of their querystring. Refs #22360. """ parsed_url1 = urlparse(url1) path1 = parsed_url1.path parsed_qs1 = dict(parse_qsl(parsed_url1.query)) parsed_url2 = urlparse(url2) path2 = parsed_url2.path parsed_qs2 = dict(parse_qsl(parsed_url2.query)) for parsed_qs in [parsed_qs1, parsed_qs2]: if "_changelist_filters" in parsed_qs: changelist_filters = parsed_qs["_changelist_filters"] parsed_filters = dict(parse_qsl(changelist_filters)) parsed_qs["_changelist_filters"] = parsed_filters self.assertEqual(path1, path2) self.assertEqual(parsed_qs1, parsed_qs2) def test_assert_url_equal(self): # Test equality. change_user_url = reverse( "admin:auth_user_change", args=(self.joepublicuser.pk,) ) self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), ) # Test inequality. with self.assertRaises(AssertionError): self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "http://testserver{}?_changelist_filters=" "is_staff__exact%3D1%26is_superuser__exact%3D1".format(change_user_url), ) # Ignore scheme and host. self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), ) # Ignore ordering of querystring. self.assertURLEqual( "{}?is_staff__exact=0&is_superuser__exact=0".format( reverse("admin:auth_user_changelist") ), "{}?is_superuser__exact=0&is_staff__exact=0".format( reverse("admin:auth_user_changelist") ), ) # Ignore ordering of _changelist_filters. self.assertURLEqual( "{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "{}?_changelist_filters=" "is_superuser__exact%3D0%26is_staff__exact%3D0".format(change_user_url), ) def get_changelist_filters(self): return { "is_superuser__exact": 0, "is_staff__exact": 0, } def get_changelist_filters_querystring(self): return urlencode(self.get_changelist_filters()) def get_preserved_filters_querystring(self): return urlencode( {"_changelist_filters": self.get_changelist_filters_querystring()} ) def get_sample_user_id(self): return self.joepublicuser.pk def get_changelist_url(self): return "%s?%s" % ( reverse("admin:auth_user_changelist", current_app=self.admin_site.name), self.get_changelist_filters_querystring(), ) def get_add_url(self, add_preserved_filters=True): url = reverse("admin:auth_user_add", current_app=self.admin_site.name) if add_preserved_filters: url = "%s?%s" % (url, self.get_preserved_filters_querystring()) return url def get_change_url(self, user_id=None, add_preserved_filters=True): if user_id is None: user_id = self.get_sample_user_id() url = reverse( "admin:auth_user_change", args=(user_id,), current_app=self.admin_site.name ) if add_preserved_filters: url = "%s?%s" % (url, self.get_preserved_filters_querystring()) return url def get_history_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse( "admin:auth_user_history", args=(user_id,), current_app=self.admin_site.name, ), self.get_preserved_filters_querystring(), ) def get_delete_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse( "admin:auth_user_delete", args=(user_id,), current_app=self.admin_site.name, ), self.get_preserved_filters_querystring(), ) def test_changelist_view(self): response = self.client.get(self.get_changelist_url()) self.assertEqual(response.status_code, 200) # Check the `change_view` link has the correct querystring. detail_link = re.search( '<a href="(.*?)">{}</a>'.format(self.joepublicuser.username), response.content.decode(), ) self.assertURLEqual(detail_link[1], self.get_change_url()) def test_change_view(self): # Get the `change_view`. response = self.client.get(self.get_change_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '<form action="(.*?)" method="post" id="user_form" novalidate>', response.content.decode(), ) self.assertURLEqual( form_action[1], "?%s" % self.get_preserved_filters_querystring() ) # Check the history link. history_link = re.search( '<a href="(.*?)" class="historylink">History</a>', response.content.decode() ) self.assertURLEqual(history_link[1], self.get_history_url()) # Check the delete link. delete_link = re.search( '<a href="(.*?)" class="deletelink">Delete</a>', response.content.decode() ) self.assertURLEqual(delete_link[1], self.get_delete_url()) # Test redirect on "Save". post_data = { "username": "joepublic", "last_login_0": "2007-05-30", "last_login_1": "13:20:10", "date_joined_0": "2007-05-30", "date_joined_1": "13:20:10", } post_data["_save"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_changelist_url()) post_data.pop("_save") # Test redirect on "Save and continue". post_data["_continue"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_change_url()) post_data.pop("_continue") # Test redirect on "Save and add new". post_data["_addanother"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_add_url()) post_data.pop("_addanother") def test_change_view_without_preserved_filters(self): response = self.client.get(self.get_change_url(add_preserved_filters=False)) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="user_form" novalidate>') def test_add_view(self): # Get the `add_view`. response = self.client.get(self.get_add_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '<form action="(.*?)" method="post" id="user_form" novalidate>', response.content.decode(), ) self.assertURLEqual( form_action[1], "?%s" % self.get_preserved_filters_querystring() ) post_data = { "username": "dummy", "password1": "test", "password2": "test", } # Test redirect on "Save". post_data["_save"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects( response, self.get_change_url(User.objects.get(username="dummy").pk) ) post_data.pop("_save") # Test redirect on "Save and continue". post_data["username"] = "dummy2" post_data["_continue"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects( response, self.get_change_url(User.objects.get(username="dummy2").pk) ) post_data.pop("_continue") # Test redirect on "Save and add new". post_data["username"] = "dummy3" post_data["_addanother"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects(response, self.get_add_url()) post_data.pop("_addanother") def test_add_view_without_preserved_filters(self): response = self.client.get(self.get_add_url(add_preserved_filters=False)) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="user_form" novalidate>') def test_delete_view(self): # Test redirect on "Delete". response = self.client.post(self.get_delete_url(), {"post": "yes"}) self.assertRedirects(response, self.get_changelist_url()) def test_url_prefix(self): context = { "preserved_filters": self.get_preserved_filters_querystring(), "opts": User._meta, } prefixes = ("", "/prefix/", "/後台/") for prefix in prefixes: with self.subTest(prefix=prefix), override_script_prefix(prefix): url = reverse( "admin:auth_user_changelist", current_app=self.admin_site.name ) self.assertURLEqual( self.get_changelist_url(), add_preserved_filters(context, url), ) class NamespacedAdminKeepChangeListFiltersTests(AdminKeepChangeListFiltersTests): admin_site = site2 @override_settings(ROOT_URLCONF="admin_views.urls") class TestLabelVisibility(TestCase): """#11277 -Labels of hidden fields in admin were not hidden.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_all_fields_visible(self): response = self.client.get(reverse("admin:admin_views_emptymodelvisible_add")) self.assert_fieldline_visible(response) self.assert_field_visible(response, "first") self.assert_field_visible(response, "second") def test_all_fields_hidden(self): response = self.client.get(reverse("admin:admin_views_emptymodelhidden_add")) self.assert_fieldline_hidden(response) self.assert_field_hidden(response, "first") self.assert_field_hidden(response, "second") def test_mixin(self): response = self.client.get(reverse("admin:admin_views_emptymodelmixin_add")) self.assert_fieldline_visible(response) self.assert_field_hidden(response, "first") self.assert_field_visible(response, "second") def assert_field_visible(self, response, field_name): self.assertContains(response, '<div class="fieldBox field-%s">' % field_name) def assert_field_hidden(self, response, field_name): self.assertContains( response, '<div class="fieldBox field-%s hidden">' % field_name ) def assert_fieldline_visible(self, response): self.assertContains(response, '<div class="form-row field-first field-second">') def assert_fieldline_hidden(self, response): self.assertContains(response, '<div class="form-row hidden') @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewOnSiteTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = State.objects.create(name="New York") cls.s2 = State.objects.create(name="Illinois") cls.s3 = State.objects.create(name="California") cls.c1 = City.objects.create(state=cls.s1, name="New York") cls.c2 = City.objects.create(state=cls.s2, name="Chicago") cls.c3 = City.objects.create(state=cls.s3, name="San Francisco") cls.r1 = Restaurant.objects.create(city=cls.c1, name="Italian Pizza") cls.r2 = Restaurant.objects.create(city=cls.c1, name="Boulevard") cls.r3 = Restaurant.objects.create(city=cls.c2, name="Chinese Dinner") cls.r4 = Restaurant.objects.create(city=cls.c2, name="Angels") cls.r5 = Restaurant.objects.create(city=cls.c2, name="Take Away") cls.r6 = Restaurant.objects.create(city=cls.c3, name="The Unknown Restaurant") cls.w1 = Worker.objects.create(work_at=cls.r1, name="Mario", surname="Rossi") cls.w2 = Worker.objects.create( work_at=cls.r1, name="Antonio", surname="Bianchi" ) cls.w3 = Worker.objects.create(work_at=cls.r1, name="John", surname="Doe") def setUp(self): self.client.force_login(self.superuser) def test_add_view_form_and_formsets_run_validation(self): """ Issue #20522 Verifying that if the parent form fails validation, the inlines also run validation even if validation is contingent on parent form data. Also, assertFormError() and assertFormSetError() is usable for admin forms and formsets. """ # The form validation should fail because 'some_required_info' is # not included on the parent form, and the family_name of the parent # does not match that of the child post_data = { "family_name": "Test1", "dependentchild_set-TOTAL_FORMS": "1", "dependentchild_set-INITIAL_FORMS": "0", "dependentchild_set-MAX_NUM_FORMS": "1", "dependentchild_set-0-id": "", "dependentchild_set-0-parent": "", "dependentchild_set-0-family_name": "Test2", } response = self.client.post( reverse("admin:admin_views_parentwithdependentchildren_add"), post_data ) self.assertFormError( response.context["adminform"], "some_required_info", ["This field is required."], ) self.assertFormError(response.context["adminform"], None, []) self.assertFormSetError( response.context["inline_admin_formset"], 0, None, [ "Children must share a family name with their parents in this " "contrived test case" ], ) self.assertFormSetError( response.context["inline_admin_formset"], None, None, [] ) def test_change_view_form_and_formsets_run_validation(self): """ Issue #20522 Verifying that if the parent form fails validation, the inlines also run validation even if validation is contingent on parent form data """ pwdc = ParentWithDependentChildren.objects.create( some_required_info=6, family_name="Test1" ) # The form validation should fail because 'some_required_info' is # not included on the parent form, and the family_name of the parent # does not match that of the child post_data = { "family_name": "Test2", "dependentchild_set-TOTAL_FORMS": "1", "dependentchild_set-INITIAL_FORMS": "0", "dependentchild_set-MAX_NUM_FORMS": "1", "dependentchild_set-0-id": "", "dependentchild_set-0-parent": str(pwdc.id), "dependentchild_set-0-family_name": "Test1", } response = self.client.post( reverse( "admin:admin_views_parentwithdependentchildren_change", args=(pwdc.id,) ), post_data, ) self.assertFormError( response.context["adminform"], "some_required_info", ["This field is required."], ) self.assertFormSetError( response.context["inline_admin_formset"], 0, None, [ "Children must share a family name with their parents in this " "contrived test case" ], ) def test_check(self): "The view_on_site value is either a boolean or a callable" try: admin = CityAdmin(City, AdminSite()) CityAdmin.view_on_site = True self.assertEqual(admin.check(), []) CityAdmin.view_on_site = False self.assertEqual(admin.check(), []) CityAdmin.view_on_site = lambda obj: obj.get_absolute_url() self.assertEqual(admin.check(), []) CityAdmin.view_on_site = [] self.assertEqual( admin.check(), [ Error( "The value of 'view_on_site' must be a callable or a boolean " "value.", obj=CityAdmin, id="admin.E025", ), ], ) finally: # Restore the original values for the benefit of other tests. CityAdmin.view_on_site = True def test_false(self): "The 'View on site' button is not displayed if view_on_site is False" response = self.client.get( reverse("admin:admin_views_restaurant_change", args=(self.r1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(Restaurant).pk self.assertNotContains( response, reverse("admin:view_on_site", args=(content_type_pk, 1)) ) def test_true(self): "The default behavior is followed if view_on_site is True" response = self.client.get( reverse("admin:admin_views_city_change", args=(self.c1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(City).pk self.assertContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.c1.pk)) ) def test_callable(self): "The right link is displayed if view_on_site is a callable" response = self.client.get( reverse("admin:admin_views_worker_change", args=(self.w1.pk,)) ) self.assertContains( response, '"/worker/%s/%s/"' % (self.w1.surname, self.w1.name) ) def test_missing_get_absolute_url(self): "None is returned if model doesn't have get_absolute_url" model_admin = ModelAdmin(Worker, None) self.assertIsNone(model_admin.get_view_on_site_url(Worker())) def test_custom_admin_site(self): model_admin = ModelAdmin(City, customadmin.site) content_type_pk = ContentType.objects.get_for_model(City).pk redirect_url = model_admin.get_view_on_site_url(self.c1) self.assertEqual( redirect_url, reverse( f"{customadmin.site.name}:view_on_site", kwargs={ "content_type_id": content_type_pk, "object_id": self.c1.pk, }, ), ) @override_settings(ROOT_URLCONF="admin_views.urls") class InlineAdminViewOnSiteTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = State.objects.create(name="New York") cls.s2 = State.objects.create(name="Illinois") cls.s3 = State.objects.create(name="California") cls.c1 = City.objects.create(state=cls.s1, name="New York") cls.c2 = City.objects.create(state=cls.s2, name="Chicago") cls.c3 = City.objects.create(state=cls.s3, name="San Francisco") cls.r1 = Restaurant.objects.create(city=cls.c1, name="Italian Pizza") cls.r2 = Restaurant.objects.create(city=cls.c1, name="Boulevard") cls.r3 = Restaurant.objects.create(city=cls.c2, name="Chinese Dinner") cls.r4 = Restaurant.objects.create(city=cls.c2, name="Angels") cls.r5 = Restaurant.objects.create(city=cls.c2, name="Take Away") cls.r6 = Restaurant.objects.create(city=cls.c3, name="The Unknown Restaurant") cls.w1 = Worker.objects.create(work_at=cls.r1, name="Mario", surname="Rossi") cls.w2 = Worker.objects.create( work_at=cls.r1, name="Antonio", surname="Bianchi" ) cls.w3 = Worker.objects.create(work_at=cls.r1, name="John", surname="Doe") def setUp(self): self.client.force_login(self.superuser) def test_false(self): "The 'View on site' button is not displayed if view_on_site is False" response = self.client.get( reverse("admin:admin_views_state_change", args=(self.s1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(City).pk self.assertNotContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.c1.pk)) ) def test_true(self): "The 'View on site' button is displayed if view_on_site is True" response = self.client.get( reverse("admin:admin_views_city_change", args=(self.c1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(Restaurant).pk self.assertContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.r1.pk)) ) def test_callable(self): "The right link is displayed if view_on_site is a callable" response = self.client.get( reverse("admin:admin_views_restaurant_change", args=(self.r1.pk,)) ) self.assertContains( response, '"/worker_inline/%s/%s/"' % (self.w1.surname, self.w1.name) ) @override_settings(ROOT_URLCONF="admin_views.urls") class GetFormsetsWithInlinesArgumentTest(TestCase): """ #23934 - When adding a new model instance in the admin, the 'obj' argument of get_formsets_with_inlines() should be None. When changing, it should be equal to the existing model instance. The GetFormsetsArgumentCheckingAdmin ModelAdmin throws an exception if obj is not None during add_view or obj is None during change_view. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_explicitly_provided_pk(self): post_data = {"name": "1"} response = self.client.post( reverse("admin:admin_views_explicitlyprovidedpk_add"), post_data ) self.assertEqual(response.status_code, 302) post_data = {"name": "2"} response = self.client.post( reverse("admin:admin_views_explicitlyprovidedpk_change", args=(1,)), post_data, ) self.assertEqual(response.status_code, 302) def test_implicitly_generated_pk(self): post_data = {"name": "1"} response = self.client.post( reverse("admin:admin_views_implicitlygeneratedpk_add"), post_data ) self.assertEqual(response.status_code, 302) post_data = {"name": "2"} response = self.client.post( reverse("admin:admin_views_implicitlygeneratedpk_change", args=(1,)), post_data, ) self.assertEqual(response.status_code, 302) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminSiteFinalCatchAllPatternTests(TestCase): """ Verifies the behaviour of the admin catch-all view. * Anonynous/non-staff users are redirected to login for all URLs, whether otherwise valid or not. * APPEND_SLASH is applied for staff if needed. * Otherwise Http404. * Catch-all view disabled via AdminSite.final_catch_all_view. """ def test_unknown_url_redirects_login_if_not_authenticated(self): unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), unknown_url) ) def test_unknown_url_404_if_authenticated(self): superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]", ) self.client.force_login(superuser) unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_known_url_redirects_login_if_not_authenticated(self): known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), known_url) ) def test_known_url_missing_slash_redirects_login_if_not_authenticated(self): known_url = reverse("admin:admin_views_article_changelist")[:-1] response = self.client.get(known_url) # Redirects with the next URL also missing the slash. self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), known_url) ) def test_non_admin_url_shares_url_prefix(self): url = reverse("non_admin")[:-1] response = self.client.get(url) # Redirects with the next URL also missing the slash. self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) def test_url_without_trailing_slash_if_not_authenticated(self): url = reverse("admin:article_extra_json") response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) def test_unkown_url_without_trailing_slash_if_not_authenticated(self): url = reverse("admin:article_extra_json")[:-1] response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_unknown_url(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, target_status_code=403 ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_script_name(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1], SCRIPT_NAME="/prefix/") self.assertRedirects( response, "/prefix" + known_url, status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True, FORCE_SCRIPT_NAME="/prefix/") def test_missing_slash_append_slash_true_force_script_name(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, "/prefix" + known_url, status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_non_staff_user(self): user = User.objects.create_user( username="user", password="secret", email="[email protected]", is_staff=False, ) self.client.force_login(user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, "/test_admin/admin/login/?next=/test_admin/admin/admin_views/article", ) @override_settings(APPEND_SLASH=False) def test_missing_slash_append_slash_false(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_single_model_no_append_slash(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin9:admin_views_actor_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) # Same tests above with final_catch_all_view=False. def test_unknown_url_404_if_not_authenticated_without_final_catch_all_view(self): unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_unknown_url_404_if_authenticated_without_final_catch_all_view(self): superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]", ) self.client.force_login(superuser) unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_known_url_redirects_login_if_not_auth_without_final_catch_all_view( self, ): known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin10:login"), known_url) ) def test_known_url_missing_slash_redirects_with_slash_if_not_auth_no_catch_all_view( self, ): known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, fetch_redirect_response=False ) def test_non_admin_url_shares_url_prefix_without_final_catch_all_view(self): url = reverse("non_admin10") response = self.client.get(url[:-1]) self.assertRedirects(response, url, status_code=301) def test_url_no_trailing_slash_if_not_auth_without_final_catch_all_view( self, ): url = reverse("admin10:article_extra_json") response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin10:login"), url)) def test_unknown_url_no_trailing_slash_if_not_auth_without_final_catch_all_view( self, ): url = reverse("admin10:article_extra_json")[:-1] response = self.client.get(url) # Matches test_admin/admin10/admin_views/article/<path:object_id>/ self.assertRedirects( response, url + "/", status_code=301, fetch_redirect_response=False ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_unknown_url_without_final_catch_all_view( self, ): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_without_final_catch_all_view(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, target_status_code=403 ) @override_settings(APPEND_SLASH=False) def test_missing_slash_append_slash_false_without_final_catch_all_view(self): superuser = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) self.client.force_login(superuser) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) # Outside admin. def test_non_admin_url_404_if_not_authenticated(self): unknown_url = "/unknown/" response = self.client.get(unknown_url) # Does not redirect to the admin login. self.assertEqual(response.status_code, 404)
c2bb07f6af0a18c75ca0e4771a0bb937f20b06b9ef2ef8555ac85ecf291b3242
import decimal import enum import json import unittest import uuid from django import forms from django.contrib.admin.utils import display_for_field from django.core import checks, exceptions, serializers, validators from django.core.exceptions import FieldError from django.core.management import call_command from django.db import IntegrityError, connection, models from django.db.models.expressions import Exists, OuterRef, RawSQL, Value from django.db.models.functions import Cast, JSONObject, Upper from django.test import TransactionTestCase, override_settings, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils import timezone from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase, PostgreSQLWidgetTestCase from .models import ( ArrayEnumModel, ArrayFieldSubclass, CharArrayModel, DateTimeArrayModel, IntegerArrayModel, NestedIntegerArrayModel, NullableIntegerArrayModel, OtherTypesArrayModel, PostgreSQLModel, Tag, ) try: from django.contrib.postgres.aggregates import ArrayAgg from django.contrib.postgres.expressions import ArraySubquery from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields.array import IndexTransform, SliceTransform from django.contrib.postgres.forms import ( SimpleArrayField, SplitArrayField, SplitArrayWidget, ) from django.db.backends.postgresql.psycopg_any import NumericRange except ImportError: pass @isolate_apps("postgres_tests") class BasicTests(PostgreSQLSimpleTestCase): def test_get_field_display(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ ["Media", [(["vinyl", "cd"], "Audio")]], (("mp3", "mp4"), "Digital"), ], ) tests = ( (["vinyl", "cd"], "Audio"), (("mp3", "mp4"), "Digital"), (("a", "b"), "('a', 'b')"), (["c", "d"], "['c', 'd']"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value) self.assertEqual(instance.get_field_display(), display) def test_get_field_display_nested_array(self): class MyModel(PostgreSQLModel): field = ArrayField( ArrayField(models.CharField(max_length=16)), choices=[ [ "Media", [([["vinyl", "cd"], ("x",)], "Audio")], ], ((["mp3"], ("mp4",)), "Digital"), ], ) tests = ( ([["vinyl", "cd"], ("x",)], "Audio"), ((["mp3"], ("mp4",)), "Digital"), ((("a", "b"), ("c",)), "(('a', 'b'), ('c',))"), ([["a", "b"], ["c"]], "[['a', 'b'], ['c']]"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value) self.assertEqual(instance.get_field_display(), display) class TestSaveLoad(PostgreSQLTestCase): def test_integer(self): instance = IntegerArrayModel(field=[1, 2, 3]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_char(self): instance = CharArrayModel(field=["hello", "goodbye"]) instance.save() loaded = CharArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_dates(self): instance = DateTimeArrayModel( datetimes=[timezone.now()], dates=[timezone.now().date()], times=[timezone.now().time()], ) instance.save() loaded = DateTimeArrayModel.objects.get() self.assertEqual(instance.datetimes, loaded.datetimes) self.assertEqual(instance.dates, loaded.dates) self.assertEqual(instance.times, loaded.times) def test_tuples(self): instance = IntegerArrayModel(field=(1,)) instance.save() loaded = IntegerArrayModel.objects.get() self.assertSequenceEqual(instance.field, loaded.field) def test_integers_passed_as_strings(self): # This checks that get_prep_value is deferred properly instance = IntegerArrayModel(field=["1"]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(loaded.field, [1]) def test_default_null(self): instance = NullableIntegerArrayModel() instance.save() loaded = NullableIntegerArrayModel.objects.get(pk=instance.pk) self.assertIsNone(loaded.field) self.assertEqual(instance.field, loaded.field) def test_null_handling(self): instance = NullableIntegerArrayModel(field=None) instance.save() loaded = NullableIntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) instance = IntegerArrayModel(field=None) with self.assertRaises(IntegrityError): instance.save() def test_nested(self): instance = NestedIntegerArrayModel(field=[[1, 2], [3, 4]]) instance.save() loaded = NestedIntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_other_array_types(self): instance = OtherTypesArrayModel( ips=["192.168.0.1", "::1"], uuids=[uuid.uuid4()], decimals=[decimal.Decimal(1.25), 1.75], tags=[Tag(1), Tag(2), Tag(3)], json=[{"a": 1}, {"b": 2}], int_ranges=[NumericRange(10, 20), NumericRange(30, 40)], bigint_ranges=[ NumericRange(7000000000, 10000000000), NumericRange(50000000000, 70000000000), ], ) instance.save() loaded = OtherTypesArrayModel.objects.get() self.assertEqual(instance.ips, loaded.ips) self.assertEqual(instance.uuids, loaded.uuids) self.assertEqual(instance.decimals, loaded.decimals) self.assertEqual(instance.tags, loaded.tags) self.assertEqual(instance.json, loaded.json) self.assertEqual(instance.int_ranges, loaded.int_ranges) self.assertEqual(instance.bigint_ranges, loaded.bigint_ranges) def test_null_from_db_value_handling(self): instance = OtherTypesArrayModel.objects.create( ips=["192.168.0.1", "::1"], uuids=[uuid.uuid4()], decimals=[decimal.Decimal(1.25), 1.75], tags=None, ) instance.refresh_from_db() self.assertIsNone(instance.tags) self.assertEqual(instance.json, []) self.assertIsNone(instance.int_ranges) self.assertIsNone(instance.bigint_ranges) def test_model_set_on_base_field(self): instance = IntegerArrayModel() field = instance._meta.get_field("field") self.assertEqual(field.model, IntegerArrayModel) self.assertEqual(field.base_field.model, IntegerArrayModel) def test_nested_nullable_base_field(self): instance = NullableIntegerArrayModel.objects.create( field_nested=[[None, None], [None, None]], ) self.assertEqual(instance.field_nested, [[None, None], [None, None]]) class TestQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.objs = NullableIntegerArrayModel.objects.bulk_create( [ NullableIntegerArrayModel(order=1, field=[1]), NullableIntegerArrayModel(order=2, field=[2]), NullableIntegerArrayModel(order=3, field=[2, 3]), NullableIntegerArrayModel(order=4, field=[20, 30, 40]), NullableIntegerArrayModel(order=5, field=None), ] ) def test_empty_list(self): NullableIntegerArrayModel.objects.create(field=[]) obj = ( NullableIntegerArrayModel.objects.annotate( empty_array=models.Value( [], output_field=ArrayField(models.IntegerField()) ), ) .filter(field=models.F("empty_array")) .get() ) self.assertEqual(obj.field, []) self.assertEqual(obj.empty_array, []) def test_exact(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[1]), self.objs[:1] ) def test_exact_null_only_array(self): obj = NullableIntegerArrayModel.objects.create( field=[None], field_nested=[None, None] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[None]), [obj] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field_nested__exact=[None, None]), [obj], ) def test_exact_null_only_nested_array(self): obj1 = NullableIntegerArrayModel.objects.create(field_nested=[[None, None]]) obj2 = NullableIntegerArrayModel.objects.create( field_nested=[[None, None], [None, None]], ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field_nested__exact=[[None, None]], ), [obj1], ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field_nested__exact=[[None, None], [None, None]], ), [obj2], ) def test_exact_with_expression(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[Value(1)]), self.objs[:1], ) def test_exact_charfield(self): instance = CharArrayModel.objects.create(field=["text"]) self.assertSequenceEqual( CharArrayModel.objects.filter(field=["text"]), [instance] ) def test_exact_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field=[[1, 2], [3, 4]]), [instance] ) def test_isnull(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__isnull=True), self.objs[-1:] ) def test_gt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__gt=[0]), self.objs[:4] ) def test_lt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__lt=[2]), self.objs[:1] ) def test_in(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[1], [2]]), self.objs[:2], ) def test_in_subquery(self): IntegerArrayModel.objects.create(field=[2, 3]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__in=IntegerArrayModel.objects.values_list("field", flat=True) ), self.objs[2:3], ) @unittest.expectedFailure def test_in_including_F_object(self): # This test asserts that Array objects passed to filters can be # constructed to contain F objects. This currently doesn't work as the # psycopg mogrify method that generates the ARRAY() syntax is # expecting literals, not column references (#27095). self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[models.F("id")]]), self.objs[:2], ) def test_in_as_F_object(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[models.F("field")]), self.objs[:4], ) def test_contained_by(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contained_by=[1, 2]), self.objs[:2], ) def test_contained_by_including_F_object(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__contained_by=[models.F("order"), 2] ), self.objs[:3], ) def test_contains(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contains=[2]), self.objs[1:3], ) def test_contains_subquery(self): IntegerArrayModel.objects.create(field=[2, 3]) inner_qs = IntegerArrayModel.objects.values_list("field", flat=True) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contains=inner_qs[:1]), self.objs[2:3], ) inner_qs = IntegerArrayModel.objects.filter(field__contains=OuterRef("field")) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(Exists(inner_qs)), self.objs[1:3], ) def test_contains_including_expression(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__contains=[2, Value(6) / Value(2)], ), self.objs[2:3], ) def test_icontains(self): # Using the __icontains lookup with ArrayField is inefficient. instance = CharArrayModel.objects.create(field=["FoO"]) self.assertSequenceEqual( CharArrayModel.objects.filter(field__icontains="foo"), [instance] ) def test_contains_charfield(self): # Regression for #22907 self.assertSequenceEqual( CharArrayModel.objects.filter(field__contains=["text"]), [] ) def test_contained_by_charfield(self): self.assertSequenceEqual( CharArrayModel.objects.filter(field__contained_by=["text"]), [] ) def test_overlap_charfield(self): self.assertSequenceEqual( CharArrayModel.objects.filter(field__overlap=["text"]), [] ) def test_overlap_charfield_including_expression(self): obj_1 = CharArrayModel.objects.create(field=["TEXT", "lower text"]) obj_2 = CharArrayModel.objects.create(field=["lower text", "TEXT"]) CharArrayModel.objects.create(field=["lower text", "text"]) self.assertSequenceEqual( CharArrayModel.objects.filter( field__overlap=[ Upper(Value("text")), "other", ] ), [obj_1, obj_2], ) def test_overlap_values(self): qs = NullableIntegerArrayModel.objects.filter(order__lt=3) self.assertCountEqual( NullableIntegerArrayModel.objects.filter( field__overlap=qs.values_list("field"), ), self.objs[:3], ) self.assertCountEqual( NullableIntegerArrayModel.objects.filter( field__overlap=qs.values("field"), ), self.objs[:3], ) def test_lookups_autofield_array(self): qs = ( NullableIntegerArrayModel.objects.filter( field__0__isnull=False, ) .values("field__0") .annotate( arrayagg=ArrayAgg("id"), ) .order_by("field__0") ) tests = ( ("contained_by", [self.objs[1].pk, self.objs[2].pk, 0], [2]), ("contains", [self.objs[2].pk], [2]), ("exact", [self.objs[3].pk], [20]), ("overlap", [self.objs[1].pk, self.objs[3].pk], [2, 20]), ) for lookup, value, expected in tests: with self.subTest(lookup=lookup): self.assertSequenceEqual( qs.filter( **{"arrayagg__" + lookup: value}, ).values_list("field__0", flat=True), expected, ) @skipUnlessDBFeature("allows_group_by_select_index") def test_group_by_order_by_select_index(self): with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0__isnull=False, ) .values("field__0") .annotate(arrayagg=ArrayAgg("id")) .order_by("field__0"), [ {"field__0": 1, "arrayagg": [self.objs[0].pk]}, {"field__0": 2, "arrayagg": [self.objs[1].pk, self.objs[2].pk]}, {"field__0": 20, "arrayagg": [self.objs[3].pk]}, ], ) alias = connection.ops.quote_name("field__0") sql = ctx[0]["sql"] self.assertIn("GROUP BY 1", sql) self.assertIn(f"ORDER BY {alias}", sql) def test_index(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0=2), self.objs[1:3] ) def test_index_chained(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0__lt=3), self.objs[0:3] ) def test_index_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0__0=1), [instance] ) @unittest.expectedFailure def test_index_used_on_nested_data(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0=[1, 2]), [instance] ) def test_index_transform_expression(self): expr = RawSQL("string_to_array(%s, ';')", ["1;2"]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0=Cast( IndexTransform(1, models.IntegerField, expr), output_field=models.IntegerField(), ), ), self.objs[:1], ) def test_index_annotation(self): qs = NullableIntegerArrayModel.objects.annotate(second=models.F("field__1")) self.assertCountEqual( qs.values_list("second", flat=True), [None, None, None, 3, 30], ) def test_overlap(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__overlap=[1, 2]), self.objs[0:3], ) def test_len(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__len__lte=2), self.objs[0:3] ) def test_len_empty_array(self): obj = NullableIntegerArrayModel.objects.create(field=[]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__len=0), [obj] ) def test_slice(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0_1=[2]), self.objs[1:3] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0_2=[2, 3]), self.objs[2:3] ) def test_order_by_slice(self): more_objs = ( NullableIntegerArrayModel.objects.create(field=[1, 637]), NullableIntegerArrayModel.objects.create(field=[2, 1]), NullableIntegerArrayModel.objects.create(field=[3, -98123]), NullableIntegerArrayModel.objects.create(field=[4, 2]), ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.order_by("field__1"), [ more_objs[2], more_objs[1], more_objs[3], self.objs[2], self.objs[3], more_objs[0], self.objs[4], self.objs[1], self.objs[0], ], ) @unittest.expectedFailure def test_slice_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0__0_1=[1]), [instance] ) def test_slice_transform_expression(self): expr = RawSQL("string_to_array(%s, ';')", ["9;2;3"]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0_2=SliceTransform(2, 3, expr) ), self.objs[2:3], ) def test_slice_annotation(self): qs = NullableIntegerArrayModel.objects.annotate( first_two=models.F("field__0_2"), ) self.assertCountEqual( qs.values_list("first_two", flat=True), [None, [1], [2], [2, 3], [20, 30]], ) def test_usage_in_subquery(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( id__in=NullableIntegerArrayModel.objects.filter(field__len=3) ), [self.objs[3]], ) def test_enum_lookup(self): class TestEnum(enum.Enum): VALUE_1 = "value_1" instance = ArrayEnumModel.objects.create(array_of_enums=[TestEnum.VALUE_1]) self.assertSequenceEqual( ArrayEnumModel.objects.filter(array_of_enums__contains=[TestEnum.VALUE_1]), [instance], ) def test_unsupported_lookup(self): msg = ( "Unsupported lookup '0_bar' for ArrayField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): list(NullableIntegerArrayModel.objects.filter(field__0_bar=[2])) msg = ( "Unsupported lookup '0bar' for ArrayField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): list(NullableIntegerArrayModel.objects.filter(field__0bar=[2])) def test_grouping_by_annotations_with_array_field_param(self): value = models.Value([1], output_field=ArrayField(models.IntegerField())) self.assertEqual( NullableIntegerArrayModel.objects.annotate( array_length=models.Func( value, 1, function="ARRAY_LENGTH", output_field=models.IntegerField(), ), ) .values("array_length") .annotate( count=models.Count("pk"), ) .get()["array_length"], 1, ) def test_filter_by_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.filter( field__len=models.OuterRef("field__len"), ).values("field") self.assertSequenceEqual( NullableIntegerArrayModel.objects.alias( same_sized_fields=ArraySubquery(inner_qs), ).filter(same_sized_fields__len__gt=1), self.objs[0:2], ) def test_annotated_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( sibling_ids=ArraySubquery(inner_qs), ) .get(order=1) .sibling_ids, [2, 3, 4, 5], ) def test_group_by_with_annotated_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( sibling_ids=ArraySubquery(inner_qs), sibling_count=models.Max("sibling_ids__len"), ).values_list("sibling_count", flat=True), [len(self.objs) - 1] * len(self.objs), ) def test_annotated_ordered_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.order_by("-order").values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( ids=ArraySubquery(inner_qs), ) .first() .ids, [5, 4, 3, 2, 1], ) def test_annotated_array_subquery_with_json_objects(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values(json=JSONObject(order="order", field="field")) siblings_json = ( NullableIntegerArrayModel.objects.annotate( siblings_json=ArraySubquery(inner_qs), ) .values_list("siblings_json", flat=True) .get(order=1) ) self.assertSequenceEqual( siblings_json, [ {"field": [2], "order": 2}, {"field": [2, 3], "order": 3}, {"field": [20, 30, 40], "order": 4}, {"field": None, "order": 5}, ], ) class TestDateTimeExactQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): now = timezone.now() cls.datetimes = [now] cls.dates = [now.date()] cls.times = [now.time()] cls.objs = [ DateTimeArrayModel.objects.create( datetimes=cls.datetimes, dates=cls.dates, times=cls.times ), ] def test_exact_datetimes(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(datetimes=self.datetimes), self.objs ) def test_exact_dates(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(dates=self.dates), self.objs ) def test_exact_times(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(times=self.times), self.objs ) class TestOtherTypesExactQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.ips = ["192.168.0.1", "::1"] cls.uuids = [uuid.uuid4()] cls.decimals = [decimal.Decimal(1.25), 1.75] cls.tags = [Tag(1), Tag(2), Tag(3)] cls.objs = [ OtherTypesArrayModel.objects.create( ips=cls.ips, uuids=cls.uuids, decimals=cls.decimals, tags=cls.tags, ) ] def test_exact_ip_addresses(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(ips=self.ips), self.objs ) def test_exact_uuids(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(uuids=self.uuids), self.objs ) def test_exact_decimals(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(decimals=self.decimals), self.objs ) def test_exact_tags(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(tags=self.tags), self.objs ) @isolate_apps("postgres_tests") class TestChecks(PostgreSQLSimpleTestCase): def test_field_checks(self): class MyModel(PostgreSQLModel): field = ArrayField(models.CharField(max_length=-1)) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField has a non-positive max_length. self.assertEqual(errors[0].id, "postgres.E001") self.assertIn("max_length", errors[0].msg) def test_invalid_base_fields(self): class MyModel(PostgreSQLModel): field = ArrayField( models.ManyToManyField("postgres_tests.IntegerArrayModel") ) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "postgres.E002") def test_invalid_default(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=[]) model = MyModel() self.assertEqual( model.check(), [ checks.Warning( msg=( "ArrayField default should be a callable instead of an " "instance so that it's not shared between all field " "instances." ), hint="Use a callable instead, e.g., use `list` instead of `[]`.", obj=MyModel._meta.get_field("field"), id="fields.E010", ) ], ) def test_valid_default(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=list) model = MyModel() self.assertEqual(model.check(), []) def test_valid_default_none(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=None) model = MyModel() self.assertEqual(model.check(), []) def test_nested_field_checks(self): """ Nested ArrayFields are permitted. """ class MyModel(PostgreSQLModel): field = ArrayField(ArrayField(models.CharField(max_length=-1))) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField has a non-positive max_length. self.assertEqual(errors[0].id, "postgres.E001") self.assertIn("max_length", errors[0].msg) def test_choices_tuple_list(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ [ "Media", [(["vinyl", "cd"], "Audio"), (("vhs", "dvd"), "Video")], ], (["mp3", "mp4"], "Digital"), ], ) self.assertEqual(MyModel._meta.get_field("field").check(), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") class TestMigrations(TransactionTestCase): available_apps = ["postgres_tests"] def test_deconstruct(self): field = ArrayField(models.IntegerField()) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(type(new.base_field), type(field.base_field)) self.assertIsNot(new.base_field, field.base_field) def test_deconstruct_with_size(self): field = ArrayField(models.IntegerField(), size=3) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(new.size, field.size) def test_deconstruct_args(self): field = ArrayField(models.CharField(max_length=20)) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(new.base_field.max_length, field.base_field.max_length) def test_subclass_deconstruct(self): field = ArrayField(models.IntegerField()) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.contrib.postgres.fields.ArrayField") field = ArrayFieldSubclass() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "postgres_tests.models.ArrayFieldSubclass") @override_settings( MIGRATION_MODULES={ "postgres_tests": "postgres_tests.array_default_migrations", } ) def test_adding_field_with_default(self): # See #22962 table_name = "postgres_tests_integerarraydefaultmodel" with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) call_command("migrate", "postgres_tests", verbosity=0) with connection.cursor() as cursor: self.assertIn(table_name, connection.introspection.table_names(cursor)) call_command("migrate", "postgres_tests", "zero", verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) @override_settings( MIGRATION_MODULES={ "postgres_tests": "postgres_tests.array_index_migrations", } ) def test_adding_arrayfield_with_index(self): """ ArrayField shouldn't have varchar_patterns_ops or text_patterns_ops indexes. """ table_name = "postgres_tests_chartextarrayindexmodel" call_command("migrate", "postgres_tests", verbosity=0) with connection.cursor() as cursor: like_constraint_columns_list = [ v["columns"] for k, v in list( connection.introspection.get_constraints(cursor, table_name).items() ) if k.endswith("_like") ] # Only the CharField should have a LIKE index. self.assertEqual(like_constraint_columns_list, [["char2"]]) # All fields should have regular indexes. with connection.cursor() as cursor: indexes = [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table_name ).values() if c["index"] and len(c["columns"]) == 1 ] self.assertIn("char", indexes) self.assertIn("char2", indexes) self.assertIn("text", indexes) call_command("migrate", "postgres_tests", "zero", verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) class TestSerialization(PostgreSQLSimpleTestCase): test_data = ( '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, ' '"model": "postgres_tests.integerarraymodel", "pk": null}]' ) def test_dumping(self): instance = IntegerArrayModel(field=[1, 2, None]) data = serializers.serialize("json", [instance]) self.assertEqual(json.loads(data), json.loads(self.test_data)) def test_loading(self): instance = list(serializers.deserialize("json", self.test_data))[0].object self.assertEqual(instance.field, [1, 2, None]) class TestValidation(PostgreSQLSimpleTestCase): def test_unbounded(self): field = ArrayField(models.IntegerField()) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, None], None) self.assertEqual(cm.exception.code, "item_invalid") self.assertEqual( cm.exception.message % cm.exception.params, "Item 2 in the array did not validate: This field cannot be null.", ) def test_blank_true(self): field = ArrayField(models.IntegerField(blank=True, null=True)) # This should not raise a validation error field.clean([1, None], None) def test_with_size(self): field = ArrayField(models.IntegerField(), size=3) field.clean([1, 2, 3], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, 2, 3, 4], None) self.assertEqual( cm.exception.messages[0], "List contains 4 items, it should contain no more than 3.", ) def test_nested_array_mismatch(self): field = ArrayField(ArrayField(models.IntegerField())) field.clean([[1, 2], [3, 4]], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([[1, 2], [3, 4, 5]], None) self.assertEqual(cm.exception.code, "nested_array_mismatch") self.assertEqual( cm.exception.messages[0], "Nested arrays must have the same length." ) def test_with_base_field_error_params(self): field = ArrayField(models.CharField(max_length=2)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["abc"], None) self.assertEqual(len(cm.exception.error_list), 1) exception = cm.exception.error_list[0] self.assertEqual( exception.message, "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", ) self.assertEqual(exception.code, "item_invalid") self.assertEqual( exception.params, {"nth": 1, "value": "abc", "limit_value": 2, "show_value": 3}, ) def test_with_validators(self): field = ArrayField( models.IntegerField(validators=[validators.MinValueValidator(1)]) ) field.clean([1, 2], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([0], None) self.assertEqual(len(cm.exception.error_list), 1) exception = cm.exception.error_list[0] self.assertEqual( exception.message, "Item 1 in the array did not validate: Ensure this value is greater than " "or equal to 1.", ) self.assertEqual(exception.code, "item_invalid") self.assertEqual( exception.params, {"nth": 1, "value": 0, "limit_value": 1, "show_value": 0} ) class TestSimpleFormField(PostgreSQLSimpleTestCase): def test_valid(self): field = SimpleArrayField(forms.CharField()) value = field.clean("a,b,c") self.assertEqual(value, ["a", "b", "c"]) def test_to_python_fail(self): field = SimpleArrayField(forms.IntegerField()) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,9") self.assertEqual( cm.exception.messages[0], "Item 1 in the array did not validate: Enter a whole number.", ) def test_validate_fail(self): field = SimpleArrayField(forms.CharField(required=True)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,") self.assertEqual( cm.exception.messages[0], "Item 3 in the array did not validate: This field is required.", ) def test_validate_fail_base_field_error_params(self): field = SimpleArrayField(forms.CharField(max_length=2)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("abc,c,defg") errors = cm.exception.error_list self.assertEqual(len(errors), 2) first_error = errors[0] self.assertEqual( first_error.message, "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", ) self.assertEqual(first_error.code, "item_invalid") self.assertEqual( first_error.params, {"nth": 1, "value": "abc", "limit_value": 2, "show_value": 3}, ) second_error = errors[1] self.assertEqual( second_error.message, "Item 3 in the array did not validate: Ensure this value has at most 2 " "characters (it has 4).", ) self.assertEqual(second_error.code, "item_invalid") self.assertEqual( second_error.params, {"nth": 3, "value": "defg", "limit_value": 2, "show_value": 4}, ) def test_validators_fail(self): field = SimpleArrayField(forms.RegexField("[a-e]{2}")) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,bc,de") self.assertEqual( cm.exception.messages[0], "Item 1 in the array did not validate: Enter a valid value.", ) def test_delimiter(self): field = SimpleArrayField(forms.CharField(), delimiter="|") value = field.clean("a|b|c") self.assertEqual(value, ["a", "b", "c"]) def test_delimiter_with_nesting(self): field = SimpleArrayField(SimpleArrayField(forms.CharField()), delimiter="|") value = field.clean("a,b|c,d") self.assertEqual(value, [["a", "b"], ["c", "d"]]) def test_prepare_value(self): field = SimpleArrayField(forms.CharField()) value = field.prepare_value(["a", "b", "c"]) self.assertEqual(value, "a,b,c") def test_max_length(self): field = SimpleArrayField(forms.CharField(), max_length=2) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,c") self.assertEqual( cm.exception.messages[0], "List contains 3 items, it should contain no more than 2.", ) def test_min_length(self): field = SimpleArrayField(forms.CharField(), min_length=4) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,c") self.assertEqual( cm.exception.messages[0], "List contains 3 items, it should contain no fewer than 4.", ) def test_required(self): field = SimpleArrayField(forms.CharField(), required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("") self.assertEqual(cm.exception.messages[0], "This field is required.") def test_model_field_formfield(self): model_field = ArrayField(models.CharField(max_length=27)) form_field = model_field.formfield() self.assertIsInstance(form_field, SimpleArrayField) self.assertIsInstance(form_field.base_field, forms.CharField) self.assertEqual(form_field.base_field.max_length, 27) def test_model_field_formfield_size(self): model_field = ArrayField(models.CharField(max_length=27), size=4) form_field = model_field.formfield() self.assertIsInstance(form_field, SimpleArrayField) self.assertEqual(form_field.max_length, 4) def test_model_field_choices(self): model_field = ArrayField(models.IntegerField(choices=((1, "A"), (2, "B")))) form_field = model_field.formfield() self.assertEqual(form_field.clean("1,2"), [1, 2]) def test_already_converted_value(self): field = SimpleArrayField(forms.CharField()) vals = ["a", "b", "c"] self.assertEqual(field.clean(vals), vals) def test_has_changed(self): field = SimpleArrayField(forms.IntegerField()) self.assertIs(field.has_changed([1, 2], [1, 2]), False) self.assertIs(field.has_changed([1, 2], "1,2"), False) self.assertIs(field.has_changed([1, 2], "1,2,3"), True) self.assertIs(field.has_changed([1, 2], "a,b"), True) def test_has_changed_empty(self): field = SimpleArrayField(forms.CharField()) self.assertIs(field.has_changed(None, None), False) self.assertIs(field.has_changed(None, ""), False) self.assertIs(field.has_changed(None, []), False) self.assertIs(field.has_changed([], None), False) self.assertIs(field.has_changed([], ""), False) class TestSplitFormField(PostgreSQLSimpleTestCase): def test_valid(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) data = {"array_0": "a", "array_1": "b", "array_2": "c"} form = SplitForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"array": ["a", "b", "c"]}) def test_required(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), required=True, size=3) data = {"array_0": "", "array_1": "", "array_2": ""} form = SplitForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"array": ["This field is required."]}) def test_remove_trailing_nulls(self): class SplitForm(forms.Form): array = SplitArrayField( forms.CharField(required=False), size=5, remove_trailing_nulls=True ) data = { "array_0": "a", "array_1": "", "array_2": "b", "array_3": "", "array_4": "", } form = SplitForm(data) self.assertTrue(form.is_valid(), form.errors) self.assertEqual(form.cleaned_data, {"array": ["a", "", "b"]}) def test_remove_trailing_nulls_not_required(self): class SplitForm(forms.Form): array = SplitArrayField( forms.CharField(required=False), size=2, remove_trailing_nulls=True, required=False, ) data = {"array_0": "", "array_1": ""} form = SplitForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"array": []}) def test_required_field(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) data = {"array_0": "a", "array_1": "b", "array_2": ""} form = SplitForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "array": [ "Item 3 in the array did not validate: This field is required." ] }, ) def test_invalid_integer(self): msg = ( "Item 2 in the array did not validate: Ensure this value is less than or " "equal to 100." ) with self.assertRaisesMessage(exceptions.ValidationError, msg): SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101]) def test_rendering(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) self.assertHTMLEqual( str(SplitForm()), """ <div> <label for="id_array_0">Array:</label> <input id="id_array_0" name="array_0" type="text" required> <input id="id_array_1" name="array_1" type="text" required> <input id="id_array_2" name="array_2" type="text" required> </div> """, ) def test_invalid_char_length(self): field = SplitArrayField(forms.CharField(max_length=2), size=3) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["abc", "c", "defg"]) self.assertEqual( cm.exception.messages, [ "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", "Item 3 in the array did not validate: Ensure this value has at most 2 " "characters (it has 4).", ], ) def test_splitarraywidget_value_omitted_from_data(self): class Form(forms.ModelForm): field = SplitArrayField(forms.IntegerField(), required=False, size=2) class Meta: model = IntegerArrayModel fields = ("field",) form = Form({"field_0": "1", "field_1": "2"}) self.assertEqual(form.errors, {}) obj = form.save(commit=False) self.assertEqual(obj.field, [1, 2]) def test_splitarrayfield_has_changed(self): class Form(forms.ModelForm): field = SplitArrayField(forms.IntegerField(), required=False, size=2) class Meta: model = IntegerArrayModel fields = ("field",) tests = [ ({}, {"field_0": "", "field_1": ""}, True), ({"field": None}, {"field_0": "", "field_1": ""}, True), ({"field": [1]}, {"field_0": "", "field_1": ""}, True), ({"field": [1]}, {"field_0": "1", "field_1": "0"}, True), ({"field": [1, 2]}, {"field_0": "1", "field_1": "2"}, False), ({"field": [1, 2]}, {"field_0": "a", "field_1": "b"}, True), ] for initial, data, expected_result in tests: with self.subTest(initial=initial, data=data): obj = IntegerArrayModel(**initial) form = Form(data, instance=obj) self.assertIs(form.has_changed(), expected_result) def test_splitarrayfield_remove_trailing_nulls_has_changed(self): class Form(forms.ModelForm): field = SplitArrayField( forms.IntegerField(), required=False, size=2, remove_trailing_nulls=True ) class Meta: model = IntegerArrayModel fields = ("field",) tests = [ ({}, {"field_0": "", "field_1": ""}, False), ({"field": None}, {"field_0": "", "field_1": ""}, False), ({"field": []}, {"field_0": "", "field_1": ""}, False), ({"field": [1]}, {"field_0": "1", "field_1": ""}, False), ] for initial, data, expected_result in tests: with self.subTest(initial=initial, data=data): obj = IntegerArrayModel(**initial) form = Form(data, instance=obj) self.assertIs(form.has_changed(), expected_result) class TestSplitFormWidget(PostgreSQLWidgetTestCase): def test_get_context(self): self.assertEqual( SplitArrayWidget(forms.TextInput(), size=2).get_context( "name", ["val1", "val2"] ), { "widget": { "name": "name", "is_hidden": False, "required": False, "value": "['val1', 'val2']", "attrs": {}, "template_name": "postgres/widgets/split_array.html", "subwidgets": [ { "name": "name_0", "is_hidden": False, "required": False, "value": "val1", "attrs": {}, "template_name": "django/forms/widgets/text.html", "type": "text", }, { "name": "name_1", "is_hidden": False, "required": False, "value": "val2", "attrs": {}, "template_name": "django/forms/widgets/text.html", "type": "text", }, ], } }, ) def test_checkbox_get_context_attrs(self): context = SplitArrayWidget( forms.CheckboxInput(), size=2, ).get_context("name", [True, False]) self.assertEqual(context["widget"]["value"], "[True, False]") self.assertEqual( [subwidget["attrs"] for subwidget in context["widget"]["subwidgets"]], [{"checked": True}, {}], ) def test_render(self): self.check_html( SplitArrayWidget(forms.TextInput(), size=2), "array", None, """ <input name="array_0" type="text"> <input name="array_1" type="text"> """, ) def test_render_attrs(self): self.check_html( SplitArrayWidget(forms.TextInput(), size=2), "array", ["val1", "val2"], attrs={"id": "foo"}, html=( """ <input id="foo_0" name="array_0" type="text" value="val1"> <input id="foo_1" name="array_1" type="text" value="val2"> """ ), ) def test_value_omitted_from_data(self): widget = SplitArrayWidget(forms.TextInput(), size=2) self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True) self.assertIs( widget.value_omitted_from_data({"field_0": "value"}, {}, "field"), False ) self.assertIs( widget.value_omitted_from_data({"field_1": "value"}, {}, "field"), False ) self.assertIs( widget.value_omitted_from_data( {"field_0": "value", "field_1": "value"}, {}, "field" ), False, ) class TestAdminUtils(PostgreSQLTestCase): empty_value = "-empty-" def test_array_display_for_field(self): array_field = ArrayField(models.IntegerField()) display_value = display_for_field( [1, 2], array_field, self.empty_value, ) self.assertEqual(display_value, "1, 2") def test_array_with_choices_display_for_field(self): array_field = ArrayField( models.IntegerField(), choices=[ ([1, 2, 3], "1st choice"), ([1, 2], "2nd choice"), ], ) display_value = display_for_field( [1, 2], array_field, self.empty_value, ) self.assertEqual(display_value, "2nd choice") display_value = display_for_field( [99, 99], array_field, self.empty_value, ) self.assertEqual(display_value, self.empty_value)
bf5f37bb8411b12cce50b5cd47e9afd53e1b25713befab71742ca439c125276c
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() def test_module_import(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ # Relative imports. b'import testConst from "./module_test.477bbebe77f0.js";', b'import relativeModule from "../nested/js/nested.866475c46bb4.js";', b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";', # Absolute import. b'import rootConst from "/static/absolute_root.5586327fe78c.js";', # Dynamic import. b'const dynamicModule = import("./module_test.477bbebe77f0.js");', # Creating a module object. b'import * as NewModule from "./module_test.477bbebe77f0.js";', # Aliases. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";', b"import {\n" b" firstVar1 as firstVarAlias,\n" b" $second_var_2 as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) self.assertPostCondition() def test_aggregating_modules(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ b'export * from "./module_test.477bbebe77f0.js";', b'export { testConst } from "./module_test.477bbebe77f0.js";', b"export {\n" b" firstVar as firstVarAlias,\n" b" secondVar as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue()) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage", }, } ) class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") self.patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) self.patched_settings.enable() self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): self.patched_settings.disable() if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) def test_manifest_hash(self): # Collect the additional file. self.run_collectstatic() _, manifest_hash_orig = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash_orig, "") self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Saving doesn't change the hash. storage.staticfiles_storage.save_manifest() self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Delete the original file from the app, collect with clear. os.unlink(self._clear_filename) self.run_collectstatic(clear=True) # Hash is changed. _, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash, manifest_hash_orig) def test_manifest_hash_v1(self): storage.staticfiles_storage.manifest_name = "staticfiles_v1.json" manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertEqual(manifest_hash, "") self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"}) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoneHashStorage", }, } ) class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage", }, } ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.SimpleStorage", }, } ) class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): self.manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=self.manifest_path, ) self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) super().setUp() def tearDown(self): os.umask(self.old_umask) super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.test_storage.CustomStaticFilesStorage", }, }, ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
e9de6c3afeaffb6918282f524f35288b5a227f7bd80cf81d6e24e39b82e06106
from datetime import datetime from functools import partialmethod from io import StringIO from unittest import mock, skipIf from django.core import serializers from django.core.serializers import SerializerDoesNotExist from django.core.serializers.base import ProgressBar from django.db import connection, transaction from django.http import HttpResponse from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature from django.test.utils import Approximate from .models import ( Actor, Article, Author, AuthorProfile, BaseModel, Category, Child, ComplexModel, Movie, Player, ProxyBaseModel, ProxyProxyBaseModel, Score, Team, ) @override_settings( SERIALIZATION_MODULES={ "json2": "django.core.serializers.json", } ) class SerializerRegistrationTests(SimpleTestCase): def setUp(self): self.old_serializers = serializers._serializers serializers._serializers = {} def tearDown(self): serializers._serializers = self.old_serializers def test_register(self): "Registering a new serializer populates the full registry. Refs #14823" serializers.register_serializer("json3", "django.core.serializers.json") public_formats = serializers.get_public_serializer_formats() self.assertIn("json3", public_formats) self.assertIn("json2", public_formats) self.assertIn("xml", public_formats) def test_unregister(self): """ Unregistering a serializer doesn't cause the registry to be repopulated. """ serializers.unregister_serializer("xml") serializers.register_serializer("json3", "django.core.serializers.json") public_formats = serializers.get_public_serializer_formats() self.assertNotIn("xml", public_formats) self.assertIn("json3", public_formats) def test_unregister_unknown_serializer(self): with self.assertRaises(SerializerDoesNotExist): serializers.unregister_serializer("nonsense") def test_builtin_serializers(self): "Requesting a list of serializer formats populates the registry" all_formats = set(serializers.get_serializer_formats()) public_formats = set(serializers.get_public_serializer_formats()) self.assertIn("xml", all_formats), self.assertIn("xml", public_formats) self.assertIn("json2", all_formats) self.assertIn("json2", public_formats) self.assertIn("python", all_formats) self.assertNotIn("python", public_formats) def test_get_unknown_serializer(self): """ #15889: get_serializer('nonsense') raises a SerializerDoesNotExist """ with self.assertRaises(SerializerDoesNotExist): serializers.get_serializer("nonsense") with self.assertRaises(KeyError): serializers.get_serializer("nonsense") # SerializerDoesNotExist is instantiated with the nonexistent format with self.assertRaisesMessage(SerializerDoesNotExist, "nonsense"): serializers.get_serializer("nonsense") def test_get_unknown_deserializer(self): with self.assertRaises(SerializerDoesNotExist): serializers.get_deserializer("nonsense") class SerializersTestBase: serializer_name = None # Set by subclasses to the serialization format name @classmethod def setUpTestData(cls): sports = Category.objects.create(name="Sports") music = Category.objects.create(name="Music") op_ed = Category.objects.create(name="Op-Ed") cls.joe = Author.objects.create(name="Joe") cls.jane = Author.objects.create(name="Jane") cls.a1 = Article( author=cls.jane, headline="Poker has no place on ESPN", pub_date=datetime(2006, 6, 16, 11, 00), ) cls.a1.save() cls.a1.categories.set([sports, op_ed]) cls.a2 = Article( author=cls.joe, headline="Time to reform copyright", pub_date=datetime(2006, 6, 16, 13, 00, 11, 345), ) cls.a2.save() cls.a2.categories.set([music, op_ed]) def test_serialize(self): """Basic serialization works.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) self.assertTrue(self._validate_output(serial_str)) def test_serializer_roundtrip(self): """Serialized content can be deserialized.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) models = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(len(models), 2) def test_serialize_to_stream(self): obj = ComplexModel(field1="first", field2="second", field3="third") obj.save_base(raw=True) # Serialize the test database to a stream for stream in (StringIO(), HttpResponse()): serializers.serialize(self.serializer_name, [obj], indent=2, stream=stream) # Serialize normally for a comparison string_data = serializers.serialize(self.serializer_name, [obj], indent=2) # The two are the same if isinstance(stream, StringIO): self.assertEqual(string_data, stream.getvalue()) else: self.assertEqual(string_data, stream.content.decode()) def test_serialize_specific_fields(self): obj = ComplexModel(field1="first", field2="second", field3="third") obj.save_base(raw=True) # Serialize then deserialize the test database serialized_data = serializers.serialize( self.serializer_name, [obj], indent=2, fields=("field1", "field3") ) result = next(serializers.deserialize(self.serializer_name, serialized_data)) # The deserialized object contains data in only the serialized fields. self.assertEqual(result.object.field1, "first") self.assertEqual(result.object.field2, "") self.assertEqual(result.object.field3, "third") def test_altering_serialized_output(self): """ The ability to create new objects by modifying serialized content. """ old_headline = "Poker has no place on ESPN" new_headline = "Poker has no place on television" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) serial_str = serial_str.replace(old_headline, new_headline) models = list(serializers.deserialize(self.serializer_name, serial_str)) # Prior to saving, old headline is in place self.assertTrue(Article.objects.filter(headline=old_headline)) self.assertFalse(Article.objects.filter(headline=new_headline)) for model in models: model.save() # After saving, new headline is in place self.assertTrue(Article.objects.filter(headline=new_headline)) self.assertFalse(Article.objects.filter(headline=old_headline)) def test_one_to_one_as_pk(self): """ If you use your own primary key field (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier. """ AuthorProfile.objects.create( author=self.joe, date_of_birth=datetime(1970, 1, 1) ) serial_str = serializers.serialize( self.serializer_name, AuthorProfile.objects.all() ) self.assertFalse(self._get_field_values(serial_str, "author")) for obj in serializers.deserialize(self.serializer_name, serial_str): self.assertEqual(obj.object.pk, self.joe.pk) def test_serialize_field_subset(self): """Output can be restricted to a subset of fields""" valid_fields = ("headline", "pub_date") invalid_fields = ("author", "categories") serial_str = serializers.serialize( self.serializer_name, Article.objects.all(), fields=valid_fields ) for field_name in invalid_fields: self.assertFalse(self._get_field_values(serial_str, field_name)) for field_name in valid_fields: self.assertTrue(self._get_field_values(serial_str, field_name)) def test_serialize_unicode_roundtrip(self): """Unicode makes the roundtrip intact""" actor_name = "Za\u017c\u00f3\u0142\u0107" movie_title = "G\u0119\u015bl\u0105 ja\u017a\u0144" ac = Actor(name=actor_name) mv = Movie(title=movie_title, actor=ac) ac.save() mv.save() serial_str = serializers.serialize(self.serializer_name, [mv]) self.assertEqual(self._get_field_values(serial_str, "title")[0], movie_title) self.assertEqual(self._get_field_values(serial_str, "actor")[0], actor_name) obj_list = list(serializers.deserialize(self.serializer_name, serial_str)) mv_obj = obj_list[0].object self.assertEqual(mv_obj.title, movie_title) def test_unicode_serialization(self): unicode_name = "יוניקוד" data = serializers.serialize(self.serializer_name, [Author(name=unicode_name)]) self.assertIn(unicode_name, data) objs = list(serializers.deserialize(self.serializer_name, data)) self.assertEqual(objs[0].object.name, unicode_name) def test_serialize_progressbar(self): fake_stdout = StringIO() serializers.serialize( self.serializer_name, Article.objects.all(), progress_output=fake_stdout, object_count=Article.objects.count(), ) self.assertTrue( fake_stdout.getvalue().endswith( "[" + "." * ProgressBar.progress_width + "]\n" ) ) def test_serialize_superfluous_queries(self): """Ensure no superfluous queries are made when serializing ForeignKeys #17602 """ ac = Actor(name="Actor name") ac.save() mv = Movie(title="Movie title", actor_id=ac.pk) mv.save() with self.assertNumQueries(0): serializers.serialize(self.serializer_name, [mv]) def test_serialize_prefetch_related_m2m(self): # One query for the Article table and one for each prefetched m2m # field. with self.assertNumQueries(3): serializers.serialize( self.serializer_name, Article.objects.prefetch_related("categories", "meta_data"), ) # One query for the Article table, and two m2m queries for each # article. with self.assertNumQueries(5): serializers.serialize(self.serializer_name, Article.objects.all()) def test_serialize_with_null_pk(self): """ Serialized data with no primary key results in a model instance with no id """ category = Category(name="Reference") serial_str = serializers.serialize(self.serializer_name, [category]) pk_value = self._get_pk_values(serial_str)[0] self.assertFalse(pk_value) cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[ 0 ].object self.assertIsNone(cat_obj.id) def test_float_serialization(self): """Float values serialize and deserialize intact""" sc = Score(score=3.4) sc.save() serial_str = serializers.serialize(self.serializer_name, [sc]) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1)) def test_deferred_field_serialization(self): author = Author.objects.create(name="Victor Hugo") author = Author.objects.defer("name").get(pk=author.pk) serial_str = serializers.serialize(self.serializer_name, [author]) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertIsInstance(deserial_objs[0].object, Author) def test_custom_field_serialization(self): """Custom fields serialize and deserialize intact""" team_str = "Spartak Moskva" player = Player() player.name = "Soslan Djanaev" player.rank = 1 player.team = Team(team_str) player.save() serial_str = serializers.serialize(self.serializer_name, Player.objects.all()) team = self._get_field_values(serial_str, "team") self.assertTrue(team) self.assertEqual(team[0], team_str) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual( deserial_objs[0].object.team.to_string(), player.team.to_string() ) def test_pre_1000ad_date(self): """Year values before 1000AD are properly formatted""" # Regression for #12524 -- dates before 1000AD get prefixed # 0's on the year a = Article.objects.create( author=self.jane, headline="Nobody remembers the early years", pub_date=datetime(1, 2, 3, 4, 5, 6), ) serial_str = serializers.serialize(self.serializer_name, [a]) date_values = self._get_field_values(serial_str, "pub_date") self.assertEqual(date_values[0].replace("T", " "), "0001-02-03 04:05:06") def test_pkless_serialized_strings(self): """ Serialized strings without PKs can be turned into models """ deserial_objs = list( serializers.deserialize(self.serializer_name, self.pkless_str) ) for obj in deserial_objs: self.assertFalse(obj.object.id) obj.save() self.assertEqual(Category.objects.count(), 5) def test_deterministic_mapping_ordering(self): """Mapping such as fields should be deterministically ordered. (#24558)""" output = serializers.serialize(self.serializer_name, [self.a1], indent=2) categories = self.a1.categories.values_list("pk", flat=True) self.assertEqual( output, self.mapping_ordering_str % { "article_pk": self.a1.pk, "author_pk": self.a1.author_id, "first_category_pk": categories[0], "second_category_pk": categories[1], }, ) def test_deserialize_force_insert(self): """Deserialized content can be saved with force_insert as a parameter.""" serial_str = serializers.serialize(self.serializer_name, [self.a1]) deserial_obj = list(serializers.deserialize(self.serializer_name, serial_str))[ 0 ] with mock.patch("django.db.models.Model") as mock_model: deserial_obj.save(force_insert=False) mock_model.save_base.assert_called_with( deserial_obj.object, raw=True, using=None, force_insert=False ) @skipUnlessDBFeature("can_defer_constraint_checks") def test_serialize_proxy_model(self): BaseModel.objects.create(parent_data=1) base_objects = BaseModel.objects.all() proxy_objects = ProxyBaseModel.objects.all() proxy_proxy_objects = ProxyProxyBaseModel.objects.all() base_data = serializers.serialize("json", base_objects) proxy_data = serializers.serialize("json", proxy_objects) proxy_proxy_data = serializers.serialize("json", proxy_proxy_objects) self.assertEqual(base_data, proxy_data.replace("proxy", "")) self.assertEqual(base_data, proxy_proxy_data.replace("proxy", "")) def test_serialize_inherited_fields(self): child_1 = Child.objects.create(parent_data="a", child_data="b") child_2 = Child.objects.create(parent_data="c", child_data="d") child_1.parent_m2m.add(child_2) child_data = serializers.serialize(self.serializer_name, [child_1, child_2]) self.assertEqual(self._get_field_values(child_data, "parent_m2m"), []) self.assertEqual(self._get_field_values(child_data, "parent_data"), []) def test_serialize_only_pk(self): with self.assertNumQueries(5) as ctx: serializers.serialize( self.serializer_name, Article.objects.all(), use_natural_foreign_keys=False, ) categories_sql = ctx[1]["sql"] self.assertNotIn(connection.ops.quote_name("meta_data_id"), categories_sql) meta_data_sql = ctx[2]["sql"] self.assertNotIn(connection.ops.quote_name("kind"), meta_data_sql) def test_serialize_no_only_pk_with_natural_keys(self): with self.assertNumQueries(5) as ctx: serializers.serialize( self.serializer_name, Article.objects.all(), use_natural_foreign_keys=True, ) categories_sql = ctx[1]["sql"] self.assertNotIn(connection.ops.quote_name("meta_data_id"), categories_sql) # CategoryMetaData has natural_key(). meta_data_sql = ctx[2]["sql"] self.assertIn(connection.ops.quote_name("kind"), meta_data_sql) class SerializerAPITests(SimpleTestCase): def test_stream_class(self): class File: def __init__(self): self.lines = [] def write(self, line): self.lines.append(line) def getvalue(self): return "".join(self.lines) class Serializer(serializers.json.Serializer): stream_class = File serializer = Serializer() data = serializer.serialize([Score(id=1, score=3.4)]) self.assertIs(serializer.stream_class, File) self.assertIsInstance(serializer.stream, File) self.assertEqual( data, '[{"model": "serializers.score", "pk": 1, "fields": {"score": 3.4}}]' ) class SerializersTransactionTestBase: available_apps = ["serializers"] @skipUnlessDBFeature("supports_forward_references") def test_forward_refs(self): """ Objects ids can be referenced before they are defined in the serialization data. """ # The deserialization process needs to run in a transaction in order # to test forward reference handling. with transaction.atomic(): objs = serializers.deserialize(self.serializer_name, self.fwd_ref_str) with connection.constraint_checks_disabled(): for obj in objs: obj.save() for model_cls in (Category, Author, Article): self.assertEqual(model_cls.objects.count(), 1) art_obj = Article.objects.all()[0] self.assertEqual(art_obj.categories.count(), 1) self.assertEqual(art_obj.author.name, "Agnes") def register_tests(test_class, method_name, test_func, exclude=()): """ Dynamically create serializer tests to ensure that all registered serializers are automatically tested. """ for format_ in serializers.get_serializer_formats(): if format_ == "geojson" or format_ in exclude: continue decorated_func = skipIf( isinstance(serializers.get_serializer(format_), serializers.BadSerializer), "The Python library for the %s serializer is not installed." % format_, )(test_func) setattr( test_class, method_name % format_, partialmethod(decorated_func, format_) )
c38ddb0e0d287ad4102d908f2d30f1692aa5aa7e8db0025b0bfcbe35ebfcccac
""" Tests for django test runner """ import collections.abc import multiprocessing import os import sys import unittest from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django import db from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.core.management.base import SystemCheckError from django.test import SimpleTestCase, TransactionTestCase, skipUnlessDBFeature from django.test.runner import ( DiscoverRunner, Shuffler, _init_worker, reorder_test_bin, reorder_tests, shuffle_tests, ) from django.test.testcases import connections_support_transactions from django.test.utils import ( captured_stderr, dependency_ordered, get_unique_databases_and_mirrors, iter_test_cases, ) from .models import B, Person, Through class MySuite: def __init__(self): self.tests = [] def addTest(self, test): self.tests.append(test) def __iter__(self): yield from self.tests class TestSuiteTests(SimpleTestCase): def build_test_suite(self, test_classes, suite=None, suite_class=None): if suite_class is None: suite_class = unittest.TestSuite if suite is None: suite = suite_class() loader = unittest.defaultTestLoader for test_class in test_classes: tests = loader.loadTestsFromTestCase(test_class) subsuite = suite_class() # Only use addTest() to simplify testing a custom TestSuite. for test in tests: subsuite.addTest(test) suite.addTest(subsuite) return suite def make_test_suite(self, suite=None, suite_class=None): class Tests1(unittest.TestCase): def test1(self): pass def test2(self): pass class Tests2(unittest.TestCase): def test1(self): pass def test2(self): pass return self.build_test_suite( (Tests1, Tests2), suite=suite, suite_class=suite_class, ) def assertTestNames(self, tests, expected): # Each test.id() has a form like the following: # "test_runner.tests.IterTestCasesTests.test_iter_test_cases.<locals>.Tests1.test1". # It suffices to check only the last two parts. names = [".".join(test.id().split(".")[-2:]) for test in tests] self.assertEqual(names, expected) def test_iter_test_cases_basic(self): suite = self.make_test_suite() tests = iter_test_cases(suite) self.assertTestNames( tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test1", "Tests2.test2", ], ) def test_iter_test_cases_string_input(self): msg = ( "Test 'a' must be a test case or test suite not string (was found " "in 'abc')." ) with self.assertRaisesMessage(TypeError, msg): list(iter_test_cases("abc")) def test_iter_test_cases_iterable_of_tests(self): class Tests(unittest.TestCase): def test1(self): pass def test2(self): pass tests = list(unittest.defaultTestLoader.loadTestsFromTestCase(Tests)) actual_tests = iter_test_cases(tests) self.assertTestNames( actual_tests, expected=[ "Tests.test1", "Tests.test2", ], ) def test_iter_test_cases_custom_test_suite_class(self): suite = self.make_test_suite(suite_class=MySuite) tests = iter_test_cases(suite) self.assertTestNames( tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test1", "Tests2.test2", ], ) def test_iter_test_cases_mixed_test_suite_classes(self): suite = self.make_test_suite(suite=MySuite()) child_suite = list(suite)[0] self.assertNotIsInstance(child_suite, MySuite) tests = list(iter_test_cases(suite)) self.assertEqual(len(tests), 4) self.assertNotIsInstance(tests[0], unittest.TestSuite) def make_tests(self): """Return an iterable of tests.""" suite = self.make_test_suite() return list(iter_test_cases(suite)) def test_shuffle_tests(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) shuffled_tests = shuffle_tests(tests, shuffler) self.assertIsInstance(shuffled_tests, collections.abc.Iterator) self.assertTestNames( shuffled_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_test_bin_no_arguments(self): tests = self.make_tests() reordered_tests = reorder_test_bin(tests) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test1", "Tests2.test2", ], ) def test_reorder_test_bin_reverse(self): tests = self.make_tests() reordered_tests = reorder_test_bin(tests, reverse=True) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests2.test2", "Tests2.test1", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_test_bin_random(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) reordered_tests = reorder_test_bin(tests, shuffler=shuffler) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_test_bin_random_and_reverse(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) reordered_tests = reorder_test_bin(tests, shuffler=shuffler, reverse=True) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test2", "Tests2.test1", ], ) def test_reorder_tests_same_type_consecutive(self): """Tests of the same type are made consecutive.""" tests = self.make_tests() # Move the last item to the front. tests.insert(0, tests.pop()) self.assertTestNames( tests, expected=[ "Tests2.test2", "Tests1.test1", "Tests1.test2", "Tests2.test1", ], ) reordered_tests = reorder_tests(tests, classes=[]) self.assertTestNames( reordered_tests, expected=[ "Tests2.test2", "Tests2.test1", "Tests1.test1", "Tests1.test2", ], ) def test_reorder_tests_random(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) reordered_tests = reorder_tests(tests, classes=[], shuffler=shuffler) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_tests_random_mixed_classes(self): tests = self.make_tests() # Move the last item to the front. tests.insert(0, tests.pop()) shuffler = Shuffler(seed=9) self.assertTestNames( tests, expected=[ "Tests2.test2", "Tests1.test1", "Tests1.test2", "Tests2.test1", ], ) reordered_tests = reorder_tests(tests, classes=[], shuffler=shuffler) self.assertTestNames( reordered_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_tests_reverse_with_duplicates(self): class Tests1(unittest.TestCase): def test1(self): pass class Tests2(unittest.TestCase): def test2(self): pass def test3(self): pass suite = self.build_test_suite((Tests1, Tests2)) subsuite = list(suite)[0] suite.addTest(subsuite) tests = list(iter_test_cases(suite)) self.assertTestNames( tests, expected=[ "Tests1.test1", "Tests2.test2", "Tests2.test3", "Tests1.test1", ], ) reordered_tests = reorder_tests(tests, classes=[]) self.assertTestNames( reordered_tests, expected=[ "Tests1.test1", "Tests2.test2", "Tests2.test3", ], ) reordered_tests = reorder_tests(tests, classes=[], reverse=True) self.assertTestNames( reordered_tests, expected=[ "Tests2.test3", "Tests2.test2", "Tests1.test1", ], ) class DependencyOrderingTests(unittest.TestCase): def test_simple_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ("s3", ("s3_db", ["charlie"])), ] dependencies = { "alpha": ["charlie"], "bravo": ["charlie"], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, value in ordered] self.assertIn("s1", ordered_sigs) self.assertIn("s2", ordered_sigs) self.assertIn("s3", ordered_sigs) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2")) def test_chained_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ("s3", ("s3_db", ["charlie"])), ] dependencies = { "alpha": ["bravo"], "bravo": ["charlie"], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, value in ordered] self.assertIn("s1", ordered_sigs) self.assertIn("s2", ordered_sigs) self.assertIn("s3", ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index("s2"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2")) # Implied dependencies self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1")) def test_multiple_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ("s3", ("s3_db", ["charlie"])), ("s4", ("s4_db", ["delta"])), ] dependencies = { "alpha": ["bravo", "delta"], "bravo": ["charlie"], "delta": ["charlie"], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, aliases in ordered] self.assertIn("s1", ordered_sigs) self.assertIn("s2", ordered_sigs) self.assertIn("s3", ordered_sigs) self.assertIn("s4", ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index("s2"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s4"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s4")) # Implicit dependencies self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1")) def test_circular_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ] dependencies = { "bravo": ["alpha"], "alpha": ["bravo"], } with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) def test_own_alias_dependency(self): raw = [("s1", ("s1_db", ["alpha", "bravo"]))] dependencies = {"alpha": ["bravo"]} with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) # reordering aliases shouldn't matter raw = [("s1", ("s1_db", ["bravo", "alpha"]))] with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) class MockTestRunner: def __init__(self, *args, **kwargs): if parallel := kwargs.get("parallel"): sys.stderr.write(f"parallel={parallel}") MockTestRunner.run_tests = mock.Mock(return_value=[]) class ManageCommandTests(unittest.TestCase): def test_custom_test_runner(self): call_command("test", "sites", testrunner="test_runner.tests.MockTestRunner") MockTestRunner.run_tests.assert_called_with(("sites",)) def test_bad_test_runner(self): with self.assertRaises(AttributeError): call_command("test", "sites", testrunner="test_runner.NonexistentRunner") def test_time_recorded(self): with captured_stderr() as stderr: call_command( "test", "--timing", "sites", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("Total run took", stderr.getvalue()) # Isolate from the real environment. @mock.patch.dict(os.environ, {}, clear=True) @mock.patch.object(multiprocessing, "cpu_count", return_value=12) class ManageCommandParallelTests(SimpleTestCase): def test_parallel_default(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", "--parallel", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=12", stderr.getvalue()) def test_parallel_auto(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", "--parallel=auto", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=12", stderr.getvalue()) def test_no_parallel(self, *mocked_objects): with captured_stderr() as stderr: call_command("test", testrunner="test_runner.tests.MockTestRunner") # Parallel is disabled by default. self.assertEqual(stderr.getvalue(), "") @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") def test_parallel_spawn(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", "--parallel=auto", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=1", stderr.getvalue()) @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") def test_no_parallel_spawn(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", testrunner="test_runner.tests.MockTestRunner", ) self.assertEqual(stderr.getvalue(), "") @mock.patch.dict(os.environ, {"DJANGO_TEST_PROCESSES": "7"}) def test_no_parallel_django_test_processes_env(self, *mocked_objects): with captured_stderr() as stderr: call_command("test", testrunner="test_runner.tests.MockTestRunner") self.assertEqual(stderr.getvalue(), "") @mock.patch.dict(os.environ, {"DJANGO_TEST_PROCESSES": "invalid"}) def test_django_test_processes_env_non_int(self, *mocked_objects): with self.assertRaises(ValueError): call_command( "test", "--parallel", testrunner="test_runner.tests.MockTestRunner", ) @mock.patch.dict(os.environ, {"DJANGO_TEST_PROCESSES": "7"}) def test_django_test_processes_parallel_default(self, *mocked_objects): for parallel in ["--parallel", "--parallel=auto"]: with self.subTest(parallel=parallel): with captured_stderr() as stderr: call_command( "test", parallel, testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=7", stderr.getvalue()) class CustomTestRunnerOptionsSettingsTests(AdminScriptTestCase): """ Custom runners can add command line arguments. The runner is specified through a settings file. """ def setUp(self): super().setUp() settings = { "TEST_RUNNER": "'test_runner.runner.CustomOptionsTestRunner'", } self.write_settings("settings.py", sdict=settings) def test_default_options(self): args = ["test", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "1:2:3") def test_default_and_given_options(self): args = ["test", "--settings=test_project.settings", "--option_b=foo"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "1:foo:3") def test_option_name_and_value_separated(self): args = ["test", "--settings=test_project.settings", "--option_b", "foo"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "1:foo:3") def test_all_options_given(self): args = [ "test", "--settings=test_project.settings", "--option_a=bar", "--option_b=foo", "--option_c=31337", ] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "bar:foo:31337") class CustomTestRunnerOptionsCmdlineTests(AdminScriptTestCase): """ Custom runners can add command line arguments when the runner is specified using --testrunner. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_testrunner_option(self): args = [ "test", "--testrunner", "test_runner.runner.CustomOptionsTestRunner", "--option_a=bar", "--option_b=foo", "--option_c=31337", ] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "bar:foo:31337") def test_testrunner_equals(self): args = [ "test", "--testrunner=test_runner.runner.CustomOptionsTestRunner", "--option_a=bar", "--option_b=foo", "--option_c=31337", ] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "bar:foo:31337") def test_no_testrunner(self): args = ["test", "--testrunner"] out, err = self.run_django_admin(args, "test_project.settings") self.assertIn("usage", err) self.assertNotIn("Traceback", err) self.assertNoOutput(out) class NoInitializeSuiteTestRunnerTests(SimpleTestCase): @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") @mock.patch( "django.test.runner.ParallelTestSuite.initialize_suite", side_effect=Exception("initialize_suite() is called."), ) def test_no_initialize_suite_test_runner(self, *mocked_objects): """ The test suite's initialize_suite() method must always be called when using spawn. It cannot rely on a test runner implementation. """ class NoInitializeSuiteTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): return def setup_databases(self, **kwargs): return def run_checks(self, databases): return def teardown_databases(self, old_config, **kwargs): return def teardown_test_environment(self, **kwargs): return def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) return runner.run(suite) with self.assertRaisesMessage(Exception, "initialize_suite() is called."): runner = NoInitializeSuiteTestRunner( verbosity=0, interactive=False, parallel=2 ) runner.run_tests( [ "test_runner_apps.sample.tests_sample.TestDjangoTestCase", "test_runner_apps.simple.tests", ] ) class TestRunnerInitializerTests(SimpleTestCase): # Raise an exception to don't actually run tests. @mock.patch.object( multiprocessing, "Pool", side_effect=Exception("multiprocessing.Pool()") ) def test_no_initialize_suite_test_runner(self, mocked_pool): class StubTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): return def setup_databases(self, **kwargs): return def run_checks(self, databases): return def teardown_databases(self, old_config, **kwargs): return def teardown_test_environment(self, **kwargs): return def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) return runner.run(suite) runner = StubTestRunner( verbosity=0, interactive=False, parallel=2, debug_mode=True ) with self.assertRaisesMessage(Exception, "multiprocessing.Pool()"): runner.run_tests( [ "test_runner_apps.sample.tests_sample.TestDjangoTestCase", "test_runner_apps.simple.tests", ] ) # Initializer must be a function. self.assertIs(mocked_pool.call_args.kwargs["initializer"], _init_worker) initargs = mocked_pool.call_args.kwargs["initargs"] self.assertEqual(len(initargs), 6) self.assertEqual(initargs[5], True) # debug_mode class Ticket17477RegressionTests(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings("settings.py") def test_ticket_17477(self): """'manage.py help test' works after r16352.""" args = ["help", "test"] out, err = self.run_manage(args) self.assertNoOutput(err) class SQLiteInMemoryTestDbs(TransactionTestCase): available_apps = ["test_runner"] databases = {"default", "other"} @unittest.skipUnless( all(db.connections[conn].vendor == "sqlite" for conn in db.connections), "This is an sqlite-specific issue", ) def test_transaction_support(self): # Assert connections mocking is appropriately applied by preventing # any attempts at calling create_test_db on the global connection # objects. for connection in db.connections.all(): create_test_db = mock.patch.object( connection.creation, "create_test_db", side_effect=AssertionError( "Global connection object shouldn't be manipulated." ), ) create_test_db.start() self.addCleanup(create_test_db.stop) for option_key, option_value in ( ("NAME", ":memory:"), ("TEST", {"NAME": ":memory:"}), ): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.sqlite3", option_key: option_value, }, "other": { "ENGINE": "django.db.backends.sqlite3", option_key: option_value, }, } ) with mock.patch("django.test.utils.connections", new=tested_connections): other = tested_connections["other"] DiscoverRunner(verbosity=0).setup_databases() msg = ( "DATABASES setting '%s' option set to sqlite3's ':memory:' value " "shouldn't interfere with transaction support detection." % option_key ) # Transaction support is properly initialized for the 'other' DB. self.assertTrue(other.features.supports_transactions, msg) # And all the DBs report that they support transactions. self.assertTrue(connections_support_transactions(), msg) class DummyBackendTest(unittest.TestCase): def test_setup_databases(self): """ setup_databases() doesn't fail with dummy database backend. """ tested_connections = db.ConnectionHandler({}) with mock.patch("django.test.utils.connections", new=tested_connections): runner_instance = DiscoverRunner(verbosity=0) old_config = runner_instance.setup_databases() runner_instance.teardown_databases(old_config) class AliasedDefaultTestSetupTest(unittest.TestCase): def test_setup_aliased_default_database(self): """ setup_databases() doesn't fail when 'default' is aliased """ tested_connections = db.ConnectionHandler( {"default": {"NAME": "dummy"}, "aliased": {"NAME": "dummy"}} ) with mock.patch("django.test.utils.connections", new=tested_connections): runner_instance = DiscoverRunner(verbosity=0) old_config = runner_instance.setup_databases() runner_instance.teardown_databases(old_config) class SetupDatabasesTests(unittest.TestCase): def setUp(self): self.runner_instance = DiscoverRunner(verbosity=0) def test_setup_aliased_databases(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, "other": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, } ) with mock.patch( "django.db.backends.dummy.base.DatabaseWrapper.creation_class" ) as mocked_db_creation: with mock.patch("django.test.utils.connections", new=tested_connections): old_config = self.runner_instance.setup_databases() self.runner_instance.teardown_databases(old_config) mocked_db_creation.return_value.destroy_test_db.assert_called_once_with( "dbname", 0, False ) def test_setup_test_database_aliases(self): """ The default database must be the first because data migrations use the default alias by default. """ tested_connections = db.ConnectionHandler( { "other": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, "default": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, } ) with mock.patch("django.test.utils.connections", new=tested_connections): test_databases, _ = get_unique_databases_and_mirrors() self.assertEqual( test_databases, { ("", "", "django.db.backends.dummy", "test_dbname"): ( "dbname", ["default", "other"], ), }, ) def test_destroy_test_db_restores_db_name(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": settings.DATABASES[db.DEFAULT_DB_ALIAS]["ENGINE"], "NAME": "xxx_test_database", }, } ) # Using the real current name as old_name to not mess with the test suite. old_name = settings.DATABASES[db.DEFAULT_DB_ALIAS]["NAME"] with mock.patch("django.db.connections", new=tested_connections): tested_connections["default"].creation.destroy_test_db( old_name, verbosity=0, keepdb=True ) self.assertEqual( tested_connections["default"].settings_dict["NAME"], old_name ) def test_serialization(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.dummy", }, } ) with mock.patch( "django.db.backends.dummy.base.DatabaseWrapper.creation_class" ) as mocked_db_creation: with mock.patch("django.test.utils.connections", new=tested_connections): self.runner_instance.setup_databases() mocked_db_creation.return_value.create_test_db.assert_called_once_with( verbosity=0, autoclobber=False, serialize=True, keepdb=False ) @skipUnlessDBFeature("supports_sequence_reset") class AutoIncrementResetTest(TransactionTestCase): """ Creating the same models in different test methods receive the same PK values since the sequences are reset before each test method. """ available_apps = ["test_runner"] reset_sequences = True def _test(self): # Regular model p = Person.objects.create(first_name="Jack", last_name="Smith") self.assertEqual(p.pk, 1) # Auto-created many-to-many through model p.friends.add(Person.objects.create(first_name="Jacky", last_name="Smith")) self.assertEqual(p.friends.through.objects.first().pk, 1) # Many-to-many through model b = B.objects.create() t = Through.objects.create(person=p, b=b) self.assertEqual(t.pk, 1) def test_autoincrement_reset1(self): self._test() def test_autoincrement_reset2(self): self._test() class EmptyDefaultDatabaseTest(unittest.TestCase): def test_empty_default_database(self): """ An empty default database in settings does not raise an ImproperlyConfigured error when running a unit test that does not use a database. """ tested_connections = db.ConnectionHandler({"default": {}}) with mock.patch("django.db.connections", new=tested_connections): connection = tested_connections[db.utils.DEFAULT_DB_ALIAS] self.assertEqual( connection.settings_dict["ENGINE"], "django.db.backends.dummy" ) connections_support_transactions() class RunTestsExceptionHandlingTests(unittest.TestCase): def test_run_checks_raises(self): """ Teardown functions are run when run_checks() raises SystemCheckError. """ with mock.patch( "django.test.runner.DiscoverRunner.setup_test_environment" ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( "django.test.runner.DiscoverRunner.build_suite" ), mock.patch( "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError ), mock.patch( "django.test.runner.DiscoverRunner.teardown_databases" ) as teardown_databases, mock.patch( "django.test.runner.DiscoverRunner.teardown_test_environment" ) as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( ["test_runner_apps.sample.tests_sample.TestDjangoTestCase"] ) self.assertTrue(teardown_databases.called) self.assertTrue(teardown_test_environment.called) def test_run_checks_raises_and_teardown_raises(self): """ SystemCheckError is surfaced when run_checks() raises SystemCheckError and teardown databases() raises ValueError. """ with mock.patch( "django.test.runner.DiscoverRunner.setup_test_environment" ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( "django.test.runner.DiscoverRunner.build_suite" ), mock.patch( "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError ), mock.patch( "django.test.runner.DiscoverRunner.teardown_databases", side_effect=ValueError, ) as teardown_databases, mock.patch( "django.test.runner.DiscoverRunner.teardown_test_environment" ) as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( ["test_runner_apps.sample.tests_sample.TestDjangoTestCase"] ) self.assertTrue(teardown_databases.called) self.assertFalse(teardown_test_environment.called) def test_run_checks_passes_and_teardown_raises(self): """ Exceptions on teardown are surfaced if no exceptions happen during run_checks(). """ with mock.patch( "django.test.runner.DiscoverRunner.setup_test_environment" ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( "django.test.runner.DiscoverRunner.build_suite" ), mock.patch( "django.test.runner.DiscoverRunner.run_checks" ), mock.patch( "django.test.runner.DiscoverRunner.teardown_databases", side_effect=ValueError, ) as teardown_databases, mock.patch( "django.test.runner.DiscoverRunner.teardown_test_environment" ) as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(ValueError): # Suppress the output when running TestDjangoTestCase. with mock.patch("sys.stderr"): runner.run_tests( ["test_runner_apps.sample.tests_sample.TestDjangoTestCase"] ) self.assertTrue(teardown_databases.called) self.assertFalse(teardown_test_environment.called)
5d70413164bc453e235e1bfaab533fd06135da74c7a2dbc6bc64ebc34a9a7a5e
""" A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import re import shutil import socket import stat import subprocess import sys import tempfile import unittest from io import StringIO from unittest import mock from django import conf, get_version from django.conf import settings from django.core.management import ( BaseCommand, CommandError, call_command, color, execute_from_command_line, ) from django.core.management.commands.loaddata import Command as LoaddataCommand from django.core.management.commands.runserver import Command as RunserverCommand from django.core.management.commands.testserver import Command as TestserverCommand from django.db import ConnectionHandler, connection from django.db.migrations.recorder import MigrationRecorder from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.urls import path from django.views.static import serve from . import urls custom_templates_dir = os.path.join(os.path.dirname(__file__), "custom_templates") SYSTEM_CHECK_MSG = "System check identified no issues" HAS_BLACK = shutil.which("black") class AdminScriptTestCase(SimpleTestCase): def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, "test_project")) os.mkdir(self.test_dir) def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: settings_dir = os.path.join(self.test_dir, filename) os.mkdir(settings_dir) settings_file_path = os.path.join(settings_dir, "__init__.py") else: settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, "w") as settings_file: settings_file.write( "# Settings file automatically generated by admin_scripts test case\n" ) if extra: settings_file.write("%s\n" % extra) exports = [ "DATABASES", "DEFAULT_AUTO_FIELD", "ROOT_URLCONF", "SECRET_KEY", "USE_TZ", ] for s in exports: if hasattr(settings, s): o = getattr(settings, s) if not isinstance(o, (dict, tuple, list)): o = "'%s'" % o settings_file.write("%s = %s\n" % (s, o)) if apps is None: apps = [ "django.contrib.auth", "django.contrib.contenttypes", "admin_scripts", ] settings_file.write("INSTALLED_APPS = %s\n" % apps) if sdict: for k, v in sdict.items(): settings_file.write("%s = %s\n" % (k, v)) def _ext_backend_paths(self): """ Returns the paths for any external backend packages. """ paths = [] for backend in settings.DATABASES.values(): package = backend["ENGINE"].split(".")[0] if package != "django": backend_pkg = __import__(package) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) return paths def run_test(self, args, settings_file=None, apps=None, umask=-1): base_dir = os.path.dirname(self.test_dir) # The base dir for Django's tests is one level up. tests_dir = os.path.dirname(os.path.dirname(__file__)) # The base dir for Django is one level above the test dir. We don't use # `import django` to figure that out, so we don't pick up a Django # from site-packages or similar. django_dir = os.path.dirname(tests_dir) ext_backend_base_dirs = self._ext_backend_paths() # Define a temporary environment for the subprocess test_environ = os.environ.copy() # Set the test environment if settings_file: test_environ["DJANGO_SETTINGS_MODULE"] = settings_file elif "DJANGO_SETTINGS_MODULE" in test_environ: del test_environ["DJANGO_SETTINGS_MODULE"] python_path = [base_dir, django_dir, tests_dir] python_path.extend(ext_backend_base_dirs) test_environ["PYTHONPATH"] = os.pathsep.join(python_path) test_environ["PYTHONWARNINGS"] = "" p = subprocess.run( [sys.executable, *args], capture_output=True, cwd=self.test_dir, env=test_environ, text=True, umask=umask, ) return p.stdout, p.stderr def run_django_admin(self, args, settings_file=None, umask=-1): return self.run_test(["-m", "django", *args], settings_file, umask=umask) def run_manage(self, args, settings_file=None, manage_py=None): template_manage_py = ( os.path.join(os.path.dirname(__file__), manage_py) if manage_py else os.path.join( os.path.dirname(conf.__file__), "project_template", "manage.py-tpl" ) ) test_manage_py = os.path.join(self.test_dir, "manage.py") shutil.copyfile(template_manage_py, test_manage_py) with open(test_manage_py) as fp: manage_py_contents = fp.read() manage_py_contents = manage_py_contents.replace( "{{ project_name }}", "test_project" ) with open(test_manage_py, "w") as fp: fp.write(manage_py_contents) return self.run_test(["./manage.py", *args], settings_file) def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" self.assertEqual( len(stream), 0, "Stream should be empty: actually contains '%s'" % stream ) def assertOutput(self, stream, msg, regex=False): "Utility assertion: assert that the given message exists in the output" if regex: self.assertIsNotNone( re.search(msg, stream), "'%s' does not match actual output text '%s'" % (msg, stream), ) else: self.assertIn( msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream), ) def assertNotInOutput(self, stream, msg): "Utility assertion: assert that the given message doesn't exist in the output" self.assertNotIn( msg, stream, "'%s' matches actual output text '%s'" % (msg, stream) ) ########################################################################## # DJANGO ADMIN TESTS # This first series of test classes checks the environment processing # of the django-admin. ########################################################################## class DjangoAdminNoSettings(AdminScriptTestCase): "A series of tests for django-admin when there is no settings.py file." def test_builtin_command(self): """ no settings: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): """ no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_commands_with_invalid_settings(self): """ Commands that don't require settings succeed if the settings file doesn't exist. """ args = ["startproject"] out, err = self.run_django_admin(args, settings_file="bad_settings") self.assertNoOutput(out) self.assertOutput(err, "You must provide a project name", regex=True) class DjangoAdminDefaultSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_builtin_command(self): """ default: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ default: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ default: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ default: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ default: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ default: django-admin can't execute user commands if it isn't provided settings. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ default: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ default: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings( "settings.py", [ "django.contrib.auth", "django.contrib.contenttypes", "admin_scripts", "admin_scripts.complex_app", ], ) def test_builtin_command(self): """ fulldefault: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ fulldefault: django-admin builtin commands succeed if a settings file is provided. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ fulldefault: django-admin builtin commands succeed if the environment contains settings. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ fulldefault: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ fulldefault: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ fulldefault: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMinimalSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) def test_builtin_command(self): """ minimal: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ minimal: django-admin builtin commands fail if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): """ minimal: django-admin builtin commands fail if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): """ minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: django-admin can't execute user commands unless settings are provided" args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ minimal: django-admin can't execute user commands, even if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): """ minimal: django-admin can't execute user commands, even if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class DjangoAdminAlternateSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ alternate: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ alternate: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ alternate: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ alternate: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ alternate: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMultipleSettings(AdminScriptTestCase): """ A series of tests for django-admin when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ alternate: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ alternate: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ alternate: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ alternate: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ alternate: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminSettingsDirectory(AdminScriptTestCase): """ A series of tests for django-admin when the settings file is in a directory. (see #9751). """ def setUp(self): super().setUp() self.write_settings("settings", is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" args = ["startapp", "settings_test"] app_path = os.path.join(self.test_dir, "settings_test") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, "apps.py")) as f: content = f.read() self.assertIn("class SettingsTestConfig(AppConfig)", content) self.assertIn( 'name = "settings_test"' if HAS_BLACK else "name = 'settings_test'", content, ) def test_setup_environ_custom_template(self): "directory: startapp creates the correct directory with a custom template" template_path = os.path.join(custom_templates_dir, "app_template") args = ["startapp", "--template", template_path, "custom_settings_test"] app_path = os.path.join(self.test_dir, "custom_settings_test") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) self.assertTrue(os.path.exists(os.path.join(app_path, "api.py"))) def test_startapp_unicode_name(self): """startapp creates the correct directory with Unicode characters.""" args = ["startapp", "こんにちは"] app_path = os.path.join(self.test_dir, "こんにちは") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) self.assertIn('name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content) def test_builtin_command(self): """ directory: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): """ directory: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ directory: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ directory: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_builtin_with_settings(self): """ directory: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ directory: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) ########################################################################## # MANAGE.PY TESTS # This next series of test classes checks the environment processing # of the generated manage.py script ########################################################################## class ManageManuallyConfiguredSettings(AdminScriptTestCase): """Customized manage.py calling settings.configure().""" def test_non_existent_command_output(self): out, err = self.run_manage( ["invalid_command"], manage_py="configured_settings_manage.py" ) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'invalid_command'") self.assertNotInOutput(err, "No Django settings specified") class ManageNoSettings(AdminScriptTestCase): "A series of tests for manage.py when there is no settings.py file." def test_builtin_command(self): """ no settings: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput( err, r"No module named '?(test_project\.)?settings'?", regex=True ) def test_builtin_with_bad_settings(self): """ no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) class ManageDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_builtin_command(self): """ default: manage.py builtin commands succeed when default settings are appropriate. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): """ default: manage.py builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ default: manage.py builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ default: manage.py builtin commands succeed if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ default: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ default: manage.py can execute user commands when default settings are appropriate. """ args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): """ default: manage.py can execute user commands when settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ default: manage.py can execute user commands when settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings( "settings.py", ["django.contrib.auth", "django.contrib.contenttypes", "admin_scripts"], ) def test_builtin_command(self): """ fulldefault: manage.py builtin commands succeed when default settings are appropriate. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): """ fulldefault: manage.py builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ fulldefault: manage.py builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ fulldefault: manage.py can execute user commands when default settings are appropriate. """ args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): """ fulldefault: manage.py can execute user commands when settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ fulldefault: manage.py can execute user commands when settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) def test_builtin_command(self): """ minimal: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "minimal: manage.py builtin commands fail if settings are provided as argument" args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): """ minimal: manage.py builtin commands fail if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): """ minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: manage.py can't execute user commands without appropriate settings" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ minimal: manage.py can't execute user commands, even if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): """ minimal: manage.py can't execute user commands, even if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: manage.py builtin commands fail with an error when no default settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput( err, r"No module named '?(test_project\.)?settings'?", regex=True ) def test_builtin_with_settings(self): "alternate: manage.py builtin commands work with settings provided as argument" args = ["check", "--settings=alternate_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_environment(self): """ alternate: manage.py builtin commands work if settings are provided in the environment """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "alternate_settings") self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_bad_settings(self): """ alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: manage.py can't execute user commands without settings" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput( err, r"No module named '?(test_project\.)?settings'?", regex=True ) def test_custom_command_with_settings(self): """ alternate: manage.py can execute user commands if settings are provided as argument """ args = ["noargs_command", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) def test_custom_command_with_environment(self): """ alternate: manage.py can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "alternate_settings") self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) def test_custom_command_output_color(self): """ alternate: manage.py output syntax color can be deactivated with the `--no-color` option. """ args = ["noargs_command", "--no-color", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', True), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) class ManageMultipleSettings(AdminScriptTestCase): """A series of tests for manage.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_builtin_command(self): """ multiple: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): """ multiple: manage.py builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=alternate_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ multiple: manage.py can execute builtin commands if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "multiple: manage.py can't execute user commands using default settings" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ multiple: manage.py can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ multiple: manage.py can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageSettingsWithSettingsErrors(AdminScriptTestCase): """ Tests for manage.py when using the default settings.py file containing runtime errors. """ def write_settings_with_import_error(self, filename): settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, "w") as settings_file: settings_file.write( "# Settings file automatically generated by admin_scripts test case\n" ) settings_file.write( "# The next line will cause an import error:\nimport foo42bar\n" ) def test_import_error(self): """ import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided (#14130). """ self.write_settings_with_import_error("settings.py") args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named") self.assertOutput(err, "foo42bar") def test_attribute_error(self): """ manage.py builtin commands does not swallow attribute error due to bad settings (#18845). """ self.write_settings("settings.py", sdict={"BAD_VAR": "INSTALLED_APPS.crash"}) args = ["collectstatic", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'") def test_key_error(self): self.write_settings("settings.py", sdict={"BAD_VAR": 'DATABASES["blah"]'}) args = ["collectstatic", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "KeyError: 'blah'") def test_help(self): """ Test listing available commands output note when only core commands are available. """ self.write_settings( "settings.py", extra="from django.core.exceptions import ImproperlyConfigured\n" "raise ImproperlyConfigured()", ) args = ["help"] out, err = self.run_manage(args) self.assertOutput(out, "only Django core commands are listed") self.assertNoOutput(err) class ManageCheck(AdminScriptTestCase): def test_nonexistent_app(self): """check reports an error on a nonexistent app in INSTALLED_APPS.""" self.write_settings( "settings.py", apps=["admin_scriptz.broken_app"], sdict={"USE_I18N": False}, ) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "ModuleNotFoundError") self.assertOutput(err, "No module named") self.assertOutput(err, "admin_scriptz") def test_broken_app(self): """manage.py check reports an ImportError if an app's models.py raises one on import""" self.write_settings("settings.py", apps=["admin_scripts.broken_app"]) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "ImportError") def test_complex_app(self): """manage.py check does not raise an ImportError validating a complex app with nested calls to load_app""" self.write_settings( "settings.py", apps=[ "admin_scripts.complex_app", "admin_scripts.simple_app", "django.contrib.admin.apps.SimpleAdminConfig", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.messages", ], sdict={ "DEBUG": True, "MIDDLEWARE": [ "django.contrib.messages.middleware.MessageMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", ], "TEMPLATES": [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ], }, ) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, "System check identified no issues (0 silenced).\n") def test_app_with_import(self): """manage.py check does not raise errors when an app imports a base class that itself has an abstract base.""" self.write_settings( "settings.py", apps=[ "admin_scripts.app_with_import", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", ], sdict={"DEBUG": True}, ) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, "System check identified no issues (0 silenced).\n") def test_output_format(self): """All errors/warnings should be sorted by level and by message.""" self.write_settings( "settings.py", apps=[ "admin_scripts.app_raising_messages", "django.contrib.auth", "django.contrib.contenttypes", ], sdict={"DEBUG": True}, ) args = ["check"] out, err = self.run_manage(args) expected_err = ( "SystemCheckError: System check identified some issues:\n" "\n" "ERRORS:\n" "?: An error\n" "\tHINT: Error hint\n" "\n" "WARNINGS:\n" "a: Second warning\n" "obj: First warning\n" "\tHINT: Hint\n" "\n" "System check identified 3 issues (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) def test_warning_does_not_halt(self): """ When there are only warnings or less serious messages, then Django should not prevent user from launching their project, so `check` command should not raise `CommandError` exception. In this test we also test output format. """ self.write_settings( "settings.py", apps=[ "admin_scripts.app_raising_warning", "django.contrib.auth", "django.contrib.contenttypes", ], sdict={"DEBUG": True}, ) args = ["check"] out, err = self.run_manage(args) expected_err = ( "System check identified some issues:\n" # No "CommandError: " part "\n" "WARNINGS:\n" "?: A warning\n" "\n" "System check identified 1 issue (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) class ManageRunserver(SimpleTestCase): def setUp(self): def monkey_run(*args, **options): return self.output = StringIO() self.cmd = RunserverCommand(stdout=self.output) self.cmd.run = monkey_run def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False): self.assertEqual(self.cmd.addr, addr) self.assertEqual(self.cmd.port, port) self.assertEqual(self.cmd.use_ipv6, ipv6) self.assertEqual(self.cmd._raw_ipv6, raw_ipv6) def test_runserver_addrport(self): call_command(self.cmd) self.assertServerSettings("127.0.0.1", "8000") call_command(self.cmd, addrport="1.2.3.4:8000") self.assertServerSettings("1.2.3.4", "8000") call_command(self.cmd, addrport="7000") self.assertServerSettings("127.0.0.1", "7000") @mock.patch("django.core.management.commands.runserver.run") @mock.patch("django.core.management.base.BaseCommand.check_migrations") def test_zero_ip_addr(self, *mocked_objects): call_command( "runserver", addrport="0:8000", use_reloader=False, skip_checks=True, stdout=self.output, ) self.assertIn( "Starting development server at http://0.0.0.0:8000/", self.output.getvalue(), ) @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_addrport_ipv6(self): call_command(self.cmd, addrport="", use_ipv6=True) self.assertServerSettings("::1", "8000", ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="7000", use_ipv6=True) self.assertServerSettings("::1", "7000", ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000") self.assertServerSettings( "2001:0db8:1234:5678::9", "7000", ipv6=True, raw_ipv6=True ) def test_runner_hostname(self): call_command(self.cmd, addrport="localhost:8000") self.assertServerSettings("localhost", "8000") call_command(self.cmd, addrport="test.domain.local:7000") self.assertServerSettings("test.domain.local", "7000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_hostname_ipv6(self): call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True) self.assertServerSettings("test.domain.local", "7000", ipv6=True) def test_runner_custom_defaults(self): self.cmd.default_addr = "0.0.0.0" self.cmd.default_port = "5000" call_command(self.cmd) self.assertServerSettings("0.0.0.0", "5000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_custom_defaults_ipv6(self): self.cmd.default_addr_ipv6 = "::" call_command(self.cmd, use_ipv6=True) self.assertServerSettings("::", "8000", ipv6=True, raw_ipv6=True) def test_runner_ambiguous(self): # Only 4 characters, all of which could be in an ipv6 address call_command(self.cmd, addrport="beef:7654") self.assertServerSettings("beef", "7654") # Uses only characters that could be in an ipv6 address call_command(self.cmd, addrport="deadbeef:7654") self.assertServerSettings("deadbeef", "7654") def test_no_database(self): """ Ensure runserver.check_migrations doesn't choke on empty DATABASES. """ tested_connections = ConnectionHandler({}) with mock.patch( "django.core.management.base.connections", new=tested_connections ): self.cmd.check_migrations() def test_readonly_database(self): """ runserver.check_migrations() doesn't choke when a database is read-only. """ with mock.patch.object(MigrationRecorder, "has_table", return_value=False): self.cmd.check_migrations() # You have # ... self.assertIn("unapplied migration(s)", self.output.getvalue()) @mock.patch("django.core.management.commands.runserver.run") @mock.patch("django.core.management.base.BaseCommand.check_migrations") @mock.patch("django.core.management.base.BaseCommand.check") def test_skip_checks(self, mocked_check, *mocked_objects): call_command( "runserver", use_reloader=False, skip_checks=True, stdout=self.output, ) self.assertNotIn("Performing system checks...", self.output.getvalue()) mocked_check.assert_not_called() self.output.truncate(0) call_command( "runserver", use_reloader=False, skip_checks=False, stdout=self.output, ) self.assertIn("Performing system checks...", self.output.getvalue()) mocked_check.assert_called() class ManageRunserverMigrationWarning(TestCase): def setUp(self): self.stdout = StringIO() self.runserver_command = RunserverCommand(stdout=self.stdout) @override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"]) def test_migration_warning_one_app(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn("You have 1 unapplied migration(s)", output) self.assertIn("apply the migrations for app(s): app_waiting_migration.", output) @override_settings( INSTALLED_APPS=[ "admin_scripts.app_waiting_migration", "admin_scripts.another_app_waiting_migration", ], ) def test_migration_warning_multiple_apps(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn("You have 2 unapplied migration(s)", output) self.assertIn( "apply the migrations for app(s): another_app_waiting_migration, " "app_waiting_migration.", output, ) class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings( "settings.py", sdict={ "ALLOWED_HOSTS": [], "DEBUG": False, }, ) def test_empty_allowed_hosts_error(self): out, err = self.run_manage(["runserver"]) self.assertNoOutput(out) self.assertOutput( err, "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False." ) class ManageRunserverHelpOutput(AdminScriptTestCase): def test_suppressed_options(self): """runserver doesn't support --verbosity and --trackback options.""" out, err = self.run_manage(["runserver", "--help"]) self.assertNotInOutput(out, "--verbosity") self.assertNotInOutput(out, "--trackback") self.assertOutput(out, "--settings") class ManageTestserver(SimpleTestCase): @mock.patch.object(TestserverCommand, "handle", return_value="") def test_testserver_handle_params(self, mock_handle): out = StringIO() call_command("testserver", "blah.json", stdout=out) mock_handle.assert_called_with( "blah.json", stdout=out, settings=None, pythonpath=None, verbosity=1, traceback=False, addrport="", no_color=False, use_ipv6=False, skip_checks=True, interactive=True, force_color=False, ) @mock.patch("django.db.connection.creation.create_test_db", return_value="test_db") @mock.patch.object(LoaddataCommand, "handle", return_value="") @mock.patch.object(RunserverCommand, "handle", return_value="") def test_params_to_runserver( self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db ): call_command("testserver", "blah.json") mock_runserver_handle.assert_called_with( addrport="", force_color=False, insecure_serving=False, no_color=False, pythonpath=None, settings=None, shutdown_message=( "\nServer stopped.\nNote that the test database, 'test_db', " "has not been deleted. You can explore it on your own." ), skip_checks=True, traceback=False, use_ipv6=False, use_reloader=False, use_static_handler=True, use_threading=connection.features.test_db_allows_multiple_connections, verbosity=1, ) ########################################################################## # COMMAND PROCESSING TESTS # user-space commands are correctly handled - in particular, arguments to # the commands are correctly parsed and processed. ########################################################################## class ColorCommand(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): self.stdout.write("Hello, world!", self.style.ERROR) self.stderr.write("Hello, world!", self.style.ERROR) class CommandTypes(AdminScriptTestCase): "Tests for the various types of base command types that can be defined." def setUp(self): super().setUp() self.write_settings("settings.py") def test_version(self): "version is handled as a special case" args = ["version"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, get_version()) def test_version_alternative(self): "--version is equivalent to version" args1, args2 = ["version"], ["--version"] # It's possible one outputs on stderr and the other on stdout, hence the set self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2))) def test_help(self): "help is handled as a special case" args = ["help"] out, err = self.run_manage(args) self.assertOutput( out, "Type 'manage.py help <subcommand>' for help on a specific subcommand." ) self.assertOutput(out, "[django]") self.assertOutput(out, "startapp") self.assertOutput(out, "startproject") def test_help_commands(self): "help --commands shows the list of all available commands" args = ["help", "--commands"] out, err = self.run_manage(args) self.assertNotInOutput(out, "usage:") self.assertNotInOutput(out, "Options:") self.assertNotInOutput(out, "[django]") self.assertOutput(out, "startapp") self.assertOutput(out, "startproject") self.assertNotInOutput(out, "\n\n") def test_help_alternative(self): "--help is equivalent to help" args1, args2 = ["help"], ["--help"] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_help_short_altert(self): "-h is handled as a short form of --help" args1, args2 = ["--help"], ["-h"] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_specific_help(self): "--help can be used on a specific command" args = ["check", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) # Command-specific options like --tag appear before options common to # all commands like --version. tag_location = out.find("--tag") version_location = out.find("--version") self.assertNotEqual(tag_location, -1) self.assertNotEqual(version_location, -1) self.assertLess(tag_location, version_location) self.assertOutput( out, "Checks the entire Django project for potential problems." ) def test_help_default_options_with_custom_arguments(self): args = ["base_command", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) expected_options = [ "-h", "--option_a OPTION_A", "--option_b OPTION_B", "--option_c OPTION_C", "--version", "-v {0,1,2,3}", "--settings SETTINGS", "--pythonpath PYTHONPATH", "--traceback", "--no-color", "--force-color", "args ...", ] for option in expected_options: self.assertOutput(out, f"[{option}]") self.assertOutput(out, "--option_a OPTION_A, -a OPTION_A") self.assertOutput(out, "--option_b OPTION_B, -b OPTION_B") self.assertOutput(out, "--option_c OPTION_C, -c OPTION_C") self.assertOutput(out, "-v {0,1,2,3}, --verbosity {0,1,2,3}") def test_color_style(self): style = color.no_style() self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!") style = color.make_style("nocolor") self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!") style = color.make_style("dark") self.assertIn("Hello, world!", style.ERROR("Hello, world!")) self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!") # Default palette has color. style = color.make_style("") self.assertIn("Hello, world!", style.ERROR("Hello, world!")) self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!") def test_command_color(self): out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command) if color.supports_color(): self.assertIn("Hello, world!\n", out.getvalue()) self.assertIn("Hello, world!\n", err.getvalue()) self.assertNotEqual(out.getvalue(), "Hello, world!\n") self.assertNotEqual(err.getvalue(), "Hello, world!\n") else: self.assertEqual(out.getvalue(), "Hello, world!\n") self.assertEqual(err.getvalue(), "Hello, world!\n") def test_command_no_color(self): "--no-color prevent colorization of the output" out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err, no_color=True) call_command(command) self.assertEqual(out.getvalue(), "Hello, world!\n") self.assertEqual(err.getvalue(), "Hello, world!\n") out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command, no_color=True) self.assertEqual(out.getvalue(), "Hello, world!\n") self.assertEqual(err.getvalue(), "Hello, world!\n") def test_force_color_execute(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, "isatty", lambda: False): command = ColorCommand(stdout=out, stderr=err) call_command(command, force_color=True) self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") def test_force_color_command_init(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, "isatty", lambda: False): command = ColorCommand(stdout=out, stderr=err, force_color=True) call_command(command) self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") def test_no_color_force_color_mutually_exclusive_execute(self): msg = "The --no-color and --force-color options can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(), no_color=True, force_color=True) def test_no_color_force_color_mutually_exclusive_command_init(self): msg = "'no_color' and 'force_color' can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(no_color=True, force_color=True)) def test_custom_stdout(self): class Command(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): self.stdout.write("Hello, World!") out = StringIO() command = Command(stdout=out) call_command(command) self.assertEqual(out.getvalue(), "Hello, World!\n") out.truncate(0) new_out = StringIO() call_command(command, stdout=new_out) self.assertEqual(out.getvalue(), "") self.assertEqual(new_out.getvalue(), "Hello, World!\n") def test_custom_stderr(self): class Command(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): self.stderr.write("Hello, World!") err = StringIO() command = Command(stderr=err) call_command(command) self.assertEqual(err.getvalue(), "Hello, World!\n") err.truncate(0) new_err = StringIO() call_command(command, stderr=new_err) self.assertEqual(err.getvalue(), "") self.assertEqual(new_err.getvalue(), "Hello, World!\n") def test_base_command(self): "User BaseCommands can execute when a label is provided" args = ["base_command", "testlabel"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels) def test_base_command_no_label(self): "User BaseCommands can execute when no labels are provided" args = ["base_command"] expected_labels = "()" self._test_base_command(args, expected_labels) def test_base_command_multiple_label(self): "User BaseCommands can execute when no labels are provided" args = ["base_command", "testlabel", "anotherlabel"] expected_labels = "('testlabel', 'anotherlabel')" self._test_base_command(args, expected_labels) def test_base_command_with_option(self): "User BaseCommands can execute with options when a label is provided" args = ["base_command", "testlabel", "--option_a=x"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'") def test_base_command_with_options(self): "User BaseCommands can execute with multiple options when a label is provided" args = ["base_command", "testlabel", "-a", "x", "--option_b=y"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'") def test_base_command_with_wrong_option(self): "User BaseCommands outputs command usage when wrong option is specified" args = ["base_command", "--invalid"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "usage: manage.py base_command") self.assertOutput(err, "error: unrecognized arguments: --invalid") def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"): out, err = self.run_manage(args) expected_out = ( "EXECUTE:BaseCommand labels=%s, " "options=[('force_color', False), ('no_color', False), " "('option_a', %s), ('option_b', %s), ('option_c', '3'), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) % (labels, option_a, option_b) self.assertNoOutput(err) self.assertOutput(out, expected_out) def test_base_run_from_argv(self): """ Test run_from_argv properly terminates even with custom execute() (#19665) Also test proper traceback display. """ err = StringIO() command = BaseCommand(stderr=err) def raise_command_error(*args, **kwargs): raise CommandError("Custom error") command.execute = lambda args: args # This will trigger TypeError # If the Exception is not CommandError it should always # raise the original exception. with self.assertRaises(TypeError): command.run_from_argv(["", ""]) # If the Exception is CommandError and --traceback is not present # this command should raise a SystemExit and don't print any # traceback to the stderr. command.execute = raise_command_error err.truncate(0) with self.assertRaises(SystemExit): command.run_from_argv(["", ""]) err_message = err.getvalue() self.assertNotIn("Traceback", err_message) self.assertIn("CommandError", err_message) # If the Exception is CommandError and --traceback is present # this command should raise the original CommandError as if it # were not a CommandError. err.truncate(0) with self.assertRaises(CommandError): command.run_from_argv(["", "", "--traceback"]) def test_run_from_argv_non_ascii_error(self): """ Non-ASCII message of CommandError does not raise any UnicodeDecodeError in run_from_argv. """ def raise_command_error(*args, **kwargs): raise CommandError("Erreur personnalisée") command = BaseCommand(stderr=StringIO()) command.execute = raise_command_error with self.assertRaises(SystemExit): command.run_from_argv(["", ""]) def test_run_from_argv_closes_connections(self): """ A command called from the command line should close connections after being executed (#21255). """ command = BaseCommand() command.check = lambda: [] command.handle = lambda *args, **kwargs: args with mock.patch("django.core.management.base.connections") as mock_connections: command.run_from_argv(["", ""]) # Test connections have been closed self.assertTrue(mock_connections.close_all.called) def test_noargs(self): "NoArg Commands can be executed" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]", ) def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" args = ["noargs_command", "argument"] out, err = self.run_manage(args) self.assertOutput(err, "error: unrecognized arguments: argument") def test_app_command(self): "User AppCommands can execute when a single app name is provided" args = ["app_command", "auth"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]", ) def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" args = ["app_command"] out, err = self.run_manage(args) self.assertOutput(err, "error: Enter at least one application label.") def test_app_command_multiple_apps(self): "User AppCommands raise an error when multiple app names are provided" args = ["app_command", "auth", "contenttypes"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]", ) self.assertOutput( out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=" ) self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]", ) def test_app_command_invalid_app_label(self): "User AppCommands can execute when a single app name is provided" args = ["app_command", "NOT_AN_APP"] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_app_command_some_invalid_app_labels(self): "User AppCommands can execute when some of the provided app names are invalid" args = ["app_command", "auth", "NOT_AN_APP"] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_label_command(self): "User LabelCommands can execute when a label is provided" args = ["label_command", "testlabel"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), ('settings', " "None), ('traceback', False), ('verbosity', 1)]", ) def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" args = ["label_command"] out, err = self.run_manage(args) self.assertOutput(err, "Enter at least one label") def test_label_command_multiple_label(self): "User LabelCommands are executed multiple times if multiple labels are provided" args = ["label_command", "testlabel", "anotherlabel"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]", ) self.assertOutput( out, "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]", ) def test_suppress_base_options_command_help(self): args = ["suppress_base_options_command", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "Test suppress base options command.") self.assertNotInOutput(out, "input file") self.assertOutput(out, "-h, --help") self.assertNotInOutput(out, "--version") self.assertNotInOutput(out, "--verbosity") self.assertNotInOutput(out, "-v {0,1,2,3}") self.assertNotInOutput(out, "--settings") self.assertNotInOutput(out, "--pythonpath") self.assertNotInOutput(out, "--traceback") self.assertNotInOutput(out, "--no-color") self.assertNotInOutput(out, "--force-color") def test_suppress_base_options_command_defaults(self): args = ["suppress_base_options_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:SuppressBaseOptionsCommand options=[('file', None), " "('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]", ) class Discovery(SimpleTestCase): def test_precedence(self): """ Apps listed first in INSTALLED_APPS have precedence. """ with self.settings( INSTALLED_APPS=[ "admin_scripts.complex_app", "admin_scripts.simple_app", "django.contrib.auth", "django.contrib.contenttypes", ] ): out = StringIO() call_command("duplicate", stdout=out) self.assertEqual(out.getvalue().strip(), "complex_app") with self.settings( INSTALLED_APPS=[ "admin_scripts.simple_app", "admin_scripts.complex_app", "django.contrib.auth", "django.contrib.contenttypes", ] ): out = StringIO() call_command("duplicate", stdout=out) self.assertEqual(out.getvalue().strip(), "simple_app") class ArgumentOrder(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. django-admin command arguments are parsed in 2 parts; the core arguments (--settings, --traceback and --pythonpath) are parsed using a basic parser, ignoring any unknown options. Then the full settings are passed to the command parser, which extracts commands of interest to the individual command. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_setting_then_option(self): """Options passed after settings are correctly handled.""" args = [ "base_command", "testlabel", "--settings=alternate_settings", "--option_a=x", ] self._test(args) def test_setting_then_short_option(self): """Short options passed after settings are correctly handled.""" args = ["base_command", "testlabel", "--settings=alternate_settings", "-a", "x"] self._test(args) def test_option_then_setting(self): """Options passed before settings are correctly handled.""" args = [ "base_command", "testlabel", "--option_a=x", "--settings=alternate_settings", ] self._test(args) def test_short_option_then_setting(self): """Short options passed before settings are correctly handled.""" args = ["base_command", "testlabel", "-a", "x", "--settings=alternate_settings"] self._test(args) def test_option_then_setting_then_option(self): """Options are correctly handled when they are passed before and after a setting.""" args = [ "base_command", "testlabel", "--option_a=x", "--settings=alternate_settings", "--option_b=y", ] self._test(args, option_b="'y'") def _test(self, args, option_b="'2'"): out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:BaseCommand labels=('testlabel',), options=[" "('force_color', False), ('no_color', False), ('option_a', 'x'), " "('option_b', %s), ('option_c', '3'), ('pythonpath', None), " "('settings', 'alternate_settings'), ('traceback', False), " "('verbosity', 1)]" % option_b, ) class ExecuteFromCommandLine(SimpleTestCase): def test_program_name_from_argv(self): """ Program name is computed from the execute_from_command_line()'s argv argument, not sys.argv. """ args = ["help", "shell"] with captured_stdout() as out, captured_stderr() as err: with mock.patch("sys.argv", [None] + args): execute_from_command_line(["django-admin"] + args) self.assertIn("usage: django-admin shell", out.getvalue()) self.assertEqual(err.getvalue(), "") @override_settings(ROOT_URLCONF="admin_scripts.urls") class StartProject(LiveServerTestCase, AdminScriptTestCase): available_apps = [ "admin_scripts", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", ] def test_wrong_args(self): """ Passing the wrong kinds of arguments outputs an error and prints usage. """ out, err = self.run_django_admin(["startproject"]) self.assertNoOutput(out) self.assertOutput(err, "usage:") self.assertOutput(err, "You must provide a project name.") def test_simple_project(self): "Make sure the startproject management command creates a project" args = ["startproject", "testproject"] testproject_dir = os.path.join(self.test_dir, "testproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "CommandError: 'testproject' conflicts with the name of an " "existing Python module and cannot be used as a project name. " "Please try another name.", ) def test_invalid_project_name(self): "Make sure the startproject management command validates a project name" for bad_name in ("7testproject", "../testproject"): with self.subTest(project_name=bad_name): args = ["startproject", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "Error: '%s' is not a valid project name. Please make " "sure the name is a valid identifier." % bad_name, ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_project_name(self): """ startproject validates that project name doesn't clash with existing Python modules. """ bad_name = "os" args = ["startproject", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as a project name. Please try " "another name.", ) self.assertFalse(os.path.exists(testproject_dir)) def test_simple_project_different_directory(self): """ The startproject management command creates a project in a specific directory. """ args = ["startproject", "testproject", "othertestproject"] testproject_dir = os.path.join(self.test_dir, "othertestproject") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "manage.py"))) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "already exists. Overlaying a project into an existing directory " "won't replace conflicting files.", ) def test_custom_project_template(self): """ The startproject management command is able to use a different project template. """ template_path = os.path.join(custom_templates_dir, "project_template") args = ["startproject", "--template", template_path, "customtestproject"] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) def test_custom_project_template_non_python_files_not_formatted(self): template_path = os.path.join(custom_templates_dir, "project_template") args = ["startproject", "--template", template_path, "customtestproject"] testproject_dir = os.path.join(self.test_dir, "customtestproject") _, err = self.run_django_admin(args) self.assertNoOutput(err) with open( os.path.join(template_path, "additional_dir", "requirements.in") ) as f: expected = f.read() with open( os.path.join(testproject_dir, "additional_dir", "requirements.in") ) as f: result = f.read() self.assertEqual(expected, result) def test_template_dir_with_trailing_slash(self): "Ticket 17475: Template dir passed has a trailing path separator" template_path = os.path.join(custom_templates_dir, "project_template" + os.sep) args = ["startproject", "--template", template_path, "customtestproject"] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) def test_custom_project_template_from_tarball_by_path(self): """ The startproject management command is able to use a different project template from a tarball. """ template_path = os.path.join(custom_templates_dir, "project_template.tgz") args = ["startproject", "--template", template_path, "tarballtestproject"] testproject_dir = os.path.join(self.test_dir, "tarballtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_to_alternative_location(self): """ Startproject can use a project template from a tarball and create it in a specified location. """ template_path = os.path.join(custom_templates_dir, "project_template.tgz") args = [ "startproject", "--template", template_path, "tarballtestproject", "altlocation", ] testproject_dir = os.path.join(self.test_dir, "altlocation") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_by_url(self): """ The startproject management command is able to use a different project template from a tarball via a URL. """ template_url = "%s/custom_templates/project_template.tgz" % self.live_server_url args = ["startproject", "--template", template_url, "urltestproject"] testproject_dir = os.path.join(self.test_dir, "urltestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_by_url_django_user_agent(self): user_agent = None def serve_template(request, *args, **kwargs): nonlocal user_agent user_agent = request.headers["User-Agent"] return serve(request, *args, **kwargs) old_urlpatterns = urls.urlpatterns[:] try: urls.urlpatterns += [ path( "user_agent_check/<path:path>", serve_template, {"document_root": os.path.join(urls.here, "custom_templates")}, ), ] template_url = ( f"{self.live_server_url}/user_agent_check/project_template.tgz" ) args = ["startproject", "--template", template_url, "urltestproject"] _, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertIn("Django/%s" % get_version(), user_agent) finally: urls.urlpatterns = old_urlpatterns def test_project_template_tarball_url(self): """ " Startproject management command handles project template tar/zip balls from non-canonical urls. """ template_url = ( "%s/custom_templates/project_template.tgz/" % self.live_server_url ) args = ["startproject", "--template", template_url, "urltestproject"] testproject_dir = os.path.join(self.test_dir, "urltestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_file_without_extension(self): "Make sure the startproject management command is able to render custom files" template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "customtestproject", "-e", "txt", "-n", "Procfile", ] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) base_path = os.path.join(testproject_dir, "additional_dir") for f in ("Procfile", "additional_file.py", "requirements.txt"): self.assertTrue(os.path.exists(os.path.join(base_path, f))) with open(os.path.join(base_path, f)) as fh: self.assertEqual( fh.read().strip(), "# some file for customtestproject test project" ) def test_custom_project_template_context_variables(self): "Make sure template context variables are rendered with proper values" template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "another_project", "project_dir", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, "manage.py") with open(test_manage_py) as fp: content = fp.read() self.assertIn('project_name = "another_project"', content) self.assertIn('project_directory = "%s"' % testproject_dir, content) def test_no_escaping_of_project_variables(self): "Make sure template context variables are not html escaped" # We're using a custom command so we need the alternate settings self.write_settings("alternate_settings.py") template_path = os.path.join(custom_templates_dir, "project_template") args = [ "custom_startproject", "--template", template_path, "another_project", "project_dir", "--extra", "<&>", "--settings=alternate_settings", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) out, err = self.run_manage(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, "additional_dir", "extra.py") with open(test_manage_py) as fp: content = fp.read() self.assertIn("<&>", content) def test_custom_project_destination_missing(self): """ Make sure an exception is raised when the provided destination directory doesn't exist """ template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "yet_another_project", "project_dir2", ] testproject_dir = os.path.join(self.test_dir, "project_dir2") out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "Destination directory '%s' does not exist, please create it first." % testproject_dir, ) self.assertFalse(os.path.exists(testproject_dir)) def test_custom_project_template_with_non_ascii_templates(self): """ The startproject management command is able to render templates with non-ASCII content. """ template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "--extension=txt", "customtestproject", ] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) path = os.path.join(testproject_dir, "ticket-18091-non-ascii-template.txt") with open(path, encoding="utf-8") as f: self.assertEqual( f.read().splitlines(False), ["Some non-ASCII text for testing ticket #18091:", "üäö €"], ) def test_custom_project_template_hidden_directory_default_excluded(self): """Hidden directories are excluded by default.""" template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "custom_project_template_hidden_directories", "project_dir", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) hidden_dir = os.path.join(testproject_dir, ".hidden") self.assertIs(os.path.exists(hidden_dir), False) def test_custom_project_template_hidden_directory_included(self): """ Template context variables in hidden directories are rendered, if not excluded. """ template_path = os.path.join(custom_templates_dir, "project_template") project_name = "custom_project_template_hidden_directories_included" args = [ "startproject", "--template", template_path, project_name, "project_dir", "--exclude", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) render_py_path = os.path.join(testproject_dir, ".hidden", "render.py") with open(render_py_path) as fp: self.assertIn( f"# The {project_name} should be rendered.", fp.read(), ) def test_custom_project_template_exclude_directory(self): """ Excluded directories (in addition to .git and __pycache__) are not included in the project. """ template_path = os.path.join(custom_templates_dir, "project_template") project_name = "custom_project_with_excluded_directories" args = [ "startproject", "--template", template_path, project_name, "project_dir", "--exclude", "additional_dir", "-x", ".hidden", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) excluded_directories = [ ".hidden", "additional_dir", ".git", "__pycache__", ] for directory in excluded_directories: self.assertIs( os.path.exists(os.path.join(testproject_dir, directory)), False, ) not_excluded = os.path.join(testproject_dir, project_name) self.assertIs(os.path.exists(not_excluded), True) @unittest.skipIf( sys.platform == "win32", "Windows only partially supports umasks and chmod.", ) def test_honor_umask(self): _, err = self.run_django_admin(["startproject", "testproject"], umask=0o077) self.assertNoOutput(err) testproject_dir = os.path.join(self.test_dir, "testproject") self.assertIs(os.path.isdir(testproject_dir), True) tests = [ (["manage.py"], 0o700), (["testproject"], 0o700), (["testproject", "settings.py"], 0o600), ] for paths, expected_mode in tests: file_path = os.path.join(testproject_dir, *paths) with self.subTest(paths[-1]): self.assertEqual( stat.S_IMODE(os.stat(file_path).st_mode), expected_mode, ) class StartApp(AdminScriptTestCase): def test_invalid_name(self): """startapp validates that app name is a valid Python identifier.""" for bad_name in ("7testproject", "../testproject"): with self.subTest(app_name=bad_name): args = ["startapp", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: '{}' is not a valid app name. Please make " "sure the name is a valid identifier.".format(bad_name), ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_name(self): """ startapp validates that app name doesn't clash with existing Python modules. """ bad_name = "os" args = ["startapp", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as an app name. Please try " "another name.", ) self.assertFalse(os.path.exists(testproject_dir)) def test_invalid_target_name(self): for bad_target in ( "invalid.dir_name", "7invalid_dir_name", ".invalid_dir_name", ): with self.subTest(bad_target): _, err = self.run_django_admin(["startapp", "app", bad_target]) self.assertOutput( err, "CommandError: '%s' is not a valid app directory. Please " "make sure the directory is a valid identifier." % bad_target, ) def test_importable_target_name(self): _, err = self.run_django_admin(["startapp", "app", "os"]) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing Python " "module and cannot be used as an app directory. Please try " "another directory.", ) def test_trailing_slash_in_target_app_directory_name(self): app_dir = os.path.join(self.test_dir, "apps", "app1") os.makedirs(app_dir) _, err = self.run_django_admin( ["startapp", "app", os.path.join("apps", "app1", "")] ) self.assertNoOutput(err) self.assertIs(os.path.exists(os.path.join(app_dir, "apps.py")), True) def test_overlaying_app(self): # Use a subdirectory so it is outside the PYTHONPATH. os.makedirs(os.path.join(self.test_dir, "apps/app1")) self.run_django_admin(["startapp", "app1", "apps/app1"]) out, err = self.run_django_admin(["startapp", "app2", "apps/app1"]) self.assertOutput( err, "already exists. Overlaying an app into an existing directory " "won't replace conflicting files.", ) def test_template(self): out, err = self.run_django_admin(["startapp", "new_app"]) self.assertNoOutput(err) app_path = os.path.join(self.test_dir, "new_app") self.assertIs(os.path.exists(app_path), True) with open(os.path.join(app_path, "apps.py")) as f: content = f.read() self.assertIn("class NewAppConfig(AppConfig)", content) if HAS_BLACK: test_str = 'default_auto_field = "django.db.models.BigAutoField"' else: test_str = "default_auto_field = 'django.db.models.BigAutoField'" self.assertIn(test_str, content) self.assertIn( 'name = "new_app"' if HAS_BLACK else "name = 'new_app'", content, ) class DiffSettings(AdminScriptTestCase): """Tests for diffsettings management command.""" def test_basic(self): """Runs without error and emits settings diff.""" self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") # Attributes from django.conf.Settings don't appear. self.assertNotInOutput(out, "is_overridden = ") def test_settings_configured(self): out, err = self.run_manage( ["diffsettings"], manage_py="configured_settings_manage.py" ) self.assertNoOutput(err) self.assertOutput(out, "CUSTOM = 1 ###\nDEBUG = True") # Attributes from django.conf.UserSettingsHolder don't appear. self.assertNotInOutput(out, "default_settings = ") def test_dynamic_settings_configured(self): # Custom default settings appear. out, err = self.run_manage( ["diffsettings"], manage_py="configured_dynamic_settings_manage.py" ) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") def test_all(self): """The all option also shows settings with the default value.""" self.write_settings("settings_to_diff.py", sdict={"STATIC_URL": "None"}) args = ["diffsettings", "--settings=settings_to_diff", "--all"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "### STATIC_URL = None") def test_custom_default(self): """ The --default option specifies an alternate settings module for comparison. """ self.write_settings( "settings_default.py", sdict={"FOO": '"foo"', "BAR": '"bar1"'} ) self.write_settings( "settings_to_diff.py", sdict={"FOO": '"foo"', "BAR": '"bar2"'} ) out, err = self.run_manage( [ "diffsettings", "--settings=settings_to_diff", "--default=settings_default", ] ) self.assertNoOutput(err) self.assertNotInOutput(out, "FOO") self.assertOutput(out, "BAR = 'bar2'") def test_unified(self): """--output=unified emits settings diff in unified mode.""" self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'") self.assertNotInOutput(out, " APPEND_SLASH = True") def test_unified_all(self): """ --output=unified --all emits settings diff in unified mode and includes settings with the default value. """ self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = [ "diffsettings", "--settings=settings_to_diff", "--output=unified", "--all", ] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, " APPEND_SLASH = True") self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") class Dumpdata(AdminScriptTestCase): """Tests for dumpdata management command.""" def setUp(self): super().setUp() self.write_settings("settings.py") def test_pks_parsing(self): """Regression for #20509 Test would raise an exception rather than printing an error message. """ args = ["dumpdata", "--pks=1"] out, err = self.run_manage(args) self.assertOutput(err, "You can only use --pks option with one model") self.assertNoOutput(out) class MainModule(AdminScriptTestCase): """python -m django works like django-admin.""" def test_program_name_in_help(self): out, err = self.run_test(["-m", "django", "help"]) self.assertOutput( out, "Type 'python -m django help <subcommand>' for help on a specific " "subcommand.", ) class DjangoAdminSuggestions(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings("settings.py") def test_suggestions(self): args = ["rnserver", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?") def test_no_suggestions(self): args = ["abcdef", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertNotInOutput(err, "Did you mean")
9fcc368c418508d2c1ef3bd406558306186013191b2928b21c2153de5c80c687
import datetime import re import sys import zoneinfo from contextlib import contextmanager from unittest import SkipTest, skipIf from xml.dom.minidom import parseString from django.contrib.auth.models import User from django.core import serializers from django.db import connection from django.db.models import F, Max, Min from django.http import HttpRequest from django.template import ( Context, RequestContext, Template, TemplateSyntaxError, context_processors, ) from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import requires_tz_support from django.urls import reverse from django.utils import timezone, translation from django.utils.timezone import timedelta from .forms import ( EventForm, EventLocalizedForm, EventLocalizedModelForm, EventModelForm, EventSplitForm, ) from .models import ( AllDayEvent, DailyEvent, Event, MaybeEvent, Session, SessionEvent, Timestamp, ) try: import yaml HAS_YAML = True except ImportError: HAS_YAML = False # These tests use the EAT (Eastern Africa Time) and ICT (Indochina Time) # who don't have daylight saving time, so we can represent them easily # with fixed offset timezones and use them directly as tzinfo in the # constructors. # settings.TIME_ZONE is forced to EAT. Most tests use a variant of # datetime.datetime(2011, 9, 1, 13, 20, 30), which translates to # 10:20:30 in UTC and 17:20:30 in ICT. UTC = datetime.timezone.utc EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok @contextmanager def override_database_connection_timezone(timezone): try: orig_timezone = connection.settings_dict["TIME_ZONE"] connection.settings_dict["TIME_ZONE"] = timezone # Clear cached properties, after first accessing them to ensure they exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name yield finally: connection.settings_dict["TIME_ZONE"] = orig_timezone # Clear cached properties, after first accessing them to ensure they exist. connection.timezone del connection.timezone connection.timezone_name del connection.timezone_name @override_settings(TIME_ZONE="Africa/Nairobi", USE_TZ=False) class LegacyDatabaseTests(TestCase): def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_local_timezone_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipUnlessDBFeature("supports_timezones") def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # interpret the naive datetime in local time to get the correct value self.assertEqual(event.dt.replace(tzinfo=EAT), dt) @skipIfDBFeature("supports_timezones") def test_aware_datetime_unsupported(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) msg = "backend does not support timezone-aware datetimes when USE_TZ is False." with self.assertRaisesMessage(ValueError, msg): Event.objects.create(dt=dt) def test_auto_now_and_auto_now_add(self): now = datetime.datetime.now() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) self.assertGreater(future, ts.updated) def test_query_filter(self): dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30) dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30) Event.objects.create(dt=dt1) Event.objects.create(dt=dt2) self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2) self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1) self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1) self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0) def test_query_datetime_lookups(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0)) self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2) self.assertEqual(Event.objects.filter(dt__month=1).count(), 2) self.assertEqual(Event.objects.filter(dt__day=1).count(), 2) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 2) self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) def test_query_aggregation(self): # Only min and max make sense for datetimes. Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40)) result = Event.objects.aggregate(Min("dt"), Max("dt")) self.assertEqual( result, { "dt__min": datetime.datetime(2011, 9, 1, 3, 20, 40), "dt__max": datetime.datetime(2011, 9, 1, 23, 20, 20), }, ) def test_query_annotation(self): # Only min and max make sense for datetimes. morning = Session.objects.create(name="morning") afternoon = Session.objects.create(name="afternoon") SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 23, 20, 20), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 13, 20, 30), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 3, 20, 40), session=morning ) morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40) afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).order_by("dt"), [morning_min_dt, afternoon_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__lt=afternoon_min_dt ), [morning_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__gte=afternoon_min_dt ), [afternoon_min_dt], transform=lambda d: d.dt, ) def test_query_datetimes(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0)) self.assertSequenceEqual( Event.objects.datetimes("dt", "year"), [datetime.datetime(2011, 1, 1, 0, 0, 0)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "month"), [datetime.datetime(2011, 1, 1, 0, 0, 0)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "day"), [datetime.datetime(2011, 1, 1, 0, 0, 0)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "hour"), [ datetime.datetime(2011, 1, 1, 1, 0, 0), datetime.datetime(2011, 1, 1, 4, 0, 0), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "minute"), [ datetime.datetime(2011, 1, 1, 1, 30, 0), datetime.datetime(2011, 1, 1, 4, 30, 0), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "second"), [ datetime.datetime(2011, 1, 1, 1, 30, 0), datetime.datetime(2011, 1, 1, 4, 30, 0), ], ) def test_raw_sql(self): # Regression test for #17755 dt = datetime.datetime(2011, 9, 1, 13, 20, 30) event = Event.objects.create(dt=dt) self.assertEqual( list( Event.objects.raw("SELECT * FROM timezones_event WHERE dt = %s", [dt]) ), [event], ) def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) with connection.cursor() as cursor: cursor.execute("INSERT INTO timezones_event (dt) VALUES (%s)", [dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute("SELECT dt FROM timezones_event WHERE dt = %s", [dt]) self.assertEqual(cursor.fetchall()[0][0], dt) def test_filter_date_field_with_aware_datetime(self): # Regression test for #17742 day = datetime.date(2011, 9, 1) AllDayEvent.objects.create(day=day) # This is 2011-09-02T01:30:00+03:00 in EAT dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) self.assertTrue(AllDayEvent.objects.filter(day__gte=dt).exists()) @override_settings(TIME_ZONE="Africa/Nairobi", USE_TZ=True) class NewDatabaseTests(TestCase): naive_warning = "DateTimeField Event.dt received a naive datetime" @skipIfDBFeature("supports_timezones") def test_aware_time_unsupported(self): t = datetime.time(13, 20, 30, tzinfo=EAT) msg = "backend does not support timezone-aware times." with self.assertRaisesMessage(ValueError, msg): DailyEvent.objects.create(time=t) @requires_tz_support def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() # naive datetimes are interpreted in local time self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) @requires_tz_support def test_datetime_from_date(self): dt = datetime.date(2011, 9, 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT)) @requires_tz_support def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): Event.objects.create(dt=dt) event = Event.objects.get() # naive datetimes are interpreted in local time self.assertEqual(event.dt, dt.replace(tzinfo=EAT)) def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_local_timezone_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060, tzinfo=EAT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertEqual(event.dt, dt) def test_auto_now_and_auto_now_add(self): now = timezone.now() past = now - datetime.timedelta(seconds=2) future = now + datetime.timedelta(seconds=2) Timestamp.objects.create() ts = Timestamp.objects.get() self.assertLess(past, ts.created) self.assertLess(past, ts.updated) self.assertGreater(future, ts.updated) self.assertGreater(future, ts.updated) def test_query_filter(self): dt1 = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) dt2 = datetime.datetime(2011, 9, 1, 14, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt1) Event.objects.create(dt=dt2) self.assertEqual(Event.objects.filter(dt__gte=dt1).count(), 2) self.assertEqual(Event.objects.filter(dt__gt=dt1).count(), 1) self.assertEqual(Event.objects.filter(dt__gte=dt2).count(), 1) self.assertEqual(Event.objects.filter(dt__gt=dt2).count(), 0) def test_query_filter_with_timezones(self): tz = zoneinfo.ZoneInfo("Europe/Paris") dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=tz) Event.objects.create(dt=dt) next = dt + datetime.timedelta(seconds=3) prev = dt - datetime.timedelta(seconds=3) self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1) self.assertEqual(Event.objects.filter(dt__exact=next).count(), 0) self.assertEqual(Event.objects.filter(dt__in=(prev, next)).count(), 0) self.assertEqual(Event.objects.filter(dt__in=(prev, dt, next)).count(), 1) self.assertEqual(Event.objects.filter(dt__range=(prev, next)).count(), 1) def test_query_convert_timezones(self): # Connection timezone is equal to the current timezone, datetime # shouldn't be converted. with override_database_connection_timezone("Africa/Nairobi"): event_datetime = datetime.datetime(2016, 1, 2, 23, 10, 11, 123, tzinfo=EAT) event = Event.objects.create(dt=event_datetime) self.assertEqual( Event.objects.filter(dt__date=event_datetime.date()).first(), event ) # Connection timezone is not equal to the current timezone, datetime # should be converted (-4h). with override_database_connection_timezone("Asia/Bangkok"): event_datetime = datetime.datetime(2016, 1, 2, 3, 10, 11, tzinfo=ICT) event = Event.objects.create(dt=event_datetime) self.assertEqual( Event.objects.filter(dt__date=datetime.date(2016, 1, 1)).first(), event ) @requires_tz_support def test_query_filter_with_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 12, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) dt = dt.replace(tzinfo=None) # naive datetimes are interpreted in local time with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__exact=dt).count(), 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__lte=dt).count(), 1) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): self.assertEqual(Event.objects.filter(dt__gt=dt).count(), 0) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetime_lookups(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) self.assertEqual(Event.objects.filter(dt__year=2011).count(), 2) self.assertEqual(Event.objects.filter(dt__month=1).count(), 2) self.assertEqual(Event.objects.filter(dt__day=1).count(), 2) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 2) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 2) self.assertEqual(Event.objects.filter(dt__hour=1).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetime_lookups_in_other_timezone(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) with timezone.override(UTC): # These two dates fall in the same day in EAT, but in different days, # years and months in UTC. self.assertEqual(Event.objects.filter(dt__year=2011).count(), 1) self.assertEqual(Event.objects.filter(dt__month=1).count(), 1) self.assertEqual(Event.objects.filter(dt__day=1).count(), 1) self.assertEqual(Event.objects.filter(dt__week_day=7).count(), 1) self.assertEqual(Event.objects.filter(dt__iso_week_day=6).count(), 1) self.assertEqual(Event.objects.filter(dt__hour=22).count(), 1) self.assertEqual(Event.objects.filter(dt__minute=30).count(), 2) self.assertEqual(Event.objects.filter(dt__second=0).count(), 2) def test_query_aggregation(self): # Only min and max make sense for datetimes. Event.objects.create(dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT)) result = Event.objects.aggregate(Min("dt"), Max("dt")) self.assertEqual( result, { "dt__min": datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), "dt__max": datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), }, ) def test_query_annotation(self): # Only min and max make sense for datetimes. morning = Session.objects.create(name="morning") afternoon = Session.objects.create(name="afternoon") SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 23, 20, 20, tzinfo=EAT), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), session=afternoon ) SessionEvent.objects.create( dt=datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT), session=morning ) morning_min_dt = datetime.datetime(2011, 9, 1, 3, 20, 40, tzinfo=EAT) afternoon_min_dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).order_by("dt"), [morning_min_dt, afternoon_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__lt=afternoon_min_dt ), [morning_min_dt], transform=lambda d: d.dt, ) self.assertQuerySetEqual( Session.objects.annotate(dt=Min("events__dt")).filter( dt__gte=afternoon_min_dt ), [afternoon_min_dt], transform=lambda d: d.dt, ) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetimes(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) self.assertSequenceEqual( Event.objects.datetimes("dt", "year"), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "month"), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "day"), [datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=EAT)], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "hour"), [ datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 0, 0, tzinfo=EAT), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "minute"), [ datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "second"), [ datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT), datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT), ], ) @skipUnlessDBFeature("has_zoneinfo_database") def test_query_datetimes_in_other_timezone(self): Event.objects.create(dt=datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=EAT)) Event.objects.create(dt=datetime.datetime(2011, 1, 1, 4, 30, 0, tzinfo=EAT)) with timezone.override(UTC): self.assertSequenceEqual( Event.objects.datetimes("dt", "year"), [ datetime.datetime(2010, 1, 1, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "month"), [ datetime.datetime(2010, 12, 1, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "day"), [ datetime.datetime(2010, 12, 31, 0, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 0, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "hour"), [ datetime.datetime(2010, 12, 31, 22, 0, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 0, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "minute"), [ datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC), ], ) self.assertSequenceEqual( Event.objects.datetimes("dt", "second"), [ datetime.datetime(2010, 12, 31, 22, 30, 0, tzinfo=UTC), datetime.datetime(2011, 1, 1, 1, 30, 0, tzinfo=UTC), ], ) def test_raw_sql(self): # Regression test for #17755 dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) event = Event.objects.create(dt=dt) self.assertSequenceEqual( list( Event.objects.raw("SELECT * FROM timezones_event WHERE dt = %s", [dt]) ), [event], ) @skipUnlessDBFeature("supports_timezones") def test_cursor_execute_accepts_aware_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) with connection.cursor() as cursor: cursor.execute("INSERT INTO timezones_event (dt) VALUES (%s)", [dt]) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipIfDBFeature("supports_timezones") def test_cursor_execute_accepts_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) utc_naive_dt = timezone.make_naive(dt, datetime.timezone.utc) with connection.cursor() as cursor: cursor.execute( "INSERT INTO timezones_event (dt) VALUES (%s)", [utc_naive_dt] ) event = Event.objects.get() self.assertEqual(event.dt, dt) @skipUnlessDBFeature("supports_timezones") def test_cursor_execute_returns_aware_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute("SELECT dt FROM timezones_event WHERE dt = %s", [dt]) self.assertEqual(cursor.fetchall()[0][0], dt) @skipIfDBFeature("supports_timezones") def test_cursor_execute_returns_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) utc_naive_dt = timezone.make_naive(dt, datetime.timezone.utc) Event.objects.create(dt=dt) with connection.cursor() as cursor: cursor.execute( "SELECT dt FROM timezones_event WHERE dt = %s", [utc_naive_dt] ) self.assertEqual(cursor.fetchall()[0][0], utc_naive_dt) @skipUnlessDBFeature("supports_timezones") def test_cursor_explicit_time_zone(self): with override_database_connection_timezone("Europe/Paris"): with connection.cursor() as cursor: cursor.execute("SELECT CURRENT_TIMESTAMP") now = cursor.fetchone()[0] self.assertEqual(str(now.tzinfo), "Europe/Paris") @requires_tz_support def test_filter_date_field_with_aware_datetime(self): # Regression test for #17742 day = datetime.date(2011, 9, 1) AllDayEvent.objects.create(day=day) # This is 2011-09-02T01:30:00+03:00 in EAT dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists()) def test_null_datetime(self): # Regression test for #17294 e = MaybeEvent.objects.create() self.assertIsNone(e.dt) def test_update_with_timedelta(self): initial_dt = timezone.now().replace(microsecond=0) event = Event.objects.create(dt=initial_dt) Event.objects.update(dt=F("dt") + timedelta(hours=2)) event.refresh_from_db() self.assertEqual(event.dt, initial_dt + timedelta(hours=2)) @override_settings(TIME_ZONE="Africa/Nairobi", USE_TZ=True) class ForcedTimeZoneDatabaseTests(TransactionTestCase): """ Test the TIME_ZONE database configuration parameter. Since this involves reading and writing to the same database through two connections, this is a TransactionTestCase. """ available_apps = ["timezones"] @classmethod def setUpClass(cls): # @skipIfDBFeature and @skipUnlessDBFeature cannot be chained. The # outermost takes precedence. Handle skipping manually instead. if connection.features.supports_timezones: raise SkipTest("Database has feature(s) supports_timezones") if not connection.features.test_db_allows_multiple_connections: raise SkipTest( "Database doesn't support feature(s): " "test_db_allows_multiple_connections" ) super().setUpClass() def test_read_datetime(self): fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC) Event.objects.create(dt=fake_dt) with override_database_connection_timezone("Asia/Bangkok"): event = Event.objects.get() dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) self.assertEqual(event.dt, dt) def test_write_datetime(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) with override_database_connection_timezone("Asia/Bangkok"): Event.objects.create(dt=dt) event = Event.objects.get() fake_dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=UTC) self.assertEqual(event.dt, fake_dt) @override_settings(TIME_ZONE="Africa/Nairobi") class SerializationTests(SimpleTestCase): # Backend-specific notes: # - JSON supports only milliseconds, microseconds will be truncated. # - PyYAML dumps the UTC offset correctly for timezone-aware datetimes. # When PyYAML < 5.3 loads this representation, it subtracts the offset # and returns a naive datetime object in UTC. PyYAML 5.3+ loads timezones # correctly. # Tests are adapted to take these quirks into account. def assert_python_contains_datetime(self, objects, dt): self.assertEqual(objects[0]["fields"]["dt"], dt) def assert_json_contains_datetime(self, json, dt): self.assertIn('"fields": {"dt": "%s"}' % dt, json) def assert_xml_contains_datetime(self, xml, dt): field = parseString(xml).getElementsByTagName("field")[0] self.assertXMLEqual(field.childNodes[0].wholeText, dt) def assert_yaml_contains_datetime(self, yaml, dt): # Depending on the yaml dumper, '!timestamp' might be absent self.assertRegex(yaml, r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt)) def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30") obj = next(serializers.deserialize("yaml", data)).object self.assertEqual(obj.dt, dt) def test_naive_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30.405") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt.replace(microsecond=405000)) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30.405060") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30.405060") obj = next(serializers.deserialize("yaml", data)).object self.assertEqual(obj.dt, dt) def test_aware_datetime_with_microsecond(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, 405060, tzinfo=ICT) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T17:20:30.405+07:00") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt.replace(microsecond=405000)) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30.405060+07:00") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 17:20:30.405060+07:00") obj = next(serializers.deserialize("yaml", data)).object if HAS_YAML and yaml.__version__ < "5.3": self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) else: self.assertEqual(obj.dt, dt) def test_aware_datetime_in_utc(self): dt = datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T10:20:30Z") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T10:20:30+00:00") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 10:20:30+00:00") obj = next(serializers.deserialize("yaml", data)).object self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) def test_aware_datetime_in_local_timezone(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T13:20:30+03:00") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T13:20:30+03:00") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 13:20:30+03:00") obj = next(serializers.deserialize("yaml", data)).object if HAS_YAML and yaml.__version__ < "5.3": self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) else: self.assertEqual(obj.dt, dt) def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) data = serializers.serialize("python", [Event(dt=dt)]) self.assert_python_contains_datetime(data, dt) obj = next(serializers.deserialize("python", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("json", [Event(dt=dt)]) self.assert_json_contains_datetime(data, "2011-09-01T17:20:30+07:00") obj = next(serializers.deserialize("json", data)).object self.assertEqual(obj.dt, dt) data = serializers.serialize("xml", [Event(dt=dt)]) self.assert_xml_contains_datetime(data, "2011-09-01T17:20:30+07:00") obj = next(serializers.deserialize("xml", data)).object self.assertEqual(obj.dt, dt) if not isinstance( serializers.get_serializer("yaml"), serializers.BadSerializer ): data = serializers.serialize( "yaml", [Event(dt=dt)], default_flow_style=None ) self.assert_yaml_contains_datetime(data, "2011-09-01 17:20:30+07:00") obj = next(serializers.deserialize("yaml", data)).object if HAS_YAML and yaml.__version__ < "5.3": self.assertEqual(obj.dt.replace(tzinfo=UTC), dt) else: self.assertEqual(obj.dt, dt) @translation.override(None) @override_settings(DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_TZ=True) class TemplateTests(SimpleTestCase): @requires_tz_support def test_localtime_templatetag_and_filters(self): """ Test the {% localtime %} templatetag and related filters. """ datetimes = { "utc": datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), "eat": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), "ict": datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), "naive": datetime.datetime(2011, 9, 1, 13, 20, 30), } templates = { "notag": Template( "{% load tz %}" "{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}" ), "noarg": Template( "{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|" "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" ), "on": Template( "{% load tz %}{% localtime on %}{{ dt }}|{{ dt|localtime }}|" "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" ), "off": Template( "{% load tz %}{% localtime off %}{{ dt }}|{{ dt|localtime }}|" "{{ dt|utc }}|{{ dt|timezone:ICT }}{% endlocaltime %}" ), } # Transform a list of keys in 'datetimes' to the expected template # output. This makes the definition of 'results' more readable. def t(*result): return "|".join(datetimes[key].isoformat() for key in result) # Results for USE_TZ = True results = { "utc": { "notag": t("eat", "eat", "utc", "ict"), "noarg": t("eat", "eat", "utc", "ict"), "on": t("eat", "eat", "utc", "ict"), "off": t("utc", "eat", "utc", "ict"), }, "eat": { "notag": t("eat", "eat", "utc", "ict"), "noarg": t("eat", "eat", "utc", "ict"), "on": t("eat", "eat", "utc", "ict"), "off": t("eat", "eat", "utc", "ict"), }, "ict": { "notag": t("eat", "eat", "utc", "ict"), "noarg": t("eat", "eat", "utc", "ict"), "on": t("eat", "eat", "utc", "ict"), "off": t("ict", "eat", "utc", "ict"), }, "naive": { "notag": t("naive", "eat", "utc", "ict"), "noarg": t("naive", "eat", "utc", "ict"), "on": t("naive", "eat", "utc", "ict"), "off": t("naive", "eat", "utc", "ict"), }, } for k1, dt in datetimes.items(): for k2, tpl in templates.items(): ctx = Context({"dt": dt, "ICT": ICT}) actual = tpl.render(ctx) expected = results[k1][k2] self.assertEqual( actual, expected, "%s / %s: %r != %r" % (k1, k2, actual, expected) ) # Changes for USE_TZ = False results["utc"]["notag"] = t("utc", "eat", "utc", "ict") results["ict"]["notag"] = t("ict", "eat", "utc", "ict") with self.settings(USE_TZ=False): for k1, dt in datetimes.items(): for k2, tpl in templates.items(): ctx = Context({"dt": dt, "ICT": ICT}) actual = tpl.render(ctx) expected = results[k1][k2] self.assertEqual( actual, expected, "%s / %s: %r != %r" % (k1, k2, actual, expected), ) def test_localtime_filters_with_iana(self): """ Test the |localtime, |utc, and |timezone filters with iana zones. """ # Use an IANA timezone as local time tpl = Template("{% load tz %}{{ dt|localtime }}|{{ dt|utc }}") ctx = Context({"dt": datetime.datetime(2011, 9, 1, 12, 20, 30)}) with self.settings(TIME_ZONE="Europe/Paris"): self.assertEqual( tpl.render(ctx), "2011-09-01T12:20:30+02:00|2011-09-01T10:20:30+00:00" ) # Use an IANA timezone as argument tz = zoneinfo.ZoneInfo("Europe/Paris") tpl = Template("{% load tz %}{{ dt|timezone:tz }}") ctx = Context( { "dt": datetime.datetime(2011, 9, 1, 13, 20, 30), "tz": tz, } ) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") def test_localtime_templatetag_invalid_argument(self): with self.assertRaises(TemplateSyntaxError): Template("{% load tz %}{% localtime foo %}{% endlocaltime %}").render() def test_localtime_filters_do_not_raise_exceptions(self): """ Test the |localtime, |utc, and |timezone filters on bad inputs. """ tpl = Template( "{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:tz }}" ) with self.settings(USE_TZ=True): # bad datetime value ctx = Context({"dt": None, "tz": ICT}) self.assertEqual(tpl.render(ctx), "None|||") ctx = Context({"dt": "not a date", "tz": ICT}) self.assertEqual(tpl.render(ctx), "not a date|||") # bad timezone value tpl = Template("{% load tz %}{{ dt|timezone:tz }}") ctx = Context({"dt": datetime.datetime(2011, 9, 1, 13, 20, 30), "tz": None}) self.assertEqual(tpl.render(ctx), "") ctx = Context( {"dt": datetime.datetime(2011, 9, 1, 13, 20, 30), "tz": "not a tz"} ) self.assertEqual(tpl.render(ctx), "") @requires_tz_support def test_timezone_templatetag(self): """ Test the {% timezone %} templatetag. """ tpl = Template( "{% load tz %}" "{{ dt }}|" "{% timezone tz1 %}" "{{ dt }}|" "{% timezone tz2 %}" "{{ dt }}" "{% endtimezone %}" "{% endtimezone %}" ) ctx = Context( { "dt": datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), "tz1": ICT, "tz2": None, } ) self.assertEqual( tpl.render(ctx), "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|" "2011-09-01T13:20:30+03:00", ) def test_timezone_templatetag_with_iana(self): """ Test the {% timezone %} templatetag with IANA time zone providers. """ tpl = Template("{% load tz %}{% timezone tz %}{{ dt }}{% endtimezone %}") # Use a IANA timezone as argument tz = zoneinfo.ZoneInfo("Europe/Paris") ctx = Context( { "dt": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), "tz": tz, } ) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") # Use a IANA timezone name as argument ctx = Context( { "dt": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), "tz": "Europe/Paris", } ) self.assertEqual(tpl.render(ctx), "2011-09-01T12:20:30+02:00") @skipIf(sys.platform == "win32", "Windows uses non-standard time zone names") def test_get_current_timezone_templatetag(self): """ Test the {% get_current_timezone %} templatetag. """ tpl = Template( "{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}" ) self.assertEqual(tpl.render(Context()), "Africa/Nairobi") with timezone.override(UTC): self.assertEqual(tpl.render(Context()), "UTC") tpl = Template( "{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}" "{% endtimezone %}{{ time_zone }}" ) self.assertEqual(tpl.render(Context({"tz": ICT})), "+0700") with timezone.override(UTC): self.assertEqual(tpl.render(Context({"tz": ICT})), "+0700") def test_get_current_timezone_templatetag_with_iana(self): tpl = Template( "{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}" ) tz = zoneinfo.ZoneInfo("Europe/Paris") with timezone.override(tz): self.assertEqual(tpl.render(Context()), "Europe/Paris") tpl = Template( "{% load tz %}{% timezone 'Europe/Paris' %}" "{% get_current_timezone as time_zone %}{% endtimezone %}" "{{ time_zone }}" ) self.assertEqual(tpl.render(Context()), "Europe/Paris") def test_get_current_timezone_templatetag_invalid_argument(self): msg = ( "'get_current_timezone' requires 'as variable' (got " "['get_current_timezone'])" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load tz %}{% get_current_timezone %}").render() @skipIf(sys.platform == "win32", "Windows uses non-standard time zone names") def test_tz_template_context_processor(self): """ Test the django.template.context_processors.tz template context processor. """ tpl = Template("{{ TIME_ZONE }}") context = Context() self.assertEqual(tpl.render(context), "") request_context = RequestContext( HttpRequest(), processors=[context_processors.tz] ) self.assertEqual(tpl.render(request_context), "Africa/Nairobi") @requires_tz_support def test_date_and_time_template_filters(self): tpl = Template("{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}") ctx = Context({"dt": datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)}) self.assertEqual(tpl.render(ctx), "2011-09-01 at 23:20:20") with timezone.override(ICT): self.assertEqual(tpl.render(ctx), "2011-09-02 at 03:20:20") def test_date_and_time_template_filters_honor_localtime(self): tpl = Template( "{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at " "{{ dt|time:'H:i:s' }}{% endlocaltime %}" ) ctx = Context({"dt": datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)}) self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20") with timezone.override(ICT): self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20") @requires_tz_support def test_now_template_tag_uses_current_time_zone(self): # Regression for #17343 tpl = Template('{% now "O" %}') self.assertEqual(tpl.render(Context({})), "+0300") with timezone.override(ICT): self.assertEqual(tpl.render(Context({})), "+0700") @override_settings(DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_TZ=False) class LegacyFormsTests(TestCase): def test_form(self): form = EventForm({"dt": "2011-09-01 13:20:30"}) self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 13, 20, 30) ) def test_form_with_non_existent_time(self): form = EventForm({"dt": "2011-03-27 02:30:00"}) tz = zoneinfo.ZoneInfo("Europe/Paris") with timezone.override(tz): # This is a bug. self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 3, 27, 2, 30, 0), ) def test_form_with_ambiguous_time(self): form = EventForm({"dt": "2011-10-30 02:30:00"}) tz = zoneinfo.ZoneInfo("Europe/Paris") with timezone.override(tz): # This is a bug. self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 10, 30, 2, 30, 0), ) def test_split_form(self): form = EventSplitForm({"dt_0": "2011-09-01", "dt_1": "13:20:30"}) self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 13, 20, 30) ) def test_model_form(self): EventModelForm({"dt": "2011-09-01 13:20:30"}).save() e = Event.objects.get() self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 13, 20, 30)) @override_settings(DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_TZ=True) class NewFormsTests(TestCase): @requires_tz_support def test_form(self): form = EventForm({"dt": "2011-09-01 13:20:30"}) self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), ) def test_form_with_other_timezone(self): form = EventForm({"dt": "2011-09-01 17:20:30"}) with timezone.override(ICT): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), ) def test_form_with_non_existent_time(self): tz = zoneinfo.ZoneInfo("Europe/Paris") with timezone.override(tz): form = EventForm({"dt": "2011-03-27 02:30:00"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["dt"], [ "2011-03-27 02:30:00 couldn’t be interpreted in time zone " "Europe/Paris; it may be ambiguous or it may not exist." ], ) def test_form_with_ambiguous_time(self): tz = zoneinfo.ZoneInfo("Europe/Paris") with timezone.override(tz): form = EventForm({"dt": "2011-10-30 02:30:00"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["dt"], [ "2011-10-30 02:30:00 couldn’t be interpreted in time zone " "Europe/Paris; it may be ambiguous or it may not exist." ], ) @requires_tz_support def test_split_form(self): form = EventSplitForm({"dt_0": "2011-09-01", "dt_1": "13:20:30"}) self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data["dt"], datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC), ) @requires_tz_support def test_localized_form(self): form = EventLocalizedForm( initial={"dt": datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)} ) with timezone.override(ICT): self.assertIn("2011-09-01 17:20:30", str(form)) @requires_tz_support def test_model_form(self): EventModelForm({"dt": "2011-09-01 13:20:30"}).save() e = Event.objects.get() self.assertEqual(e.dt, datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC)) @requires_tz_support def test_localized_model_form(self): form = EventLocalizedModelForm( instance=Event(dt=datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) ) with timezone.override(ICT): self.assertIn("2011-09-01 17:20:30", str(form)) @translation.override(None) @override_settings( DATETIME_FORMAT="c", TIME_ZONE="Africa/Nairobi", USE_TZ=True, ROOT_URLCONF="timezones.urls", ) class AdminTests(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user( password="secret", last_login=datetime.datetime(2007, 5, 30, 13, 20, 10, tzinfo=UTC), is_superuser=True, username="super", first_name="Super", last_name="User", email="[email protected]", is_staff=True, is_active=True, date_joined=datetime.datetime(2007, 5, 30, 13, 20, 10, tzinfo=UTC), ) def setUp(self): self.client.force_login(self.u1) @requires_tz_support def test_changelist(self): e = Event.objects.create( dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) ) response = self.client.get(reverse("admin_tz:timezones_event_changelist")) self.assertContains(response, e.dt.astimezone(EAT).isoformat()) def test_changelist_in_other_timezone(self): e = Event.objects.create( dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) ) with timezone.override(ICT): response = self.client.get(reverse("admin_tz:timezones_event_changelist")) self.assertContains(response, e.dt.astimezone(ICT).isoformat()) @requires_tz_support def test_change_editable(self): e = Event.objects.create( dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) ) response = self.client.get( reverse("admin_tz:timezones_event_change", args=(e.pk,)) ) self.assertContains(response, e.dt.astimezone(EAT).date().isoformat()) self.assertContains(response, e.dt.astimezone(EAT).time().isoformat()) def test_change_editable_in_other_timezone(self): e = Event.objects.create( dt=datetime.datetime(2011, 9, 1, 10, 20, 30, tzinfo=UTC) ) with timezone.override(ICT): response = self.client.get( reverse("admin_tz:timezones_event_change", args=(e.pk,)) ) self.assertContains(response, e.dt.astimezone(ICT).date().isoformat()) self.assertContains(response, e.dt.astimezone(ICT).time().isoformat()) @requires_tz_support def test_change_readonly(self): t = Timestamp.objects.create() response = self.client.get( reverse("admin_tz:timezones_timestamp_change", args=(t.pk,)) ) self.assertContains(response, t.created.astimezone(EAT).isoformat()) def test_change_readonly_in_other_timezone(self): t = Timestamp.objects.create() with timezone.override(ICT): response = self.client.get( reverse("admin_tz:timezones_timestamp_change", args=(t.pk,)) ) self.assertContains(response, t.created.astimezone(ICT).isoformat())
2aef89227d6ba3917091d8eb1f497290412a29dee8f2ca04f74e259e37d6f16b
import datetime import decimal import gettext as gettext_module import os import pickle import re import tempfile from contextlib import contextmanager from importlib import import_module from pathlib import Path from unittest import mock from asgiref.local import Local from django import forms from django.apps import AppConfig from django.conf import settings from django.conf.locale import LANG_INFO from django.conf.urls.i18n import i18n_patterns from django.template import Context, Template from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.utils import translation from django.utils.formats import ( date_format, get_format, iter_format_modules, localize, localize_input, reset_format_cache, sanitize_separators, sanitize_strftime_format, time_format, ) from django.utils.numberformat import format as nformat from django.utils.safestring import SafeString, mark_safe from django.utils.translation import ( activate, check_for_language, deactivate, get_language, get_language_bidi, get_language_from_request, get_language_info, gettext, gettext_lazy, ngettext, ngettext_lazy, npgettext, npgettext_lazy, pgettext, round_away_from_one, to_language, to_locale, trans_null, trans_real, ) from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) from .forms import CompanyForm, I18nForm, SelectDateForm from .models import Company, TestModel here = os.path.dirname(os.path.abspath(__file__)) extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(here, "other", "locale"), ] class AppModuleStub: def __init__(self, **kwargs): self.__dict__.update(kwargs) @contextmanager def patch_formats(lang, **settings): from django.utils.formats import _format_cache # Populate _format_cache with temporary values for key, value in settings.items(): _format_cache[(key, lang)] = value try: yield finally: reset_format_cache() class TranslationTests(SimpleTestCase): @translation.override("fr") def test_plural(self): """ Test plurals with ngettext. French differs from English in that 0 is singular. """ self.assertEqual( ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 année", ) self.assertEqual( ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 années", ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet" ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets" ) def test_plural_null(self): g = trans_null.ngettext self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years") self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year") self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years") @override_settings(LOCALE_PATHS=extended_locale_paths) @translation.override("fr") def test_multiple_plurals_per_language(self): """ Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po has a different plural equation with 3 plurals, this tests if those plural are honored. """ self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1") self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier") self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2") french = trans_real.catalog() # Internal _catalog can query subcatalogs (from different po files). self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier") self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure") def test_override(self): activate("de") try: with translation.override("pl"): self.assertEqual(get_language(), "pl") self.assertEqual(get_language(), "de") with translation.override(None): self.assertIsNone(get_language()) with translation.override("pl"): pass self.assertIsNone(get_language()) self.assertEqual(get_language(), "de") finally: deactivate() def test_override_decorator(self): @translation.override("pl") def func_pl(): self.assertEqual(get_language(), "pl") @translation.override(None) def func_none(): self.assertIsNone(get_language()) try: activate("de") func_pl() self.assertEqual(get_language(), "de") func_none() self.assertEqual(get_language(), "de") finally: deactivate() def test_override_exit(self): """ The language restored is the one used when the function was called, not the one used when the decorator was initialized (#23381). """ activate("fr") @translation.override("pl") def func_pl(): pass deactivate() try: activate("en") func_pl() self.assertEqual(get_language(), "en") finally: deactivate() def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = gettext_lazy("Add %(name)s") d = {"name": "Ringo"} self.assertEqual("Add Ringo", s % d) with translation.override("de", deactivate=True): self.assertEqual("Ringo hinzuf\xfcgen", s % d) with translation.override("pl"): self.assertEqual("Dodaj Ringo", s % d) # It should be possible to compare *_lazy objects. s1 = gettext_lazy("Add %(name)s") self.assertEqual(s, s1) s2 = gettext_lazy("Add %(name)s") s3 = gettext_lazy("Add %(name)s") self.assertEqual(s2, s3) self.assertEqual(s, s2) s4 = gettext_lazy("Some other string") self.assertNotEqual(s, s4) def test_lazy_pickle(self): s1 = gettext_lazy("test") self.assertEqual(str(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(str(s2), "test") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy(self): simple_with_format = ngettext_lazy("%d good result", "%d good results") simple_context_with_format = npgettext_lazy( "Exclamation", "%d good result", "%d good results" ) simple_without_format = ngettext_lazy("good result", "good results") with translation.override("de"): self.assertEqual(simple_with_format % 1, "1 gutes Resultat") self.assertEqual(simple_with_format % 4, "4 guten Resultate") self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!") self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!") self.assertEqual(simple_without_format % 1, "gutes Resultat") self.assertEqual(simple_without_format % 4, "guten Resultate") complex_nonlazy = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4 ) complex_deferred = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy % {"num": 4, "name": "Jim"}, "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 1}, "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 5}, "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred % {"name": "Jim"} self.assertEqual( complex_context_nonlazy % {"num": 4, "name": "Jim"}, "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 1}, "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 5}, "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred % {"name": "Jim"} @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy_format_style(self): simple_with_format = ngettext_lazy("{} good result", "{} good results") simple_context_with_format = npgettext_lazy( "Exclamation", "{} good result", "{} good results" ) with translation.override("de"): self.assertEqual(simple_with_format.format(1), "1 gutes Resultat") self.assertEqual(simple_with_format.format(4), "4 guten Resultate") self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!") self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!") complex_nonlazy = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4 ) complex_deferred = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num" ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy.format(num=4, name="Jim"), "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred.format(name="Jim", num=1), "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred.format(name="Jim", num=5), "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred.format(name="Jim") self.assertEqual( complex_context_nonlazy.format(num=4, name="Jim"), "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=1), "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=5), "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred.format(name="Jim") def test_ngettext_lazy_bool(self): self.assertTrue(ngettext_lazy("%d good result", "%d good results")) self.assertFalse(ngettext_lazy("", "")) def test_ngettext_lazy_pickle(self): s1 = ngettext_lazy("%d good result", "%d good results") self.assertEqual(s1 % 1, "1 good result") self.assertEqual(s1 % 8, "8 good results") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(s2 % 1, "1 good result") self.assertEqual(s2 % 8, "8 good results") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_pgettext(self): trans_real._active = Local() trans_real._translations = {} with translation.override("de"): self.assertEqual(pgettext("unexisting", "May"), "May") self.assertEqual(pgettext("month name", "May"), "Mai") self.assertEqual(pgettext("verb", "May"), "Kann") self.assertEqual( npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate" ) def test_empty_value(self): """Empty value must stay empty after being translated (#23196).""" with translation.override("de"): self.assertEqual("", gettext("")) s = mark_safe("") self.assertEqual(s, gettext(s)) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_safe_status(self): """ Translating a string requiring no auto-escaping with gettext or pgettext shouldn't change the "safe" status. """ trans_real._active = Local() trans_real._translations = {} s1 = mark_safe("Password") s2 = mark_safe("May") with translation.override("de", deactivate=True): self.assertIs(type(gettext(s1)), SafeString) self.assertIs(type(pgettext("month name", s2)), SafeString) self.assertEqual("aPassword", SafeString("a") + s1) self.assertEqual("Passworda", s1 + SafeString("a")) self.assertEqual("Passworda", s1 + mark_safe("a")) self.assertEqual("aPassword", mark_safe("a") + s1) self.assertEqual("as", mark_safe("a") + mark_safe("s")) def test_maclines(self): """ Translations on files with Mac or DOS end of lines will be converted to unix EOF in .po catalogs. """ ca_translation = trans_real.translation("ca") ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n" ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n" with translation.override("ca", deactivate=True): self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r")) self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n")) def test_to_locale(self): tests = ( ("en", "en"), ("EN", "en"), ("en-us", "en_US"), ("EN-US", "en_US"), ("en_US", "en_US"), # With > 2 characters after the dash. ("sr-latn", "sr_Latn"), ("sr-LATN", "sr_Latn"), ("sr_Latn", "sr_Latn"), # 3-char language codes. ("ber-MA", "ber_MA"), ("BER-MA", "ber_MA"), ("BER_MA", "ber_MA"), ("ber_MA", "ber_MA"), # With private use subtag (x-informal). ("nl-nl-x-informal", "nl_NL-x-informal"), ("NL-NL-X-INFORMAL", "nl_NL-x-informal"), ("sr-latn-x-informal", "sr_Latn-x-informal"), ("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"), ) for lang, locale in tests: with self.subTest(lang=lang): self.assertEqual(to_locale(lang), locale) def test_to_language(self): self.assertEqual(to_language("en_US"), "en-us") self.assertEqual(to_language("sr_Lat"), "sr-lat") def test_language_bidi(self): self.assertIs(get_language_bidi(), False) with translation.override(None): self.assertIs(get_language_bidi(), False) def test_language_bidi_null(self): self.assertIs(trans_null.get_language_bidi(), False) with override_settings(LANGUAGE_CODE="he"): self.assertIs(get_language_bidi(), True) class TranslationLoadingTests(SimpleTestCase): def setUp(self): """Clear translation state.""" self._old_language = get_language() self._old_translations = trans_real._translations deactivate() trans_real._translations = {} def tearDown(self): trans_real._translations = self._old_translations activate(self._old_language) @override_settings( USE_I18N=True, LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("en-ca", "English (Canada)"), ("en-nz", "English (New Zealand)"), ("en-au", "English (Australia)"), ], LOCALE_PATHS=[os.path.join(here, "loading")], INSTALLED_APPS=["i18n.loading_app"], ) def test_translation_loading(self): """ "loading_app" does not have translations for all languages provided by "loading". Catalogs are merged correctly. """ tests = [ ("en", "local country person"), ("en_AU", "aussie"), ("en_NZ", "kiwi"), ("en_CA", "canuck"), ] # Load all relevant translations. for language, _ in tests: activate(language) # Catalogs are merged correctly. for language, nickname in tests: with self.subTest(language=language): activate(language) self.assertEqual(gettext("local country person"), nickname) class TranslationThreadSafetyTests(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *args, **kwargs): res = str.split(self, *args, **kwargs) trans_real._translations["en-YY"] = None return res trans_real._translations = {sideeffect_str("en-XX"): None} def tearDown(self): trans_real._translations = self._translations activate(self._old_language) def test_bug14894_translation_activate_thread_safety(self): translation_count = len(trans_real._translations) # May raise RuntimeError if translation.activate() isn't thread-safe. translation.activate("pl") # make sure sideeffect_str actually added a new translation self.assertLess(translation_count, len(trans_real._translations)) class FormattingTests(SimpleTestCase): def setUp(self): super().setUp() self.n = decimal.Decimal("66666.666") self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.long = 10000 self.ctxt = Context( { "n": self.n, "t": self.t, "d": self.d, "dt": self.dt, "f": self.f, "l": self.long, } ) def test_all_format_strings(self): all_locales = LANG_INFO.keys() some_date = datetime.date(2017, 10, 14) some_datetime = datetime.datetime(2017, 10, 14, 10, 23) for locale in all_locales: with self.subTest(locale=locale), translation.override(locale): self.assertIn( "2017", date_format(some_date) ) # Uses DATE_FORMAT by default self.assertIn( "23", time_format(some_datetime) ) # Uses TIME_FORMAT by default self.assertIn("2017", date_format(some_datetime, "DATETIME_FORMAT")) self.assertIn("2017", date_format(some_date, "YEAR_MONTH_FORMAT")) self.assertIn("14", date_format(some_date, "MONTH_DAY_FORMAT")) self.assertIn("2017", date_format(some_date, "SHORT_DATE_FORMAT")) self.assertIn( "2017", date_format(some_datetime, "SHORT_DATETIME_FORMAT"), ) def test_locale_independent(self): """ Localization of numbers """ with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual( "66666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "66666A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "66666", nformat( self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y" ), ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( "66,666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "6B6B6B6B6A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10,00,00,000.00", nformat( 100000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, 0), thousand_sep=",", ), ) self.assertEqual( "1,0,00,000,0000.00", nformat( 10000000000.00, decimal_sep=".", decimal_pos=2, grouping=(4, 3, 2, 1, 0), thousand_sep=",", ), ) self.assertEqual( "10000,00,000.00", nformat( 1000000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, -1), thousand_sep=",", ), ) # This unusual grouping/force_grouping combination may be triggered # by the intcomma filter. self.assertEqual( "10000", nformat( self.long, decimal_sep=".", decimal_pos=0, grouping=0, force_grouping=True, ), ) # date filter self.assertEqual( "31.12.2009 в 20:50", Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt), ) self.assertEqual( "⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt) ) def test_false_like_locale_formats(self): """ The active locale's formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string) (#16938). """ with translation.override("fr"): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"): self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) # Even a second time (after the format has been cached)... self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) with self.settings(FIRST_DAY_OF_WEEK=0): self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) # Even a second time (after the format has been cached)... self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) def test_l10n_enabled(self): self.maxDiff = 3000 # Catalan locale with translation.override("ca", deactivate=True): self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT")) self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(",", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15", time_format(self.t)) self.assertEqual("31 desembre de 2009", date_format(self.d)) self.assertEqual("1 abril de 2009", date_format(datetime.date(2009, 4, 1))) self.assertEqual( "desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT") ) self.assertEqual( "31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", localize(self.n)) self.assertEqual("99.999,999", localize(self.f)) self.assertEqual("10.000", localize(self.long)) self.assertEqual("True", localize(True)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", localize(self.n)) self.assertEqual("99999,999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("31 desembre de 2009", localize(self.d)) self.assertEqual("31 desembre de 2009 a les 20:50", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=True): form3 = I18nForm( { "decimal_field": "66.666,666", "float_field": "99.999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertTrue(form3.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form3.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form3.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form3.cleaned_data["time_field"] ) self.assertEqual(1234, form3.cleaned_data["integer_field"]) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual( "31 desembre de 2009", Template("{{ d }}").render(self.ctxt) ) self.assertEqual( "31 desembre de 2009 a les 20:50", Template("{{ dt }}").render(self.ctxt), ) self.assertEqual( "66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000,0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66.666,67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100.000,0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "31/12/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "31/12/2009 20:50", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) self.assertEqual( date_format(datetime.datetime.now()), Template('{% now "DATE_FORMAT" %}').render(self.ctxt), ) with self.settings(USE_THOUSAND_SEPARATOR=False): form4 = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form4.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form4.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form4.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form4.cleaned_data["time_field"] ) self.assertEqual(1234, form4.cleaned_data["integer_field"]) form5 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form5.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # Russian locale (with E as month) with translation.override("ru", deactivate=True): self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' '<option value="3">\u041c\u0430\u0440\u0442</option>' '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' '<option value="5">\u041c\u0430\u0439</option>' '<option value="6">\u0418\u044e\u043d\u044c</option>' '<option value="7">\u0418\u044e\u043b\u044c</option>' '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c' "</option>" '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c' "</option>" "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # English locale with translation.override("en", deactivate=True): self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("Dec. 31, 2009", date_format(self.d)) self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", localize(self.n)) self.assertEqual("99,999.999", localize(self.f)) self.assertEqual("10,000", localize(self.long)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Dec. 31, 2009", localize(self.d)) self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000.0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66,666.67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100,000.0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form5 = I18nForm( { "decimal_field": "66666.666", "float_field": "99999.999", "date_field": "12/31/2009", "datetime_field": "12/31/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form5.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form5.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data["datetime_field"], ) self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"]) self.assertEqual(1234, form5.cleaned_data["integer_field"]) form6 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form6.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form6.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">January</option>' '<option value="2">February</option>' '<option value="3">March</option>' '<option value="4">April</option>' '<option value="5">May</option>' '<option value="6">June</option>' '<option value="7">July</option>' '<option value="8">August</option>' '<option value="9">September</option>' '<option value="10">October</option>' '<option value="11">November</option>' '<option value="12" selected>December</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de-at", deactivate=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) with translation.override("es-us", deactivate=True): self.assertEqual("31 de diciembre de 2009", date_format(self.d)) def test_localized_input(self): """ Tests if form input is correctly localized """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): form6 = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertTrue(form6.is_valid()) self.assertHTMLEqual( form6.as_ul(), '<li><label for="id_name">Name:</label>' '<input id="id_name" type="text" name="name" value="acme" ' ' maxlength="50" required></li>' '<li><label for="id_date_added">Date added:</label>' '<input type="text" name="date_added" value="31.12.2009 06:00:00" ' ' id="id_date_added" required></li>' '<li><label for="id_cents_paid">Cents paid:</label>' '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" ' " required></li>" '<li><label for="id_products_delivered">Products delivered:</label>' '<input type="text" name="products_delivered" value="12000" ' ' id="id_products_delivered" required>' "</li>", ) self.assertEqual( localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00", ) self.assertEqual( datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"], ) with self.settings(USE_THOUSAND_SEPARATOR=True): # Checking for the localized "products_delivered" field self.assertInHTML( '<input type="text" name="products_delivered" ' 'value="12.000" id="id_products_delivered" required>', form6.as_ul(), ) def test_localized_input_func(self): tests = ( (True, "True"), (datetime.date(1, 1, 1), "0001-01-01"), (datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"), ) with self.settings(USE_THOUSAND_SEPARATOR=True): for value, expected in tests: with self.subTest(value=value): self.assertEqual(localize_input(value), expected) def test_sanitize_strftime_format(self): for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%C", "%02d" % (year // 100)), ("%F", "%04d-01-01" % year), ("%G", "%04d" % year), ("%Y", "%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_strftime_format_with_escaped_percent(self): dt = datetime.date(1, 1, 1) for fmt, expected in [ ("%%C", "%C"), ("%%F", "%F"), ("%%G", "%G"), ("%%Y", "%Y"), ("%%%%C", "%%C"), ("%%%%F", "%%F"), ("%%%%G", "%%G"), ("%%%%Y", "%%Y"), ]: with self.subTest(fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%%%C", "%%%02d" % (year // 100)), ("%%%F", "%%%04d-01-01" % year), ("%%%G", "%%%04d" % year), ("%%%Y", "%%%04d" % year), ("%%%%%C", "%%%%%02d" % (year // 100)), ("%%%%%F", "%%%%%04d-01-01" % year), ("%%%%%G", "%%%%%04d" % year), ("%%%%%Y", "%%%%%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_separators(self): """ Tests django.utils.formats.sanitize_separators. """ # Non-strings are untouched self.assertEqual(sanitize_separators(123), 123) with translation.override("ru", deactivate=True): # Russian locale has non-breaking space (\xa0) as thousand separator # Usual space is accepted too when sanitizing inputs with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567") self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777") self.assertEqual(sanitize_separators("12 345"), "12345") self.assertEqual(sanitize_separators("77 777,777"), "77777.777") with translation.override(None): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."): self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345") with self.settings(USE_THOUSAND_SEPARATOR=True): with patch_formats( get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR="," ): self.assertEqual(sanitize_separators("10.234"), "10234") # Suspicion that user entered dot as decimal separator (#22171) self.assertEqual(sanitize_separators("10.10"), "10.10") with translation.override(None): with self.settings(DECIMAL_SEPARATOR=","): self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") with self.settings( DECIMAL_SEPARATOR=",", THOUSAND_SEPARATOR=".", USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(sanitize_separators("1.001,10"), "1001.10") self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") # Invalid output. self.assertEqual(sanitize_separators("1,001.10"), "1.001.10") def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ # Importing some format modules so that we can compare the returned # modules with these expected modules default_mod = import_module("django.conf.locale.de.formats") test_mod = import_module("i18n.other.locale.de.formats") test_mod2 = import_module("i18n.other2.locale.de.formats") with translation.override("de-at", deactivate=True): # Should return the correct default module when no setting is set self.assertEqual(list(iter_format_modules("de")), [default_mod]) # When the setting is a string, should return the given module and # the default module self.assertEqual( list(iter_format_modules("de", "i18n.other.locale")), [test_mod, default_mod], ) # When setting is a list of strings, should return the given # modules and the default module self.assertEqual( list( iter_format_modules( "de", ["i18n.other.locale", "i18n.other2.locale"] ) ), [test_mod, test_mod2, default_mod], ) def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ en_format_mod = import_module("django.conf.locale.en.formats") en_gb_format_mod = import_module("django.conf.locale.en_GB.formats") self.assertEqual( list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod] ) def test_get_format_modules_lang(self): with translation.override("de", deactivate=True): self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en")) def test_get_format_lazy_format(self): self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y") def test_localize_templatetag_and_filter(self): """ Test the {% localize %} templatetag and the localize/unlocalize filters. """ context = Context( {"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)} ) template1 = Template( "{% load l10n %}{% localize %}" "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; " "{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}" ) template2 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} " "{{ int }}/{{ float }}/{{ date }}" ) template3 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}" ) expected_localized = "1.455/3,14/31. Dezember 2016" expected_unlocalized = "1455/3.14/Dez. 31, 2016" output1 = "; ".join([expected_localized, expected_localized]) output2 = "; ".join( [expected_localized, expected_unlocalized, expected_localized] ) output3 = "; ".join([expected_localized, expected_unlocalized]) with translation.override("de", deactivate=True): with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) def test_localized_off_numbers(self): """A string representation is returned for unlocalized numbers.""" template = Template( "{% load l10n %}{% localize off %}" "{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}" ) context = Context( {"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")} ) with self.settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") def test_localized_as_text_as_hidden_input(self): """ Form input with 'as_hidden' or 'as_text' is correctly localized. """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): template = Template( "{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}" ) template_as_text = Template( "{% load l10n %}" "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}" ) template_as_hidden = Template( "{% load l10n %}" "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}" ) form = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) context = Context({"form": form}) self.assertTrue(form.is_valid()) self.assertHTMLEqual( template.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_text.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_hidden.render(context), '<input id="id_date_added" name="date_added" type="hidden" ' 'value="31.12.2009 06:00:00">;' '<input id="id_cents_paid" name="cents_paid" type="hidden" ' 'value="59,47">', ) def test_format_arbitrary_settings(self): self.assertEqual(get_format("DEBUG"), "DEBUG") def test_get_custom_format(self): reset_format_cache() with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"): with translation.override("fr", deactivate=True): self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT")) def test_admin_javascript_supported_input_formats(self): """ The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by the admin's time picker widget. """ regex = re.compile("%([^BcdHImMpSwxXyY%])") for language_code, language_name in settings.LANGUAGES: for format_name in ( "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ): with self.subTest(language=language_code, format=format_name): formatter = get_format(format_name, lang=language_code)[0] self.assertEqual( regex.findall(formatter), [], "%s locale's %s uses an unsupported format code." % (language_code, format_name), ) class MiscTests(SimpleTestCase): rf = RequestFactory() @override_settings(LANGUAGE_CODE="de") def test_english_fallback(self): """ With a non-English LANGUAGE_CODE and if the active language is English or one of its variants, the untranslated string should be returned (instead of falling back to LANGUAGE_CODE) (See #24413). """ self.assertEqual(gettext("Image"), "Bild") with translation.override("en"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-us"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-ca"): self.assertEqual(gettext("Image"), "Image") def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ tests = [ # Good headers ("de", [("de", 1.0)]), ("en-AU", [("en-au", 1.0)]), ("es-419", [("es-419", 1.0)]), ("*;q=1.00", [("*", 1.0)]), ("en-AU;q=0.123", [("en-au", 0.123)]), ("en-au;q=0.5", [("en-au", 0.5)]), ("en-au;q=1.0", [("en-au", 1.0)]), ("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]), ("en-au-xx", [("en-au-xx", 1.0)]), ( "de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125", [ ("de", 1.0), ("en-au", 0.75), ("en-us", 0.5), ("en", 0.25), ("es", 0.125), ("fa", 0.125), ], ), ("*", [("*", 1.0)]), ("de;q=0.", [("de", 0.0)]), ("en; q=1,", [("en", 1.0)]), ("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]), # Bad headers ("en-gb;q=1.0000", []), ("en;q=0.1234", []), ("en;q=.2", []), ("abcdefghi-au", []), ("**", []), ("en,,gb", []), ("en-au;q=0.1.0", []), (("X" * 97) + "Z,en", []), ("da, en-gb;q=0.8, en;q=0.7,#", []), ("de;q=2.0", []), ("de;q=0.a", []), ("12-345", []), ("", []), ("en;q=1e0", []), ("en-au;q=1.0", []), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual( trans_real.parse_accept_lang_header(value), tuple(expected) ) def test_parse_literal_http_header(self): tests = [ ("pt-br", "pt-br"), ("pt", "pt"), ("es,de", "es"), ("es-a,de", "es"), # There isn't a Django translation to a US variation of the Spanish # language, a safe assumption. When the user sets it as the # preferred language, the main 'es' translation should be selected # instead. ("es-us", "es"), # There isn't a main language (zh) translation of Django but there # is a translation to variation (zh-hans) the user sets zh-hans as # the preferred language, it should be selected without falling # back nor ignoring it. ("zh-hans,de", "zh-hans"), ("NL", "nl"), ("fy", "fy"), ("ia", "ia"), ("sr-latn", "sr-latn"), ("zh-hans", "zh-hans"), ("zh-hant", "zh-hant"), ] for header, expected in tests: with self.subTest(header=header): request = self.rf.get("/", headers={"accept-language": header}) self.assertEqual(get_language_from_request(request), expected) @override_settings( LANGUAGES=[ ("en", "English"), ("zh-hans", "Simplified Chinese"), ("zh-hant", "Traditional Chinese"), ] ) def test_support_for_deprecated_chinese_language_codes(self): """ Some browsers (Firefox, IE, etc.) use deprecated language codes. As these language codes will be removed in Django 1.9, these will be incorrectly matched. For example zh-tw (traditional) will be interpreted as zh-hans (simplified), which is wrong. So we should also accept these deprecated language codes. refs #18419 -- this is explicitly for browser compatibility """ g = get_language_from_request request = self.rf.get("/", headers={"accept-language": "zh-cn,en"}) self.assertEqual(g(request), "zh-hans") request = self.rf.get("/", headers={"accept-language": "zh-tw,en"}) self.assertEqual(g(request), "zh-hant") def test_special_fallback_language(self): """ Some languages may have special fallbacks that don't follow the simple 'fr-ca' -> 'fr' logic (notably Chinese codes). """ request = self.rf.get("/", headers={"accept-language": "zh-my,en"}) self.assertEqual(get_language_from_request(request), "zh-hans") def test_subsequent_code_fallback_language(self): """ Subsequent language codes should be used when the language code is not supported. """ tests = [ ("zh-Hans-CN", "zh-hans"), ("zh-hans-mo", "zh-hans"), ("zh-hans-HK", "zh-hans"), ("zh-Hant-HK", "zh-hant"), ("zh-hant-tw", "zh-hant"), ("zh-hant-SG", "zh-hant"), ] for value, expected in tests: with self.subTest(value=value): request = self.rf.get("/", headers={"accept-language": f"{value},en"}) self.assertEqual(get_language_from_request(request), expected) def test_parse_language_cookie(self): g = get_language_from_request request = self.rf.get("/") request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt-br" self.assertEqual("pt-br", g(request)) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "pt" self.assertEqual("pt", g(request)) request = self.rf.get("/", headers={"accept-language": "de"}) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es" self.assertEqual("es", g(request)) # There isn't a Django translation to a US variation of the Spanish # language, a safe assumption. When the user sets it as the preferred # language, the main 'es' translation should be selected instead. request = self.rf.get("/") request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "es-us" self.assertEqual(g(request), "es") # There isn't a main language (zh) translation of Django but there is a # translation to variation (zh-hans) the user sets zh-hans as the # preferred language, it should be selected without falling back nor # ignoring it. request = self.rf.get("/", headers={"accept-language": "de"}) request.COOKIES[settings.LANGUAGE_COOKIE_NAME] = "zh-hans" self.assertEqual(g(request), "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("ar-dz", "Algerian Arabic"), ("de", "German"), ("de-at", "Austrian German"), ("pt-BR", "Portuguese (Brazil)"), ], ) def test_get_supported_language_variant_real(self): g = trans_real.get_supported_language_variant self.assertEqual(g("en"), "en") self.assertEqual(g("en-gb"), "en") self.assertEqual(g("de"), "de") self.assertEqual(g("de-at"), "de-at") self.assertEqual(g("de-ch"), "de") self.assertEqual(g("pt-br"), "pt-br") self.assertEqual(g("pt-BR"), "pt-BR") self.assertEqual(g("pt"), "pt-br") self.assertEqual(g("pt-pt"), "pt-br") self.assertEqual(g("ar-dz"), "ar-dz") self.assertEqual(g("ar-DZ"), "ar-DZ") with self.assertRaises(LookupError): g("pt", strict=True) with self.assertRaises(LookupError): g("pt-pt", strict=True) with self.assertRaises(LookupError): g("xyz") with self.assertRaises(LookupError): g("xy-zz") def test_get_supported_language_variant_null(self): g = trans_null.get_supported_language_variant self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) with self.assertRaises(LookupError): g("pt") with self.assertRaises(LookupError): g("de") with self.assertRaises(LookupError): g("de-at") with self.assertRaises(LookupError): g("de", strict=True) with self.assertRaises(LookupError): g("de-at", strict=True) with self.assertRaises(LookupError): g("xyz") @override_settings( LANGUAGES=[ ("en", "English"), ("en-latn-us", "Latin English"), ("de", "German"), ("de-1996", "German, orthography of 1996"), ("de-at", "Austrian German"), ("de-ch-1901", "German, Swiss variant, traditional orthography"), ("i-mingo", "Mingo"), ("kl-tunumiit", "Tunumiisiut"), ("nan-hani-tw", "Hanji"), ("pl", "Polish"), ], ) def test_get_language_from_path_real(self): g = trans_real.get_language_from_path tests = [ ("/pl/", "pl"), ("/pl", "pl"), ("/xyz/", None), ("/en/", "en"), ("/en-gb/", "en"), ("/en-latn-us/", "en-latn-us"), ("/en-Latn-US/", "en-Latn-US"), ("/de/", "de"), ("/de-1996/", "de-1996"), ("/de-at/", "de-at"), ("/de-AT/", "de-AT"), ("/de-ch/", "de"), ("/de-ch-1901/", "de-ch-1901"), ("/de-simple-page-test/", None), ("/i-mingo/", "i-mingo"), ("/kl-tunumiit/", "kl-tunumiit"), ("/nan-hani-tw/", "nan-hani-tw"), ] for path, language in tests: with self.subTest(path=path): self.assertEqual(g(path), language) def test_get_language_from_path_null(self): g = trans_null.get_language_from_path self.assertIsNone(g("/pl/")) self.assertIsNone(g("/pl")) self.assertIsNone(g("/xyz/")) def test_cache_resetting(self): """ After setting LANGUAGE, the cache should be cleared and languages previously valid should not be used (#14170). """ g = get_language_from_request request = self.rf.get("/", headers={"accept-language": "pt-br"}) self.assertEqual("pt-br", g(request)) with self.settings(LANGUAGES=[("en", "English")]): self.assertNotEqual("pt-br", g(request)) def test_i18n_patterns_returns_list(self): with override_settings(USE_I18N=False): self.assertIsInstance(i18n_patterns([]), list) with override_settings(USE_I18N=True): self.assertIsInstance(i18n_patterns([]), list) class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): super().setUp() activate("de") def tearDown(self): deactivate() super().tearDown() def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the translation of '%s'; the actual result is " "'%s'." % (msgstr, msgid, result), ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): @override_settings(LANGUAGE_CODE="de") def test_app_translation(self): # Original translation. self.assertGettext("Date/time", "Datum/Zeit") # Different translation. with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}): # Force refreshing translations. activate("de") # Doesn't work because it's added later in the list. self.assertGettext("Date/time", "Datum/Zeit") with self.modify_settings( INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"} ): # Force refreshing translations. activate("de") # Unless the original is removed from the list. self.assertGettext("Date/time", "Datum/Zeit (APP)") @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext("Time", "LOCALE_PATHS") def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=["i18n.resolution"]): self.assertGettext("Time", "LOCALE_PATHS") class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(gettext("Date/time"), "Datum/Zeit") @override_settings(INSTALLED_APPS=["i18n.territorial_fallback"]) class TranslationFallbackI18NTests(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override("de-de"): self.assertGettext("Test 1 (en)", "(de-de)") self.assertGettext("Test 2 (en)", "(de)") class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_paid=12, products_delivered=1) c.name = SafeString("Iñtërnâtiônàlizætiøn1") c.save() class TestLanguageInfo(SimpleTestCase): def test_localized_language_info(self): li = get_language_info("de") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx"): get_language_info("xx") with translation.override("xx"): # A language with no translation catalogs should fallback to the # untranslated string. self.assertEqual(gettext("Title"), "Title") def test_unknown_only_country_code(self): li = get_language_info("de-xx") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code_and_country_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): get_language_info("xx-xx") def test_fallback_language_code(self): """ get_language_info return the first fallback language info if the lang_info struct does not contain the 'name' key. """ li = get_language_info("zh-my") self.assertEqual(li["code"], "zh-hans") li = get_language_info("zh-hans") self.assertEqual(li["code"], "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class LocaleMiddlewareTests(TestCase): def test_streaming_response(self): # Regression test for #5241 response = self.client.get("/fr/streaming/") self.assertContains(response, "Oui/Non") response = self.client.get("/en/streaming/") self.assertContains(response, "Yes/No") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("de", "German"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="en", ) class UnprefixedDefaultLanguageTests(SimpleTestCase): def test_default_lang_without_prefix(self): """ With i18n_patterns(..., prefix_default_language=False), the default language (settings.LANGUAGE_CODE) should be accessible without a prefix. """ response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") def test_other_lang_with_prefix(self): response = self.client.get("/fr/simple/") self.assertEqual(response.content, b"Oui") def test_unprefixed_language_with_accept_language(self): """'Accept-Language' is respected.""" response = self.client.get("/simple/", headers={"accept-language": "fr"}) self.assertRedirects(response, "/fr/simple/") def test_unprefixed_language_with_cookie_language(self): """A language set in the cookies is respected.""" self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "fr"}) response = self.client.get("/simple/") self.assertRedirects(response, "/fr/simple/") def test_unprefixed_language_with_non_valid_language(self): response = self.client.get("/simple/", headers={"accept-language": "fi"}) self.assertEqual(response.content, b"Yes") self.client.cookies.load({settings.LANGUAGE_COOKIE_NAME: "fi"}) response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") def test_page_with_dash(self): # A page starting with /de* shouldn't match the 'de' language code. response = self.client.get("/de-simple-page-test/") self.assertEqual(response.content, b"Yes") def test_no_redirect_on_404(self): """ A request for a nonexistent URL shouldn't cause a redirect to /<default_language>/<request_url> when prefix_default_language=False and /<default_language>/<request_url> has a URL match (#27402). """ # A match for /group1/group2/ must exist for this to act as a # regression test. response = self.client.get("/group1/group2/") self.assertEqual(response.status_code, 200) response = self.client.get("/nonexistent/") self.assertEqual(response.status_code, 404) @override_settings( USE_I18N=True, LANGUAGES=[ ("bg", "Bulgarian"), ("en-us", "English"), ("pt-br", "Portuguese (Brazil)"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class CountrySpecificLanguageTests(SimpleTestCase): rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language("en")) self.assertTrue(check_for_language("en-us")) self.assertTrue(check_for_language("en-US")) self.assertFalse(check_for_language("en_US")) self.assertTrue(check_for_language("be")) self.assertTrue(check_for_language("be@latin")) self.assertTrue(check_for_language("sr-RS@latin")) self.assertTrue(check_for_language("sr-RS@12345")) self.assertFalse(check_for_language("en-ü")) self.assertFalse(check_for_language("en\x00")) self.assertFalse(check_for_language(None)) self.assertFalse(check_for_language("be@ ")) # Specifying encoding is not supported (Django enforces UTF-8) self.assertFalse(check_for_language("tr-TR.UTF-8")) self.assertFalse(check_for_language("tr-TR.UTF8")) self.assertFalse(check_for_language("de-DE.utf-8")) def test_check_for_language_null(self): self.assertIs(trans_null.check_for_language("en"), True) def test_get_language_from_request(self): # issue 19919 request = self.rf.get( "/", headers={"accept-language": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("en-us", lang) request = self.rf.get( "/", headers={"accept-language": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("bg", lang) def test_get_language_from_request_null(self): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, None) def test_specific_language_codes(self): # issue 11915 request = self.rf.get( "/", headers={"accept-language": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("pt-br", lang) request = self.rf.get( "/", headers={"accept-language": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} ) lang = get_language_from_request(request) self.assertEqual("pt-br", lang) class TranslationFilesMissing(SimpleTestCase): def setUp(self): super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None def test_failure_finding_default_mo_files(self): """OSError is raised if the default language is unparseable.""" self.patchGettextFind() trans_real._translations = {} with self.assertRaises(OSError): activate("en") class NonDjangoLanguageTests(SimpleTestCase): """ A language non present in default Django languages can still be installed/used by a Django project. """ @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), ("xxx", "Somelanguage"), ], LANGUAGE_CODE="xxx", LOCALE_PATHS=[os.path.join(here, "commands", "locale")], ) def test_non_django_language(self): self.assertEqual(get_language(), "xxx") self.assertEqual(gettext("year"), "reay") @override_settings(USE_I18N=True) def test_check_for_language(self): with tempfile.TemporaryDirectory() as app_dir: os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES")) open( os.path.join( app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo" ), "w", ).close() app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir])) with mock.patch( "django.apps.apps.get_app_configs", return_value=[app_config] ): self.assertIs(check_for_language("dummy-lang"), True) @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), # xyz language has no locale files ("xyz", "XYZ"), ], ) @translation.override("xyz") def test_plural_non_django_language(self): self.assertEqual(get_language(), "xyz") self.assertEqual(ngettext("year", "years", 2), "years") @override_settings(USE_I18N=True) class WatchForTranslationChangesTests(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / "sampleproject" / "locale" mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") def test_i18n_app_dirs_ignore_django_apps(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["django.contrib.admin"]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / "locale" mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo") class TranslationFileChangedTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext_module._translations.copy() self.trans_real_translations = trans_real._translations.copy() def tearDown(self): gettext._translations = self.gettext_translations trans_real._translations = self.trans_real_translations def test_ignores_non_mo_files(self): gettext_module._translations = {"foo": "bar"} path = Path("test.py") self.assertIsNone(translation_file_changed(None, path)) self.assertEqual(gettext_module._translations, {"foo": "bar"}) def test_resets_cache_with_mo_files(self): gettext_module._translations = {"foo": "bar"} trans_real._translations = {"foo": "bar"} trans_real._default = 1 trans_real._active = False path = Path("test.mo") self.assertIs(translation_file_changed(None, path), True) self.assertEqual(gettext_module._translations, {}) self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, Local) class UtilsTests(SimpleTestCase): def test_round_away_from_one(self): tests = [ (0, 0), (0.0, 0), (0.25, 0), (0.5, 0), (0.75, 0), (1, 1), (1.0, 1), (1.25, 2), (1.5, 2), (1.75, 2), (-0.0, 0), (-0.25, -1), (-0.5, -1), (-0.75, -1), (-1, -1), (-1.0, -1), (-1.25, -2), (-1.5, -2), (-1.75, -2), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(round_away_from_one(value), expected)
9883dac417261caced5784540541a1b9aef1324e1ed5748e2e044162c4d7aa18
import gettext import os import re import zoneinfo from datetime import datetime, timedelta from importlib import import_module from unittest import skipUnless from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import widgets from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.core.files.storage import default_storage from django.core.files.uploadedfile import SimpleUploadedFile from django.db.models import ( CharField, DateField, DateTimeField, ForeignKey, ManyToManyField, UUIDField, ) from django.test import SimpleTestCase, TestCase, override_settings from django.urls import reverse from django.utils import translation from .models import ( Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Image, Individual, Inventory, Member, MyFileField, Profile, ReleaseEvent, School, Student, UnsafeLimitChoicesTo, VideoStream, ) from .widgetadmin import site as widget_admin_site class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email=None ) cls.u2 = User.objects.create_user(username="testser", password="secret") Car.objects.create(owner=cls.superuser, make="Volkswagen", model="Passat") Car.objects.create(owner=cls.u2, make="BMW", model="M3") class AdminFormfieldForDBFieldTests(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. """ # Override any settings on the model admin class MyModelAdmin(admin.ModelAdmin): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) # Construct the admin, and ask it for a formfield ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) # "unwrap" the widget wrapper, if needed if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper): widget = ff.widget.widget else: widget = ff.widget self.assertIsInstance(widget, widgetclass) # Return the formfield so that other tests can continue return ff def test_DateField(self): self.assertFormfield(Event, "start_date", widgets.AdminDateWidget) def test_DateTimeField(self): self.assertFormfield(Member, "birthdate", widgets.AdminSplitDateTime) def test_TimeField(self): self.assertFormfield(Event, "start_time", widgets.AdminTimeWidget) def test_TextField(self): self.assertFormfield(Event, "description", widgets.AdminTextareaWidget) def test_URLField(self): self.assertFormfield(Event, "link", widgets.AdminURLFieldWidget) def test_IntegerField(self): self.assertFormfield(Event, "min_age", widgets.AdminIntegerFieldWidget) def test_CharField(self): self.assertFormfield(Member, "name", widgets.AdminTextInputWidget) def test_EmailField(self): self.assertFormfield(Member, "email", widgets.AdminEmailInputWidget) def test_FileField(self): self.assertFormfield(Album, "cover_art", widgets.AdminFileWidget) def test_ForeignKey(self): self.assertFormfield(Event, "main_band", forms.Select) def test_raw_id_ForeignKey(self): self.assertFormfield( Event, "main_band", widgets.ForeignKeyRawIdWidget, raw_id_fields=["main_band"], ) def test_radio_fields_ForeignKey(self): ff = self.assertFormfield( Event, "main_band", widgets.AdminRadioSelect, radio_fields={"main_band": admin.VERTICAL}, ) self.assertIsNone(ff.empty_label) def test_radio_fields_foreignkey_formfield_overrides_empty_label(self): class MyModelAdmin(admin.ModelAdmin): radio_fields = {"parent": admin.VERTICAL} formfield_overrides = { ForeignKey: {"empty_label": "Custom empty label"}, } ma = MyModelAdmin(Inventory, admin.site) ff = ma.formfield_for_dbfield(Inventory._meta.get_field("parent"), request=None) self.assertEqual(ff.empty_label, "Custom empty label") def test_many_to_many(self): self.assertFormfield(Band, "members", forms.SelectMultiple) def test_raw_id_many_to_many(self): self.assertFormfield( Band, "members", widgets.ManyToManyRawIdWidget, raw_id_fields=["members"] ) def test_filtered_many_to_many(self): self.assertFormfield( Band, "members", widgets.FilteredSelectMultiple, filter_vertical=["members"] ) def test_formfield_overrides(self): self.assertFormfield( Event, "start_date", forms.TextInput, formfield_overrides={DateField: {"widget": forms.TextInput}}, ) def test_formfield_overrides_widget_instances(self): """ Widget instances in formfield_overrides are not shared between different fields. (#19423) """ class BandAdmin(admin.ModelAdmin): formfield_overrides = { CharField: {"widget": forms.TextInput(attrs={"size": "10"})} } ma = BandAdmin(Band, admin.site) f1 = ma.formfield_for_dbfield(Band._meta.get_field("name"), request=None) f2 = ma.formfield_for_dbfield(Band._meta.get_field("style"), request=None) self.assertNotEqual(f1.widget, f2.widget) self.assertEqual(f1.widget.attrs["maxlength"], "100") self.assertEqual(f2.widget.attrs["maxlength"], "20") self.assertEqual(f2.widget.attrs["size"], "10") def test_formfield_overrides_m2m_filter_widget(self): """ The autocomplete_fields, raw_id_fields, filter_vertical, and filter_horizontal widgets for ManyToManyFields may be overridden by specifying a widget in formfield_overrides. """ class BandAdmin(admin.ModelAdmin): filter_vertical = ["members"] formfield_overrides = { ManyToManyField: {"widget": forms.CheckboxSelectMultiple}, } ma = BandAdmin(Band, admin.site) field = ma.formfield_for_dbfield(Band._meta.get_field("members"), request=None) self.assertIsInstance(field.widget.widget, forms.CheckboxSelectMultiple) def test_formfield_overrides_for_datetime_field(self): """ Overriding the widget for DateTimeField doesn't overrides the default form_class for that field (#26449). """ class MemberAdmin(admin.ModelAdmin): formfield_overrides = { DateTimeField: {"widget": widgets.AdminSplitDateTime} } ma = MemberAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield(Member._meta.get_field("birthdate"), request=None) self.assertIsInstance(f1.widget, widgets.AdminSplitDateTime) self.assertIsInstance(f1, forms.SplitDateTimeField) def test_formfield_overrides_for_custom_field(self): """ formfield_overrides works for a custom field class. """ class AlbumAdmin(admin.ModelAdmin): formfield_overrides = {MyFileField: {"widget": forms.TextInput()}} ma = AlbumAdmin(Member, admin.site) f1 = ma.formfield_for_dbfield( Album._meta.get_field("backside_art"), request=None ) self.assertIsInstance(f1.widget, forms.TextInput) def test_field_with_choices(self): self.assertFormfield(Member, "gender", forms.Select) def test_choices_with_radio_fields(self): self.assertFormfield( Member, "gender", widgets.AdminRadioSelect, radio_fields={"gender": admin.VERTICAL}, ) def test_inheritance(self): self.assertFormfield(Album, "backside_art", widgets.AdminFileWidget) def test_m2m_widgets(self): """m2m fields help text as it applies to admin app (#9321).""" class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual( f.help_text, "Hold down “Control”, or “Command” on a Mac, to select more than one.", ) def test_m2m_widgets_no_allow_multiple_selected(self): class NoAllowMultipleSelectedWidget(forms.SelectMultiple): allow_multiple_selected = False class AdvisorAdmin(admin.ModelAdmin): filter_vertical = ["companies"] formfield_overrides = { ManyToManyField: {"widget": NoAllowMultipleSelectedWidget}, } self.assertFormfield( Advisor, "companies", widgets.FilteredSelectMultiple, filter_vertical=["companies"], ) ma = AdvisorAdmin(Advisor, admin.site) f = ma.formfield_for_dbfield(Advisor._meta.get_field("companies"), request=None) self.assertEqual(f.help_text, "") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase): def test_filter_choices_by_request_user(self): """ Ensure the user can only see their own cars in the foreign key dropdown. """ self.client.force_login(self.superuser) response = self.client.get(reverse("admin:admin_widgets_cartire_add")) self.assertNotContains(response, "BMW M3") self.assertContains(response, "Volkswagen Passat") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_changelist_ForeignKey(self): response = self.client.get(reverse("admin:admin_widgets_car_changelist")) self.assertContains(response, "/auth/user/add/") @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_nonexistent_target_id(self): band = Band.objects.create(name="Bogey Blues") pk = band.pk band.delete() post_data = { "main_band": str(pk), } # Try posting with a nonexistent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post(reverse("admin:admin_widgets_event_add"), post_data) self.assertContains( response, "Select a valid choice. That choice is not one of the available choices.", ) def test_invalid_target_id(self): for test_str in ("Iñtërnâtiônàlizætiøn", "1234'", -1234): # This should result in an error message, not a server exception. response = self.client.post( reverse("admin:admin_widgets_event_add"), {"main_band": test_str} ) self.assertContains( response, "Select a valid choice. That choice is not one of the available " "choices.", ) def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({"color__in": ("red", "blue")}) lookup2 = widgets.url_params_from_lookup_dict({"color__in": ["red", "blue"]}) self.assertEqual(lookup1, {"color__in": "red,blue"}) self.assertEqual(lookup1, lookup2) def test_url_params_from_lookup_dict_callable(self): def my_callable(): return "works" lookup1 = widgets.url_params_from_lookup_dict({"myfield": my_callable}) lookup2 = widgets.url_params_from_lookup_dict({"myfield": my_callable()}) self.assertEqual(lookup1, lookup2) def test_label_and_url_for_value_invalid_uuid(self): field = Bee._meta.get_field("honeycomb") self.assertIsInstance(field.target_field, UUIDField) widget = widgets.ForeignKeyRawIdWidget(field.remote_field, admin.site) self.assertEqual(widget.label_and_url_for_value("invalid-uuid"), ("", "")) class FilteredSelectMultipleWidgetTest(SimpleTestCase): def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", False) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilter" ' 'data-field-name="test\\" data-is-stacked="0">\n</select>', ) def test_stacked_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple("test\\", True) self.assertHTMLEqual( w.render("test", "test"), '<select multiple name="test" class="selectfilterstacked" ' 'data-field-name="test\\" data-is-stacked="1">\n</select>', ) class AdminDateWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="vDateField" name="test" ' 'size="10">', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="myDateField" name="test" ' 'size="20">', ) class AdminTimeWidgetTest(SimpleTestCase): def test_attrs(self): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="vTimeField" name="test" ' 'size="8">', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="myTimeField" name="test" ' 'size="20">', ) class AdminSplitDateTimeWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Date: <input value="2007-12-01" type="text" class="vDateField" ' 'name="test_0" size="10"><br>' 'Time: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>', ) def test_localization(self): w = widgets.AdminSplitDateTime() with translation.override("de-at"): w.is_localized = True self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Datum: <input value="01.12.2007" type="text" ' 'class="vDateField" name="test_0"size="10"><br>' 'Zeit: <input value="09:30:00" type="text" class="vTimeField" ' 'name="test_1" size="8"></p>', ) class AdminURLWidgetTest(SimpleTestCase): def test_get_context_validates_url(self): w = widgets.AdminURLFieldWidget() for invalid in ["", "/not/a/full/url/", 'javascript:alert("Danger XSS!")']: with self.subTest(url=invalid): self.assertFalse(w.get_context("name", invalid, {})["url_valid"]) self.assertTrue(w.get_context("name", "http://example.com", {})["url_valid"]) def test_render(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", ""), '<input class="vURLField" name="test" type="url">' ) self.assertHTMLEqual( w.render("test", "http://example.com"), '<p class="url">Currently:<a href="http://example.com">' "http://example.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example.com"></p>', ) def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( w.render("test", "http://example-äüö.com"), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">' "http://example-äüö.com</a><br>" 'Change:<input class="vURLField" name="test" type="url" ' 'value="http://example-äüö.com"></p>', ) def test_render_quoting(self): """ WARNING: This test doesn't use assertHTMLEqual since it will get rid of some escapes which are tested here! """ HREF_RE = re.compile('href="([^"]+)"') VALUE_RE = re.compile('value="([^"]+)"') TEXT_RE = re.compile("<a[^>]+>([^>]+)</a>") w = widgets.AdminURLFieldWidget() output = w.render("test", "http://example.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://example.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render("test", "http://example-äüö.com/<sometag>some-text</sometag>") self.assertEqual( HREF_RE.search(output)[1], "http://xn--example--7za4pnc.com/%3Csometag%3Esome-text%3C/sometag%3E", ) self.assertEqual( TEXT_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://example-äüö.com/&lt;sometag&gt;some-text&lt;/sometag&gt;", ) output = w.render( "test", 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"' ) self.assertEqual( HREF_RE.search(output)[1], "http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)" "%3C/script%3E%22", ) self.assertEqual( TEXT_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) self.assertEqual( VALUE_RE.search(output)[1], "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;" "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;", ) class AdminUUIDWidgetTests(SimpleTestCase): def test_attrs(self): w = widgets.AdminUUIDInputWidget() self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="vUUIDField" name="test">', ) w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"}) self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" ' 'class="myUUIDInput" name="test">', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): super().setUpTestData() band = Band.objects.create(name="Linkin Park") cls.album = band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) def test_render(self): w = widgets.AdminFileWidget() self.assertHTMLEqual( w.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id"> ' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) self.assertHTMLEqual( w.render("test", SimpleUploadedFile("test", b"content")), '<input type="file" name="test">', ) def test_render_required(self): widget = widgets.AdminFileWidget() widget.is_required = True self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a><br>' 'Change: <input type="file" name="test"></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_render_disabled(self): widget = widgets.AdminFileWidget(attrs={"disabled": True}) self.assertHTMLEqual( widget.render("test", self.album.cover_art), '<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/' r'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> ' '<span class="clearable-file-input">' '<input type="checkbox" name="test-clear" id="test-clear_id" disabled>' '<label for="test-clear_id">Clear</label></span><br>' 'Change: <input type="file" name="test" disabled></p>' % { "STORAGE_URL": default_storage.url(""), }, ) def test_readonly_fields(self): """ File widgets should render as a link when they're marked "read only." """ self.client.force_login(self.superuser) response = self.client.get( reverse("admin:admin_widgets_album_change", args=(self.album.id,)) ) self.assertContains( response, '<div class="readonly"><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">' r"albums\hybrid_theory.jpg</a></div>" % {"STORAGE_URL": default_storage.url("")}, html=True, ) self.assertNotContains( response, '<input type="file" name="cover_art" id="id_cover_art">', html=True, ) response = self.client.get(reverse("admin:admin_widgets_album_add")) self.assertContains( response, '<div class="readonly"></div>', html=True, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ForeignKeyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") band.album_set.create( name="Hybrid Theory", cover_art=r"albums\hybrid_theory.jpg" ) rel_uuid = Album._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel_uuid, widget_admin_site) self.assertHTMLEqual( w.render("test", band.uuid, attrs={}), '<input type="text" name="test" value="%(banduuid)s" ' 'class="vForeignKeyRawIdAdminField vUUIDField">' '<a href="/admin_widgets/band/?_to_field=uuid" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>&nbsp;<strong>' '<a href="/admin_widgets/band/%(bandpk)s/change/">Linkin Park</a>' "</strong>" % {"banduuid": band.uuid, "bandpk": band.pk}, ) rel_id = ReleaseEvent._meta.get_field("album").remote_field w = widgets.ForeignKeyRawIdWidget(rel_id, widget_admin_site) self.assertHTMLEqual( w.render("test", None, attrs={}), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/album/?_to_field=id" class="related-lookup" ' 'id="lookup_id_test" title="Lookup"></a>', ) def test_relations_to_non_primary_key(self): # ForeignKeyRawIdWidget works with fields which aren't related to # the model's primary key. apple = Inventory.objects.create(barcode=86, name="Apple") Inventory.objects.create(barcode=22, name="Pear") core = Inventory.objects.create(barcode=87, name="Core", parent=apple) rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", core.parent_id, attrs={}), '<input type="text" name="test" value="86" ' 'class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Apple</a></strong>" % {"pk": apple.pk}, ) def test_fk_related_model_not_in_admin(self): # FK to a model not registered with admin site. Raw ID widget should # have no magnifying glass link. See #16542 big_honeycomb = Honeycomb.objects.create(location="Old tree") big_honeycomb.bee_set.create() rel = Bee._meta.get_field("honeycomb").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("honeycomb_widget", big_honeycomb.pk, attrs={}), '<input type="text" name="honeycomb_widget" value="%(hcombpk)s">' "&nbsp;<strong>%(hcomb)s</strong>" % {"hcombpk": big_honeycomb.pk, "hcomb": big_honeycomb}, ) def test_fk_to_self_model_not_in_admin(self): # FK to self, not registered with admin site. Raw ID widget should have # no magnifying glass link. See #16542 subject1 = Individual.objects.create(name="Subject #1") Individual.objects.create(name="Child", parent=subject1) rel = Individual._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("individual_widget", subject1.pk, attrs={}), '<input type="text" name="individual_widget" value="%(subj1pk)s">' "&nbsp;<strong>%(subj1)s</strong>" % {"subj1pk": subject1.pk, "subj1": subject1}, ) def test_proper_manager_for_label_lookup(self): # see #9258 rel = Inventory._meta.get_field("parent").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) hidden = Inventory.objects.create(barcode=93, name="Hidden", hidden=True) child_of_hidden = Inventory.objects.create( barcode=94, name="Child of hidden", parent=hidden ) self.assertHTMLEqual( w.render("test", child_of_hidden.parent_id, attrs={}), '<input type="text" name="test" value="93" ' ' class="vForeignKeyRawIdAdminField">' '<a href="/admin_widgets/inventory/?_to_field=barcode" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>' '&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">' "Hidden</a></strong>" % {"pk": hidden.pk}, ) def test_render_unsafe_limit_choices_to(self): rel = UnsafeLimitChoicesTo._meta.get_field("band").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n' '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;' '_to_field=artist_ptr" class="related-lookup" id="lookup_id_test" ' 'title="Lookup"></a>', ) def test_render_fk_as_pk_model(self): rel = VideoStream._meta.get_field("release_event").remote_field w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", None), '<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n' '<a href="/admin_widgets/releaseevent/?_to_field=album" ' 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>', ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class ManyToManyRawIdWidgetTest(TestCase): def test_render(self): band = Band.objects.create(name="Linkin Park") m1 = Member.objects.create(name="Chester") m2 = Member.objects.create(name="Mike") band.members.add(m1, m2) rel = Band._meta.get_field("members").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("test", [m1.pk, m2.pk], attrs={}), ( '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" ' ' class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" ' ' id="lookup_id_test" title="Lookup"></a>' ) % {"m1pk": m1.pk, "m2pk": m2.pk}, ) self.assertHTMLEqual( w.render("test", [m1.pk]), ( '<input type="text" name="test" value="%(m1pk)s" ' ' class="vManyToManyRawIdAdminField">' '<a href="/admin_widgets/member/" class="related-lookup" ' ' id="lookup_id_test" title="Lookup"></a>' ) % {"m1pk": m1.pk}, ) def test_m2m_related_model_not_in_admin(self): # M2M relationship with model not registered with admin site. Raw ID # widget should have no magnifying glass link. See #16542 consultor1 = Advisor.objects.create(name="Rockstar Techie") c1 = Company.objects.create(name="Doodle") c2 = Company.objects.create(name="Pear") consultor1.companies.add(c1, c2) rel = Advisor._meta.get_field("companies").remote_field w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) self.assertHTMLEqual( w.render("company_widget1", [c1.pk, c2.pk], attrs={}), '<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s">' % {"c1pk": c1.pk, "c2pk": c2.pk}, ) self.assertHTMLEqual( w.render("company_widget2", [c1.pk]), '<input type="text" name="company_widget2" value="%(c1pk)s">' % {"c1pk": c1.pk}, ) @override_settings(ROOT_URLCONF="admin_widgets.urls") class RelatedFieldWidgetWrapperTests(SimpleTestCase): def test_no_can_add_related(self): rel = Individual._meta.get_field("parent").remote_field w = widgets.AdminRadioSelect() # Used to fail with a name error. w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site) self.assertFalse(w.can_add_related) def test_select_multiple_widget_cant_change_delete_related(self): rel = Individual._meta.get_field("parent").remote_field widget = forms.SelectMultiple() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertFalse(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_on_delete_cascade_rel_cant_delete_related(self): rel = Individual._meta.get_field("soulmate").remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) self.assertTrue(wrapper.can_add_related) self.assertTrue(wrapper.can_change_related) self.assertFalse(wrapper.can_delete_related) def test_custom_widget_render(self): class CustomWidget(forms.Select): def render(self, *args, **kwargs): return "custom render output" rel = Album._meta.get_field("band").remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper( widget, rel, widget_admin_site, can_add_related=True, can_change_related=True, can_delete_related=True, ) output = wrapper.render("name", "value") self.assertIn("custom render output", output) def test_widget_delegates_value_omitted_from_data(self): class CustomWidget(forms.Select): def value_omitted_from_data(self, data, files, name): return False rel = Album._meta.get_field("band").remote_field widget = CustomWidget() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.value_omitted_from_data({}, {}, "band"), False) def test_widget_is_hidden(self): rel = Album._meta.get_field("band").remote_field widget = forms.HiddenInput() widget.choices = () wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, True) context = wrapper.get_context("band", None, {}) self.assertIs(context["is_hidden"], True) output = wrapper.render("name", "value") # Related item links are hidden. self.assertNotIn("<a ", output) def test_widget_is_not_hidden(self): rel = Album._meta.get_field("band").remote_field widget = forms.Select() wrapper = widgets.RelatedFieldWidgetWrapper(widget, rel, widget_admin_site) self.assertIs(wrapper.is_hidden, False) context = wrapper.get_context("band", None, {}) self.assertIs(context["is_hidden"], False) output = wrapper.render("name", "value") # Related item links are present. self.assertIn("<a ", output) @override_settings(ROOT_URLCONF="admin_widgets.urls") class AdminWidgetSeleniumTestCase(AdminSeleniumTestCase): available_apps = ["admin_widgets"] + AdminSeleniumTestCase.available_apps def setUp(self): self.u1 = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): def test_show_hide_date_time_picker_widgets(self): """ Pressing the ESC key or clicking on a widget value closes the date and time picker widgets. """ from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # First, with the date picker widget --------------------------------- cal_icon = self.selenium.find_element(By.ID, "calendarlink0") # The date picker is hidden self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Click the calendar icon cal_icon.click() # The date picker is visible self.assertTrue( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Press the ESC key self.selenium.find_element(By.TAG_NAME, "body").send_keys([Keys.ESCAPE]) # The date picker is hidden again self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) # Click the calendar icon, then on the 15th of current month cal_icon.click() self.selenium.find_element(By.XPATH, "//a[contains(text(), '15')]").click() self.assertFalse( self.selenium.find_element(By.ID, "calendarbox0").is_displayed() ) self.assertEqual( self.selenium.find_element(By.ID, "id_birthdate_0").get_attribute("value"), datetime.today().strftime("%Y-%m-") + "15", ) # Then, with the time picker widget ---------------------------------- time_icon = self.selenium.find_element(By.ID, "clocklink0") # The time picker is hidden self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) # Click the time icon time_icon.click() # The time picker is visible self.assertTrue(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) self.assertEqual( [ x.text for x in self.selenium.find_elements( By.XPATH, "//ul[@class='timelist']/li/a" ) ], ["Now", "Midnight", "6 a.m.", "Noon", "6 p.m."], ) # Press the ESC key self.selenium.find_element(By.TAG_NAME, "body").send_keys([Keys.ESCAPE]) # The time picker is hidden again self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) # Click the time icon, then select the 'Noon' value time_icon.click() self.selenium.find_element(By.XPATH, "//a[contains(text(), 'Noon')]").click() self.assertFalse(self.selenium.find_element(By.ID, "clockbox0").is_displayed()) self.assertEqual( self.selenium.find_element(By.ID, "id_birthdate_1").get_attribute("value"), "12:00:00", ) def test_calendar_nonday_class(self): """ Ensure cells that are not days of the month have the `nonday` CSS class. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # fill in the birth date. self.selenium.find_element(By.ID, "id_birthdate_0").send_keys("2013-06-01") # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # make sure the first and last 6 cells have class nonday for td in tds[:6] + tds[-6:]: self.assertEqual(td.get_attribute("class"), "nonday") def test_calendar_selected_class(self): """ Ensure cell for the day in the input has the `selected` CSS class. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # fill in the birth date. self.selenium.find_element(By.ID, "id_birthdate_0").send_keys("2013-06-01") # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # verify the selected cell selected = tds[6] self.assertEqual(selected.get_attribute("class"), "selected") self.assertEqual(selected.text, "1") def test_calendar_no_selected_class(self): """ Ensure no cells are given the selected class when the field is empty. Refs #4574. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") # Open a page that has a date and time picker widgets self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) # Click the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # get all the tds within the calendar calendar0 = self.selenium.find_element(By.ID, "calendarin0") tds = calendar0.find_elements(By.TAG_NAME, "td") # verify there are no cells with the selected class selected = [td for td in tds if td.get_attribute("class") == "selected"] self.assertEqual(len(selected), 0) def test_calendar_show_date_from_input(self): """ The calendar shows the date from the input field for every locale supported by Django. """ from selenium.webdriver.common.by import By self.selenium.set_window_size(1024, 768) self.admin_login(username="super", password="secret", login_url="/") # Enter test data member = Member.objects.create( name="Bob", birthdate=datetime(1984, 5, 15), gender="M" ) # Get month name translations for every locale month_string = "May" path = os.path.join( os.path.dirname(import_module("django.contrib.admin").__file__), "locale" ) for language_code, language_name in settings.LANGUAGES: try: catalog = gettext.translation("djangojs", path, [language_code]) except OSError: continue if month_string in catalog._catalog: month_name = catalog._catalog[month_string] else: month_name = month_string # Get the expected caption may_translation = month_name expected_caption = "{:s} {:d}".format(may_translation.upper(), 1984) # Test with every locale with override_settings(LANGUAGE_CODE=language_code): # Open a page that has a date picker widget url = reverse("admin:admin_widgets_member_change", args=(member.pk,)) self.selenium.get(self.live_server_url + url) # Click on the calendar icon self.selenium.find_element(By.ID, "calendarlink0").click() # Make sure that the right month and year are displayed self.wait_for_text("#calendarin0 caption", expected_caption) @override_settings(TIME_ZONE="Asia/Singapore") class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase): def test_date_time_picker_shortcuts(self): """ date/time/datetime picker shortcuts work in the current time zone. Refs #20663. This test case is fairly tricky, it relies on selenium still running the browser in the default time zone "America/Chicago" despite `override_settings` changing the time zone to "Asia/Singapore". """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") error_margin = timedelta(seconds=10) # If we are neighbouring a DST, we add an hour of error margin. tz = zoneinfo.ZoneInfo("America/Chicago") utc_now = datetime.now(zoneinfo.ZoneInfo("UTC")) tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname() tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname() if tz_yesterday != tz_tomorrow: error_margin += timedelta(hours=1) self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_member_add") ) self.selenium.find_element(By.ID, "id_name").send_keys("test") # Click on the "today" and "now" shortcuts. shortcuts = self.selenium.find_elements( By.CSS_SELECTOR, ".field-birthdate .datetimeshortcuts" ) now = datetime.now() for shortcut in shortcuts: shortcut.find_element(By.TAG_NAME, "a").click() # There is a time zone mismatch warning. # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. self.assertCountSeleniumElements(".field-birthdate .timezonewarning", 1) # Submit the form. with self.wait_page_loaded(): self.selenium.find_element(By.NAME, "_save").click() # Make sure that "now" in JavaScript is within 10 seconds # from "now" on the server side. member = Member.objects.get(name="test") self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) # The above tests run with Asia/Singapore which are on the positive side of # UTC. Here we test with a timezone on the negative side. @override_settings(TIME_ZONE="US/Eastern") class DateTimePickerAltTimezoneSeleniumTests(DateTimePickerShortcutsSeleniumTests): pass class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() self.lisa = Student.objects.create(name="Lisa") self.john = Student.objects.create(name="John") self.bob = Student.objects.create(name="Bob") self.peter = Student.objects.create(name="Peter") self.jenny = Student.objects.create(name="Jenny") self.jason = Student.objects.create(name="Jason") self.cliff = Student.objects.create(name="Cliff") self.arthur = Student.objects.create(name="Arthur") self.school = School.objects.create(name="School of Awesome") def assertActiveButtons( self, mode, field_name, choose, remove, choose_all=None, remove_all=None ): choose_link = "#id_%s_add_link" % field_name choose_all_link = "#id_%s_add_all_link" % field_name remove_link = "#id_%s_remove_link" % field_name remove_all_link = "#id_%s_remove_all_link" % field_name self.assertEqual(self.has_css_class(choose_link, "active"), choose) self.assertEqual(self.has_css_class(remove_link, "active"), remove) if mode == "horizontal": self.assertEqual(self.has_css_class(choose_all_link, "active"), choose_all) self.assertEqual(self.has_css_class(remove_all_link, "active"), remove_all) def execute_basic_operations(self, mode, field_name): from selenium.webdriver.common.by import By original_url = self.selenium.current_url from_box = "#id_%s_from" % field_name to_box = "#id_%s_to" % field_name choose_link = "id_%s_add_link" % field_name choose_all_link = "id_%s_add_all_link" % field_name remove_link = "id_%s_remove_link" % field_name remove_all_link = "id_%s_remove_all_link" % field_name # Initial positions --------------------------------------------------- self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- if mode == "horizontal": self.selenium.find_element(By.ID, choose_all_link).click() elif mode == "vertical": # There 's no 'Choose all' button in vertical mode, so individually # select all options and click 'Choose'. for option in self.selenium.find_elements( By.CSS_SELECTOR, from_box + " > option" ): option.click() self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions(from_box, []) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- if mode == "horizontal": self.selenium.find_element(By.ID, remove_all_link).click() elif mode == "vertical": # There 's no 'Remove all' button in vertical mode, so individually # select all options and click 'Remove'. for option in self.selenium.find_elements( By.CSS_SELECTOR, to_box + " > option" ): option.click() self.selenium.find_element(By.ID, remove_link).click() self.assertSelectOptions( from_box, [ str(self.lisa.id), str(self.peter.id), str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) # Choose some options ------------------------------------------------ from_lisa_select_option = self.selenium.find_element( By.CSS_SELECTOR, '{} > option[value="{}"]'.format(from_box, self.lisa.id) ) # Check the title attribute is there for tool tips: ticket #20821 self.assertEqual( from_lisa_select_option.get_attribute("title"), from_lisa_select_option.get_attribute("text"), ) self.select_option(from_box, str(self.lisa.id)) self.select_option(from_box, str(self.jason.id)) self.select_option(from_box, str(self.bob.id)) self.select_option(from_box, str(self.john.id)) self.assertActiveButtons(mode, field_name, True, False, True, False) self.selenium.find_element(By.ID, choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), ], ) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.bob.id), str(self.jason.id), str(self.john.id), ], ) # Check the tooltip is still there after moving: ticket #20821 to_lisa_select_option = self.selenium.find_element( By.CSS_SELECTOR, '{} > option[value="{}"]'.format(to_box, self.lisa.id) ) self.assertEqual( to_lisa_select_option.get_attribute("title"), to_lisa_select_option.get_attribute("text"), ) # Remove some options ------------------------------------------------- self.select_option(to_box, str(self.lisa.id)) self.select_option(to_box, str(self.bob.id)) self.assertActiveButtons(mode, field_name, False, True, True, True) self.selenium.find_element(By.ID, remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.arthur.id), str(self.cliff.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ], ) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.select_option(from_box, str(self.arthur.id)) self.select_option(from_box, str(self.cliff.id)) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions( from_box, [ str(self.peter.id), str(self.jenny.id), str(self.lisa.id), str(self.bob.id), ], ) self.assertSelectOptions( to_box, [ str(self.jason.id), str(self.john.id), str(self.arthur.id), str(self.cliff.id), ], ) # Choose some more options -------------------------------------------- self.select_option(from_box, str(self.peter.id)) self.select_option(from_box, str(self.lisa.id)) # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) self.selenium.find_element(By.ID, remove_link).click() self.assertSelectedOptions(from_box, [str(self.peter.id), str(self.lisa.id)]) # Unselect the options ------------------------------------------------ self.deselect_option(from_box, str(self.peter.id)) self.deselect_option(from_box, str(self.lisa.id)) # Choose some more options -------------------------------------------- self.select_option(to_box, str(self.jason.id)) self.select_option(to_box, str(self.john.id)) # Confirm they're selected after clicking inactive buttons: ticket #26575 self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectedOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Unselect the options ------------------------------------------------ self.deselect_option(to_box, str(self.jason.id)) self.deselect_option(to_box, str(self.john.id)) # Pressing buttons shouldn't change the URL. self.assertEqual(self.selenium.current_url, original_url) def test_basic(self): from selenium.webdriver.common.by import By self.selenium.set_window_size(1024, 768) self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_school_change", args=(self.school.id,)) ) self.wait_page_ready() self.execute_basic_operations("vertical", "students") self.execute_basic_operations("horizontal", "alumni") # Save and check that everything is properly stored in the database --- self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_page_ready() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual( list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john], ) self.assertEqual( list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john], ) def test_filter(self): """ Typing in the search box filters out options displayed in the 'from' box. """ from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.selenium.set_window_size(1024, 768) self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_school_change", args=(self.school.id,)) ) for field_name in ["students", "alumni"]: from_box = "#id_%s_from" % field_name to_box = "#id_%s_to" % field_name choose_link = "id_%s_add_link" % field_name remove_link = "id_%s_remove_link" % field_name input = self.selenium.find_element(By.ID, "id_%s_input" % field_name) # Initial values self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) # Typing in some characters filters out non-matching options input.send_keys("a") self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) input.send_keys("R") self.assertSelectOptions(from_box, [str(self.arthur.id)]) # Clearing the text box makes the other options reappear input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ], ) # ----------------------------------------------------------------- # Choosing a filtered option sends it properly to the 'to' box. input.send_keys("a") self.assertSelectOptions( from_box, [str(self.arthur.id), str(self.jason.id)] ) self.select_option(from_box, str(self.jason.id)) self.selenium.find_element(By.ID, choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions( to_box, [ str(self.lisa.id), str(self.peter.id), str(self.jason.id), ], ) self.select_option(to_box, str(self.lisa.id)) self.selenium.find_element(By.ID, remove_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions( from_box, [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), str(self.john.id), str(self.lisa.id), ], ) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # ----------------------------------------------------------------- # Pressing enter on a filtered option sends it properly to # the 'to' box. self.select_option(to_box, str(self.jason.id)) self.selenium.find_element(By.ID, remove_link).click() input.send_keys("ja") self.assertSelectOptions(from_box, [str(self.jason.id)]) input.send_keys([Keys.ENTER]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE]) # Save and check that everything is properly stored in the database --- with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.school = School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) def test_back_button_bug(self): """ Some browsers had a bug where navigating away from the change page and then clicking the browser's back button would clear the filter_horizontal/filter_vertical widgets (#13614). """ from selenium.webdriver.common.by import By self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username="super", password="secret", login_url="/") change_url = reverse( "admin:admin_widgets_school_change", args=(self.school.id,) ) self.selenium.get(self.live_server_url + change_url) # Navigate away and go back to the change form page. self.selenium.find_element(By.LINK_TEXT, "Home").click() self.selenium.back() expected_unselected_values = [ str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jason.id), str(self.jenny.id), str(self.john.id), ] expected_selected_values = [str(self.lisa.id), str(self.peter.id)] # Everything is still in place self.assertSelectOptions("#id_students_from", expected_unselected_values) self.assertSelectOptions("#id_students_to", expected_selected_values) self.assertSelectOptions("#id_alumni_from", expected_unselected_values) self.assertSelectOptions("#id_alumni_to", expected_selected_values) def test_refresh_page(self): """ Horizontal and vertical filter widgets keep selected options on page reload (#22955). """ self.school.students.add(self.arthur, self.jason) self.school.alumni.add(self.arthur, self.jason) self.admin_login(username="super", password="secret", login_url="/") change_url = reverse( "admin:admin_widgets_school_change", args=(self.school.id,) ) self.selenium.get(self.live_server_url + change_url) self.assertCountSeleniumElements("#id_students_to > option", 2) # self.selenium.refresh() or send_keys(Keys.F5) does hard reload and # doesn't replicate what happens when a user clicks the browser's # 'Refresh' button. with self.wait_page_loaded(): self.selenium.execute_script("location.reload()") self.assertCountSeleniumElements("#id_students_to > option", 2) class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def setUp(self): super().setUp() Band.objects.create(id=42, name="Bogey Blues") Band.objects.create(id=98, name="Green Potatoes") def test_ForeignKey(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_event_add") ) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element(By.ID, "id_main_band").get_attribute("value"), "" ) # Open the popup window and click on a band self.selenium.find_element(By.ID, "lookup_id_main_band").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Bogey Blues") self.assertIn("/band/42/", link.get_attribute("href")) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_main_band", "42") # Reopen the popup window and click on another band self.selenium.find_element(By.ID, "lookup_id_main_band").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Green Potatoes") self.assertIn("/band/98/", link.get_attribute("href")) link.click() # The field now contains the other selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_main_band", "98") def test_many_to_many(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_event_add") ) main_window = self.selenium.current_window_handle # No value has been selected yet self.assertEqual( self.selenium.find_element(By.ID, "id_supporting_bands").get_attribute( "value" ), "", ) # Help text for the field is displayed self.assertEqual( self.selenium.find_element( By.CSS_SELECTOR, ".field-supporting_bands div.help" ).text, "Supporting Bands.", ) # Open the popup window and click on a band self.selenium.find_element(By.ID, "lookup_id_supporting_bands").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Bogey Blues") self.assertIn("/band/42/", link.get_attribute("href")) link.click() # The field now contains the selected band's id self.selenium.switch_to.window(main_window) self.wait_for_value("#id_supporting_bands", "42") # Reopen the popup window and click on another band self.selenium.find_element(By.ID, "lookup_id_supporting_bands").click() self.wait_for_and_switch_to_popup() link = self.selenium.find_element(By.LINK_TEXT, "Green Potatoes") self.assertIn("/band/98/", link.get_attribute("href")) link.click() # The field now contains the two selected bands' ids self.selenium.switch_to.window(main_window) self.wait_for_value("#id_supporting_bands", "42,98") class RelatedFieldWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_ForeignKey_using_to_field(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_profile_add") ) main_window = self.selenium.current_window_handle # Click the Add User button to add new self.selenium.find_element(By.ID, "add_id_user").click() self.wait_for_and_switch_to_popup() password_field = self.selenium.find_element(By.ID, "id_password") password_field.send_keys("password") username_field = self.selenium.find_element(By.ID, "id_username") username_value = "newuser" username_field.send_keys(username_value) save_button_css_selector = ".submit-row > input[type=submit]" self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.selenium.switch_to.window(main_window) # The field now contains the new user self.selenium.find_element(By.CSS_SELECTOR, "#id_user option[value=newuser]") self.selenium.find_element(By.ID, "view_id_user").click() self.wait_for_value("#id_username", "newuser") self.selenium.back() # Chrome and Safari don't update related object links when selecting # the same option as previously submitted. As a consequence, the # "pencil" and "eye" buttons remain disable, so select "---------" # first. select = Select(self.selenium.find_element(By.ID, "id_user")) select.select_by_index(0) select.select_by_value("newuser") # Click the Change User button to change it self.selenium.find_element(By.ID, "change_id_user").click() self.wait_for_and_switch_to_popup() username_field = self.selenium.find_element(By.ID, "id_username") username_value = "changednewuser" username_field.clear() username_field.send_keys(username_value) save_button_css_selector = ".submit-row > input[type=submit]" self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.selenium.switch_to.window(main_window) self.selenium.find_element( By.CSS_SELECTOR, "#id_user option[value=changednewuser]" ) self.selenium.find_element(By.ID, "view_id_user").click() self.wait_for_value("#id_username", "changednewuser") self.selenium.back() select = Select(self.selenium.find_element(By.ID, "id_user")) select.select_by_value("changednewuser") # Go ahead and submit the form to make sure it works self.selenium.find_element(By.CSS_SELECTOR, save_button_css_selector).click() self.wait_for_text( "li.success", "The profile “changednewuser” was added successfully." ) profiles = Profile.objects.all() self.assertEqual(len(profiles), 1) self.assertEqual(profiles[0].user.username, username_value) @skipUnless(Image, "Pillow not installed") class ImageFieldWidgetsSeleniumTests(AdminWidgetSeleniumTestCase): def test_clearablefileinput_widget(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret", login_url="/") self.selenium.get( self.live_server_url + reverse("admin:admin_widgets_student_add"), ) photo_input_id = "id_photo" save_and_edit_button_css_selector = "input[value='Save and continue editing']" tests_files_folder = "%s/files" % os.getcwd() clear_checkbox_id = "photo-clear_id" def _submit_and_wait(): with self.wait_page_loaded(): self.selenium.find_element( By.CSS_SELECTOR, save_and_edit_button_css_selector ).click() # Add a student. title_input = self.selenium.find_element(By.ID, "id_name") title_input.send_keys("Joe Doe") photo_input = self.selenium.find_element(By.ID, photo_input_id) photo_input.send_keys(f"{tests_files_folder}/test.png") _submit_and_wait() student = Student.objects.last() self.assertEqual(student.name, "Joe Doe") self.assertEqual(student.photo.name, "photos/test.png") # Uploading non-image files is not supported by Safari with Selenium, # so upload a broken one instead. photo_input = self.selenium.find_element(By.ID, photo_input_id) photo_input.send_keys(f"{tests_files_folder}/brokenimg.png") _submit_and_wait() self.assertEqual( self.selenium.find_element(By.CSS_SELECTOR, ".errorlist li").text, ( "Upload a valid image. The file you uploaded was either not an image " "or a corrupted image." ), ) # "Currently" with "Clear" checkbox and "Change" still shown. cover_field_row = self.selenium.find_element(By.CSS_SELECTOR, ".field-photo") self.assertIn("Currently", cover_field_row.text) self.assertIn("Change", cover_field_row.text) # "Clear" box works. self.selenium.find_element(By.ID, clear_checkbox_id).click() _submit_and_wait() student.refresh_from_db() self.assertEqual(student.name, "Joe Doe") self.assertEqual(student.photo.name, "")
64c4717b80a20d47542c366b8d0f180a23cbf5ea041ce6b56b6b3155c866e972
from django.core.exceptions import ValidationError from django.forms import FloatField, NumberInput from django.test import SimpleTestCase from django.test.selenium import SeleniumTestCase from django.test.utils import override_settings from django.urls import reverse from django.utils import formats, translation from . import FormFieldAssertionsMixin class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_floatfield_1(self): f = FloatField() self.assertWidgetRendersTo( f, '<input step="any" type="number" name="f" id="id_f" required>' ) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual(1.0, f.clean("1")) self.assertIsInstance(f.clean("1"), float) self.assertEqual(23.0, f.clean("23")) self.assertEqual(3.1400000000000001, f.clean("3.14")) self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(42.0, f.clean(42)) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("a") self.assertEqual(1.0, f.clean("1.0 ")) self.assertEqual(1.0, f.clean(" 1.0")) self.assertEqual(1.0, f.clean(" 1.0 ")) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("1.0a") self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("Infinity") with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("NaN") with self.assertRaisesMessage(ValidationError, "'Enter a number.'"): f.clean("-Inf") def test_floatfield_2(self): f = FloatField(required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertEqual(1.0, f.clean("1")) self.assertIsNone(f.max_value) self.assertIsNone(f.min_value) def test_floatfield_3(self): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo( f, '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" ' "required>", ) with self.assertRaisesMessage( ValidationError, "'Ensure this value is less than or equal to 1.5.'" ): f.clean("1.6") with self.assertRaisesMessage( ValidationError, "'Ensure this value is greater than or equal to 0.5.'" ): f.clean("0.4") self.assertEqual(1.5, f.clean("1.5")) self.assertEqual(0.5, f.clean("0.5")) self.assertEqual(f.max_value, 1.5) self.assertEqual(f.min_value, 0.5) def test_floatfield_4(self): f = FloatField(step_size=0.02) self.assertWidgetRendersTo( f, '<input name="f" step="0.02" type="number" id="id_f" required>', ) msg = "'Ensure this value is a multiple of step size 0.02.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("0.01") self.assertEqual(2.34, f.clean("2.34")) self.assertEqual(2.1, f.clean("2.1")) self.assertEqual(-0.50, f.clean("-.5")) self.assertEqual(-1.26, f.clean("-1.26")) self.assertEqual(f.step_size, 0.02) def test_floatfield_widget_attrs(self): f = FloatField(widget=NumberInput(attrs={"step": 0.01, "max": 1.0, "min": 0.0})) self.assertWidgetRendersTo( f, '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" ' "required>", ) def test_floatfield_localized(self): """ A localized FloatField's widget renders to a text input without any number input specific attributes. """ f = FloatField(localize=True) self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required>') def test_floatfield_changed(self): f = FloatField() n = 4.35 self.assertFalse(f.has_changed(n, "4.3500")) with translation.override("fr"): f = FloatField(localize=True) localized_n = formats.localize_input(n) # -> '4,35' in French self.assertFalse(f.has_changed(n, localized_n)) @override_settings(DECIMAL_SEPARATOR=",") def test_floatfield_support_decimal_separator(self): with translation.override(None): f = FloatField(localize=True) self.assertEqual(f.clean("1001,10"), 1001.10) self.assertEqual(f.clean("1001.10"), 1001.10) @override_settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR=".", ) def test_floatfield_support_thousands_separator(self): with translation.override(None): f = FloatField(localize=True) self.assertEqual(f.clean("1.001,10"), 1001.10) msg = "'Enter a number.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("1,001.1") @override_settings(ROOT_URLCONF="forms_tests.urls") class FloatFieldHTMLTest(SeleniumTestCase): available_apps = ["forms_tests"] def test_float_field_rendering_passes_client_side_validation(self): """ Rendered widget allows non-integer value with the client-side validation. """ from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("form_view")) number_input = self.selenium.find_element(By.ID, "id_number") number_input.send_keys("0.5") is_valid = self.selenium.execute_script( "return document.getElementById('id_number').checkValidity()" ) self.assertTrue(is_valid)
2f53ddb268bec6f016ffdf68ea241132cb29e1ed4d2a7c163c6314aa52bba334
import json import math import re from decimal import Decimal from django.contrib.gis.db.models import GeometryField, PolygonField, functions from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon, fromstr from django.contrib.gis.measure import Area from django.db import NotSupportedError, connection from django.db.models import IntegerField, Sum, Value from django.test import TestCase, skipUnlessDBFeature from ..utils import FuncTestMixin from .models import City, Country, CountryWebMercator, State, Track class GISFunctionsTests(FuncTestMixin, TestCase): """ Testing functions from django/contrib/gis/db/models/functions.py. Area/Distance/Length/Perimeter are tested in distapp/tests. Please keep the tests in function's alphabetic order. """ fixtures = ["initial"] def test_asgeojson(self): if not connection.features.has_AsGeoJSON_function: with self.assertRaises(NotSupportedError): list(Country.objects.annotate(json=functions.AsGeoJSON("mpoly"))) return pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' houston_json = json.loads( '{"type":"Point","crs":{"type":"name","properties":' '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}' ) victoria_json = json.loads( '{"type":"Point",' '"bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],' '"coordinates":[-123.305196,48.462611]}' ) chicago_json = json.loads( '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},' '"bbox":[-87.65018,41.85039,-87.65018,41.85039],' '"coordinates":[-87.65018,41.85039]}' ) if "crs" in connection.features.unsupported_geojson_options: del houston_json["crs"] del chicago_json["crs"] if "bbox" in connection.features.unsupported_geojson_options: del chicago_json["bbox"] del victoria_json["bbox"] if "precision" in connection.features.unsupported_geojson_options: chicago_json["coordinates"] = [-87.650175, 41.850385] # Precision argument should only be an integer with self.assertRaises(TypeError): City.objects.annotate(geojson=functions.AsGeoJSON("point", precision="foo")) # Reference queries and values. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo'; self.assertJSONEqual( pueblo_json, City.objects.annotate(geojson=functions.AsGeoJSON("point")) .get(name="Pueblo") .geojson, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we want to include the CRS by using the `crs` keyword. self.assertJSONEqual( City.objects.annotate(json=functions.AsGeoJSON("point", crs=True)) .get(name="Houston") .json, houston_json, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Houston'; # This time we include the bounding box by using the `bbox` keyword. self.assertJSONEqual( City.objects.annotate(geojson=functions.AsGeoJSON("point", bbox=True)) .get(name="Victoria") .geojson, victoria_json, ) # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city" # WHERE "geoapp_city"."name" = 'Chicago'; # Finally, we set every available keyword. # MariaDB doesn't limit the number of decimals in bbox. if connection.ops.mariadb: chicago_json["bbox"] = [-87.650175, 41.850385, -87.650175, 41.850385] try: self.assertJSONEqual( City.objects.annotate( geojson=functions.AsGeoJSON( "point", bbox=True, crs=True, precision=5 ) ) .get(name="Chicago") .geojson, chicago_json, ) except AssertionError: # Give a second chance with different coords rounding. chicago_json["coordinates"][1] = 41.85038 self.assertJSONEqual( City.objects.annotate( geojson=functions.AsGeoJSON( "point", bbox=True, crs=True, precision=5 ) ) .get(name="Chicago") .geojson, chicago_json, ) @skipUnlessDBFeature("has_AsGML_function") def test_asgml(self): # Should throw a TypeError when trying to obtain GML from a # non-geometry field. qs = City.objects.all() with self.assertRaises(TypeError): qs.annotate(gml=functions.AsGML("name")) ptown = City.objects.annotate(gml=functions.AsGML("point", precision=9)).get( name="Pueblo" ) if connection.ops.oracle: # No precision parameter for Oracle :-/ gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326" ' r'xmlns:gml="http://www.opengis.net/gml">' r'<gml:coordinates decimal="\." cs="," ts=" ">' r"-104.60925\d+,38.25500\d+ " r"</gml:coordinates></gml:Point>" ) else: gml_regex = re.compile( r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>' r"-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>" ) self.assertTrue(gml_regex.match(ptown.gml)) self.assertIn( '<gml:pos srsDimension="2">', City.objects.annotate(gml=functions.AsGML("point", version=3)) .get(name="Pueblo") .gml, ) @skipUnlessDBFeature("has_AsKML_function") def test_askml(self): # Should throw a TypeError when trying to obtain KML from a # non-geometry field. with self.assertRaises(TypeError): City.objects.annotate(kml=functions.AsKML("name")) # Ensuring the KML is as expected. ptown = City.objects.annotate(kml=functions.AsKML("point", precision=9)).get( name="Pueblo" ) self.assertEqual( "<Point><coordinates>-104.609252,38.255001</coordinates></Point>", ptown.kml ) @skipUnlessDBFeature("has_AsSVG_function") def test_assvg(self): with self.assertRaises(TypeError): City.objects.annotate(svg=functions.AsSVG("point", precision="foo")) # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; svg1 = 'cx="-104.609252" cy="-38.255001"' # Even though relative, only one point so it's practically the same except for # the 'c' letter prefix on the x,y values. svg2 = svg1.replace("c", "") self.assertEqual( svg1, City.objects.annotate(svg=functions.AsSVG("point")).get(name="Pueblo").svg, ) self.assertEqual( svg2, City.objects.annotate(svg=functions.AsSVG("point", relative=5)) .get(name="Pueblo") .svg, ) @skipUnlessDBFeature("has_AsWKB_function") def test_aswkb(self): wkb = ( City.objects.annotate( wkb=functions.AsWKB(Point(1, 2, srid=4326)), ) .first() .wkb ) # WKB is either XDR or NDR encoded. self.assertIn( bytes(wkb), ( b"\x00\x00\x00\x00\x01?\xf0\x00\x00\x00\x00\x00\x00@\x00\x00" b"\x00\x00\x00\x00\x00", b"\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0?\x00\x00" b"\x00\x00\x00\x00\x00@", ), ) @skipUnlessDBFeature("has_AsWKT_function") def test_aswkt(self): wkt = ( City.objects.annotate( wkt=functions.AsWKT(Point(1, 2, srid=4326)), ) .first() .wkt ) self.assertEqual( wkt, "POINT (1.0 2.0)" if connection.ops.oracle else "POINT(1 2)" ) @skipUnlessDBFeature("has_Azimuth_function") def test_azimuth(self): # Returns the azimuth in radians. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(1, 1, srid=4326)) self.assertAlmostEqual( City.objects.annotate(azimuth=azimuth_expr).first().azimuth, math.pi / 4, places=2, ) # Returns None if the two points are coincident. azimuth_expr = functions.Azimuth(Point(0, 0, srid=4326), Point(0, 0, srid=4326)) self.assertIsNone(City.objects.annotate(azimuth=azimuth_expr).first().azimuth) @skipUnlessDBFeature("has_BoundingCircle_function") def test_bounding_circle(self): def circle_num_points(num_seg): # num_seg is the number of segments per quarter circle. return (4 * num_seg) + 1 expected_areas = (169, 136) if connection.ops.postgis else (171, 126) qs = Country.objects.annotate( circle=functions.BoundingCircle("mpoly") ).order_by("name") self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0) self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0) if connection.ops.postgis: # By default num_seg=48. self.assertEqual(qs[0].circle.num_points, circle_num_points(48)) self.assertEqual(qs[1].circle.num_points, circle_num_points(48)) tests = [12, Value(12, output_field=IntegerField())] for num_seq in tests: with self.subTest(num_seq=num_seq): qs = Country.objects.annotate( circle=functions.BoundingCircle("mpoly", num_seg=num_seq), ).order_by("name") if connection.ops.postgis: self.assertGreater(qs[0].circle.area, 168.4, 0) self.assertLess(qs[0].circle.area, 169.5, 0) self.assertAlmostEqual(qs[1].circle.area, 136, 0) self.assertEqual(qs[0].circle.num_points, circle_num_points(12)) self.assertEqual(qs[1].circle.num_points, circle_num_points(12)) else: self.assertAlmostEqual(qs[0].circle.area, expected_areas[0], 0) self.assertAlmostEqual(qs[1].circle.area, expected_areas[1], 0) @skipUnlessDBFeature("has_Centroid_function") def test_centroid(self): qs = State.objects.exclude(poly__isnull=True).annotate( centroid=functions.Centroid("poly") ) tol = ( 1.8 if connection.ops.mysql else (0.1 if connection.ops.oracle else 0.00001) ) for state in qs: self.assertTrue(state.poly.centroid.equals_exact(state.centroid, tol)) with self.assertRaisesMessage( TypeError, "'Centroid' takes exactly 1 argument (2 given)" ): State.objects.annotate(centroid=functions.Centroid("poly", "poly")) @skipUnlessDBFeature("has_Difference_function") def test_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(diff=functions.Difference("mpoly", geom)) # Oracle does something screwy with the Texas geometry. if connection.ops.oracle: qs = qs.exclude(name="Texas") for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.diff)) @skipUnlessDBFeature("has_Difference_function", "has_Transform_function") def test_difference_mixed_srid(self): """Testing with mixed SRID (Country has default 4326).""" geom = Point(556597.4, 2632018.6, srid=3857) # Spherical Mercator qs = Country.objects.annotate(difference=functions.Difference("mpoly", geom)) # Oracle does something screwy with the Texas geometry. if connection.ops.oracle: qs = qs.exclude(name="Texas") for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.difference)) @skipUnlessDBFeature("has_Envelope_function") def test_envelope(self): countries = Country.objects.annotate(envelope=functions.Envelope("mpoly")) for country in countries: self.assertTrue(country.envelope.equals(country.mpoly.envelope)) @skipUnlessDBFeature("has_ForcePolygonCW_function") def test_force_polygon_cw(self): rings = ( ((0, 0), (5, 0), (0, 5), (0, 0)), ((1, 1), (1, 3), (3, 1), (1, 1)), ) rhr_rings = ( ((0, 0), (0, 5), (5, 0), (0, 0)), ((1, 1), (3, 1), (1, 3), (1, 1)), ) State.objects.create(name="Foo", poly=Polygon(*rings)) st = State.objects.annotate( force_polygon_cw=functions.ForcePolygonCW("poly") ).get(name="Foo") self.assertEqual(rhr_rings, st.force_polygon_cw.coords) @skipUnlessDBFeature("has_FromWKB_function") def test_fromwkb(self): g = Point(56.811078, 60.608647) g2 = City.objects.values_list( functions.FromWKB(Value(g.wkb.tobytes())), flat=True, )[0] self.assertIs(g.equals_exact(g2, 0.00001), True) @skipUnlessDBFeature("has_FromWKT_function") def test_fromwkt(self): g = Point(56.811078, 60.608647) g2 = City.objects.values_list( functions.FromWKT(Value(g.wkt)), flat=True, )[0] self.assertIs(g.equals_exact(g2, 0.00001), True) @skipUnlessDBFeature("has_GeoHash_function") def test_geohash(self): # Reference query: # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston'; # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston'; ref_hash = "9vk1mfq8jx0c8e0386z6" h1 = City.objects.annotate(geohash=functions.GeoHash("point")).get( name="Houston" ) h2 = City.objects.annotate(geohash=functions.GeoHash("point", precision=5)).get( name="Houston" ) self.assertEqual(ref_hash, h1.geohash[: len(ref_hash)]) self.assertEqual(ref_hash[:5], h2.geohash) @skipUnlessDBFeature("has_GeometryDistance_function") def test_geometry_distance(self): point = Point(-90, 40, srid=4326) qs = City.objects.annotate( distance=functions.GeometryDistance("point", point) ).order_by("distance") distances = ( 2.99091995527296, 5.33507274054713, 9.33852187483721, 9.91769193646233, 11.556465744884, 14.713098433352, 34.3635252198568, 276.987855073372, ) for city, expected_distance in zip(qs, distances): with self.subTest(city=city): self.assertAlmostEqual(city.distance, expected_distance) @skipUnlessDBFeature("has_Intersection_function") def test_intersection(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate(inter=functions.Intersection("mpoly", geom)) for c in qs: if connection.features.empty_intersection_returns_none: self.assertIsNone(c.inter) else: self.assertIs(c.inter.empty, True) @skipUnlessDBFeature("supports_empty_geometries", "has_IsEmpty_function") def test_isempty(self): empty = City.objects.create(name="Nowhere", point=Point(srid=4326)) City.objects.create(name="Somewhere", point=Point(6.825, 47.1, srid=4326)) self.assertSequenceEqual( City.objects.annotate(isempty=functions.IsEmpty("point")).filter( isempty=True ), [empty], ) self.assertSequenceEqual(City.objects.filter(point__isempty=True), [empty]) @skipUnlessDBFeature("has_IsValid_function") def test_isvalid(self): valid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))") invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") State.objects.create(name="valid", poly=valid_geom) State.objects.create(name="invalid", poly=invalid_geom) valid = ( State.objects.filter(name="valid") .annotate(isvalid=functions.IsValid("poly")) .first() ) invalid = ( State.objects.filter(name="invalid") .annotate(isvalid=functions.IsValid("poly")) .first() ) self.assertIs(valid.isvalid, True) self.assertIs(invalid.isvalid, False) @skipUnlessDBFeature("has_Area_function") def test_area_with_regular_aggregate(self): # Create projected country objects, for this test to work on all backends. for c in Country.objects.all(): CountryWebMercator.objects.create( name=c.name, mpoly=c.mpoly.transform(3857, clone=True) ) # Test in projected coordinate system qs = CountryWebMercator.objects.annotate(area_sum=Sum(functions.Area("mpoly"))) # Some backends (e.g. Oracle) cannot group by multipolygon values, so # defer such fields in the aggregation query. for c in qs.defer("mpoly"): result = c.area_sum # If the result is a measure object, get value. if isinstance(result, Area): result = result.sq_m self.assertAlmostEqual((result - c.mpoly.area) / c.mpoly.area, 0) @skipUnlessDBFeature("has_Area_function") def test_area_lookups(self): # Create projected countries so the test works on all backends. CountryWebMercator.objects.bulk_create( CountryWebMercator(name=c.name, mpoly=c.mpoly.transform(3857, clone=True)) for c in Country.objects.all() ) qs = CountryWebMercator.objects.annotate(area=functions.Area("mpoly")) self.assertEqual( qs.get(area__lt=Area(sq_km=500000)), CountryWebMercator.objects.get(name="New Zealand"), ) with self.assertRaisesMessage( ValueError, "AreaField only accepts Area measurement objects." ): qs.get(area__lt=500000) @skipUnlessDBFeature("has_LineLocatePoint_function") def test_line_locate_point(self): pos_expr = functions.LineLocatePoint( LineString((0, 0), (0, 3), srid=4326), Point(0, 1, srid=4326) ) self.assertAlmostEqual( State.objects.annotate(pos=pos_expr).first().pos, 0.3333333 ) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid(self): invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))") State.objects.create(name="invalid", poly=invalid_geom) invalid = ( State.objects.filter(name="invalid") .annotate(repaired=functions.MakeValid("poly")) .first() ) self.assertIs(invalid.repaired.valid, True) self.assertTrue( invalid.repaired.equals( fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))", srid=invalid.poly.srid) ) ) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid_multipolygon(self): invalid_geom = fromstr( "POLYGON((0 0, 0 1 , 1 1 , 1 0, 0 0), (10 0, 10 1, 11 1, 11 0, 10 0))" ) State.objects.create(name="invalid", poly=invalid_geom) invalid = ( State.objects.filter(name="invalid") .annotate( repaired=functions.MakeValid("poly"), ) .get() ) self.assertIs(invalid.repaired.valid, True) self.assertTrue( invalid.repaired.equals( fromstr( "MULTIPOLYGON (((0 0, 0 1, 1 1, 1 0, 0 0)), " "((10 0, 10 1, 11 1, 11 0, 10 0)))", srid=invalid.poly.srid, ) ) ) self.assertEqual(len(invalid.repaired), 2) @skipUnlessDBFeature("has_MakeValid_function") def test_make_valid_output_field(self): # output_field is GeometryField instance because different geometry # types can be returned. output_field = functions.MakeValid( Value(Polygon(), PolygonField(srid=42)), ).output_field self.assertIs(output_field.__class__, GeometryField) self.assertEqual(output_field.srid, 42) @skipUnlessDBFeature("has_MemSize_function") def test_memsize(self): ptown = City.objects.annotate(size=functions.MemSize("point")).get( name="Pueblo" ) # Exact value depends on database and version. self.assertTrue(20 <= ptown.size <= 105) @skipUnlessDBFeature("has_NumGeom_function") def test_num_geom(self): # Both 'countries' only have two geometries. for c in Country.objects.annotate(num_geom=functions.NumGeometries("mpoly")): self.assertEqual(2, c.num_geom) qs = City.objects.filter(point__isnull=False).annotate( num_geom=functions.NumGeometries("point") ) for city in qs: # The results for the number of geometries on non-collections # depends on the database. if connection.ops.mysql or connection.ops.mariadb: self.assertIsNone(city.num_geom) else: self.assertEqual(1, city.num_geom) @skipUnlessDBFeature("has_NumPoint_function") def test_num_points(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name="Foo", line=LineString(coords)) qs = Track.objects.annotate(num_points=functions.NumPoints("line")) self.assertEqual(qs.first().num_points, 2) mpoly_qs = Country.objects.annotate(num_points=functions.NumPoints("mpoly")) if not connection.features.supports_num_points_poly: for c in mpoly_qs: self.assertIsNone(c.num_points) return for c in mpoly_qs: self.assertEqual(c.mpoly.num_points, c.num_points) for c in City.objects.annotate(num_points=functions.NumPoints("point")): self.assertEqual(c.num_points, 1) @skipUnlessDBFeature("has_PointOnSurface_function") def test_point_on_surface(self): qs = Country.objects.annotate( point_on_surface=functions.PointOnSurface("mpoly") ) for country in qs: self.assertTrue(country.mpoly.intersection(country.point_on_surface)) @skipUnlessDBFeature("has_Reverse_function") def test_reverse_geom(self): coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)] Track.objects.create(name="Foo", line=LineString(coords)) track = Track.objects.annotate(reverse_geom=functions.Reverse("line")).get( name="Foo" ) coords.reverse() self.assertEqual(tuple(coords), track.reverse_geom.coords) @skipUnlessDBFeature("has_Scale_function") def test_scale(self): xfac, yfac = 2, 3 tol = 5 # The low precision tolerance is for SpatiaLite qs = Country.objects.annotate(scaled=functions.Scale("mpoly", xfac, yfac)) for country in qs: for p1, p2 in zip(country.mpoly, country.scaled): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): self.assertAlmostEqual(c1[0] * xfac, c2[0], tol) self.assertAlmostEqual(c1[1] * yfac, c2[1], tol) # Test float/Decimal values qs = Country.objects.annotate( scaled=functions.Scale("mpoly", 1.5, Decimal("2.5")) ) self.assertGreater(qs[0].scaled.area, qs[0].mpoly.area) @skipUnlessDBFeature("has_SnapToGrid_function") def test_snap_to_grid(self): # Let's try and break snap_to_grid() with bad combinations of arguments. for bad_args in ((), range(3), range(5)): with self.assertRaises(ValueError): Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args)) for bad_args in (("1.0",), (1.0, None), tuple(map(str, range(4)))): with self.assertRaises(TypeError): Country.objects.annotate(snap=functions.SnapToGrid("mpoly", *bad_args)) # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org # from the world borders dataset he provides. wkt = ( "MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167," "12.46250 43.98472,12.47167 43.98694,12.49278 43.98917," "12.50555 43.98861,12.51000 43.98694,12.51028 43.98277," "12.51167 43.94333,12.51056 43.93916,12.49639 43.92333," "12.49500 43.91472,12.48778 43.90583,12.47444 43.89722," "12.46472 43.89555,12.45917 43.89611,12.41639 43.90472," "12.41222 43.90610,12.40782 43.91366,12.40389 43.92667," "12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))" ) Country.objects.create(name="San Marino", mpoly=fromstr(wkt)) # Because floating-point arithmetic isn't exact, we set a tolerance # to pass into GEOS `equals_exact`. tol = 0.000000001 # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) # FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr("MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))") self.assertTrue( ref.equals_exact( Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.1)) .get(name="San Marino") .snap, tol, ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) # FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( "MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))" ) self.assertTrue( ref.equals_exact( Country.objects.annotate(snap=functions.SnapToGrid("mpoly", 0.05, 0.23)) .get(name="San Marino") .snap, tol, ) ) # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) # FROM "geoapp_country" # WHERE "geoapp_country"."name" = 'San Marino'; ref = fromstr( "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87," "12.45 43.87,12.4 43.87)))" ) self.assertTrue( ref.equals_exact( Country.objects.annotate( snap=functions.SnapToGrid("mpoly", 0.05, 0.23, 0.5, 0.17) ) .get(name="San Marino") .snap, tol, ) ) @skipUnlessDBFeature("has_SymDifference_function") def test_sym_difference(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate( sym_difference=functions.SymDifference("mpoly", geom) ) # Oracle does something screwy with the Texas geometry. if connection.ops.oracle: qs = qs.exclude(name="Texas") for country in qs: self.assertTrue( country.mpoly.sym_difference(geom).equals(country.sym_difference) ) @skipUnlessDBFeature("has_Transform_function") def test_transform(self): # Pre-transformed points for Houston and Pueblo. ptown = fromstr("POINT(992363.390841912 481455.395105533)", srid=2774) # Asserting the result of the transform operation with the values in # the pre-transformed points. h = City.objects.annotate(pt=functions.Transform("point", ptown.srid)).get( name="Pueblo" ) self.assertEqual(2774, h.pt.srid) # Precision is low due to version variations in PROJ and GDAL. self.assertLess(ptown.x - h.pt.x, 1) self.assertLess(ptown.y - h.pt.y, 1) @skipUnlessDBFeature("has_Translate_function") def test_translate(self): xfac, yfac = 5, -23 qs = Country.objects.annotate( translated=functions.Translate("mpoly", xfac, yfac) ) for c in qs: for p1, p2 in zip(c.mpoly, c.translated): for r1, r2 in zip(p1, p2): for c1, c2 in zip(r1.coords, r2.coords): # The low precision is for SpatiaLite self.assertAlmostEqual(c1[0] + xfac, c2[0], 5) self.assertAlmostEqual(c1[1] + yfac, c2[1], 5) # Some combined function tests @skipUnlessDBFeature( "has_Difference_function", "has_Intersection_function", "has_SymDifference_function", "has_Union_function", ) def test_diff_intersection_union(self): geom = Point(5, 23, srid=4326) qs = Country.objects.annotate( difference=functions.Difference("mpoly", geom), sym_difference=functions.SymDifference("mpoly", geom), union=functions.Union("mpoly", geom), intersection=functions.Intersection("mpoly", geom), ) if connection.ops.oracle: # Should be able to execute the queries; however, they won't be the same # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or # SpatiaLite). return for c in qs: self.assertTrue(c.mpoly.difference(geom).equals(c.difference)) if connection.features.empty_intersection_returns_none: self.assertIsNone(c.intersection) else: self.assertIs(c.intersection.empty, True) self.assertTrue(c.mpoly.sym_difference(geom).equals(c.sym_difference)) self.assertTrue(c.mpoly.union(geom).equals(c.union)) @skipUnlessDBFeature("has_Union_function") def test_union(self): """Union with all combinations of geometries/geometry fields.""" geom = Point(-95.363151, 29.763374, srid=4326) union = ( City.objects.annotate(union=functions.Union("point", geom)) .get(name="Dallas") .union ) expected = fromstr( "MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)", srid=4326 ) self.assertTrue(expected.equals(union)) union = ( City.objects.annotate(union=functions.Union(geom, "point")) .get(name="Dallas") .union ) self.assertTrue(expected.equals(union)) union = ( City.objects.annotate(union=functions.Union("point", "point")) .get(name="Dallas") .union ) expected = GEOSGeometry("POINT(-96.801611 32.782057)", srid=4326) self.assertTrue(expected.equals(union)) union = ( City.objects.annotate(union=functions.Union(geom, geom)) .get(name="Dallas") .union ) self.assertTrue(geom.equals(union)) @skipUnlessDBFeature("has_Union_function", "has_Transform_function") def test_union_mixed_srid(self): """The result SRID depends on the order of parameters.""" geom = Point(61.42915, 55.15402, srid=4326) geom_3857 = geom.transform(3857, clone=True) tol = 0.001 for city in City.objects.annotate(union=functions.Union("point", geom_3857)): expected = city.point | geom self.assertTrue(city.union.equals_exact(expected, tol)) self.assertEqual(city.union.srid, 4326) for city in City.objects.annotate(union=functions.Union(geom_3857, "point")): expected = geom_3857 | city.point.transform(3857, clone=True) self.assertTrue(expected.equals_exact(city.union, tol)) self.assertEqual(city.union.srid, 3857) def test_argument_validation(self): with self.assertRaisesMessage( ValueError, "SRID is required for all geometries." ): City.objects.annotate(geo=functions.GeoFunc(Point(1, 1))) msg = "GeoFunc function requires a GeometryField in position 1, got CharField." with self.assertRaisesMessage(TypeError, msg): City.objects.annotate(geo=functions.GeoFunc("name")) msg = "GeoFunc function requires a geometric argument in position 1." with self.assertRaisesMessage(TypeError, msg): City.objects.annotate(union=functions.GeoFunc(1, "point")).get( name="Dallas" )
89a2688a956a219c9537d63cec3d24979002df2c1f46f77be031797dee99a585
import ctypes import itertools import json import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock, skipIf from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile, fromstr, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.contrib.gis.shortcuts import numpy from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = fromstr(g.wkt) if geom.hasz: self.assertEqual(g.ewkt, geom.wkt) def test_wkt_invalid(self): msg = "String input unrecognized as WKT EWKT, and HEXEWKB." with self.assertRaisesMessage(ValueError, msg): fromstr("POINT(٠٠١ ٠)") with self.assertRaisesMessage(ValueError, msg): fromstr("SRID=٧٥٨٣;POINT(100 0)") def test_hex(self): "Testing HEX output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode()) def test_hexewkb(self): "Testing (HEX)EWKB output." # For testing HEX(EWKB). ogc_hex = b"01010000000000000000000000000000000000F03F" ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040" # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));` hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F" # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));` hexewkb_3d = ( b"01010000A0E61000000000000000000000000000000000F03F0000000000000040" ) pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) # OGC-compliant HEX will not have SRID value. self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) # HEXEWKB should be appropriate for its dimension -- have to use an # a WKBWriter w/dimension set accordingly, else GEOS will insert # garbage into 3D coordinate if there is none. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True) # Same for EWKB. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) # Redundant sanity check. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid) def test_kml(self): "Testing KML output." for tg in self.geometries.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, "kml", False) if kml: self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): fromstr(err.wkt) # Bad WKB with self.assertRaises(GEOSException): GEOSGeometry(memoryview(b"0")) class NotAGeometry: pass # Some other object with self.assertRaises(TypeError): GEOSGeometry(NotAGeometry()) # None with self.assertRaises(TypeError): GEOSGeometry(None) def test_wkb(self): "Testing WKB output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(wkb.hex().upper(), g.hex) def test_create_hex(self): "Testing creation from HEX." for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_create_wkb(self): "Testing creation from WKB." for g in self.geometries.hex_wkt: wkb = memoryview(bytes.fromhex(g.hex)) geom_h = GEOSGeometry(wkb) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_ewkt(self): "Testing EWKT." srids = (-1, 32140) for srid in srids: for p in self.geometries.polygons: ewkt = "SRID=%d;%s" % (srid, p.wkt) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export def test_json(self): "Testing GeoJSON input/output (via GDAL)." for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if not hasattr(g, "not_equal"): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json)) def test_json_srid(self): geojson_data = { "type": "Point", "coordinates": [2, 49], "crs": { "type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::4322"}, }, } self.assertEqual( GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322) ) def test_fromfile(self): "Testing the fromfile() factory." ref_pnt = GEOSGeometry("POINT(5 23)") wkt_f = BytesIO() wkt_f.write(ref_pnt.wkt.encode()) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) # Other tests use `fromfile()` on string filenames so those # aren't tested here. for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt) def test_eq(self): "Testing equivalence." p = fromstr("POINT(5 23)") self.assertEqual(p, p.wkt) self.assertNotEqual(p, "foo") ls = fromstr("LINESTRING(0 0, 1 1, 5 5)") self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, "bar") self.assertEqual(p, "POINT(5.0 23.0)") # Error shouldn't be raise on equivalence testing with # an invalid type. for g in (p, ls): self.assertIsNotNone(g) self.assertNotEqual(g, {"foo": "bar"}) self.assertIsNot(g, False) def test_hash(self): point_1 = Point(5, 23) point_2 = Point(5, 23, srid=4326) point_3 = Point(5, 23, srid=32632) multipoint_1 = MultiPoint(point_1, srid=4326) multipoint_2 = MultiPoint(point_2) multipoint_3 = MultiPoint(point_3) self.assertNotEqual(hash(point_1), hash(point_2)) self.assertNotEqual(hash(point_1), hash(point_3)) self.assertNotEqual(hash(point_2), hash(point_3)) self.assertNotEqual(hash(multipoint_1), hash(multipoint_2)) self.assertEqual(hash(multipoint_2), hash(multipoint_3)) self.assertNotEqual(hash(multipoint_1), hash(point_1)) self.assertNotEqual(hash(multipoint_2), hash(point_2)) self.assertNotEqual(hash(multipoint_3), hash(point_3)) def test_eq_with_srid(self): "Testing non-equivalence with different srids." p0 = Point(5, 23) p1 = Point(5, 23, srid=4326) p2 = Point(5, 23, srid=32632) # GEOS self.assertNotEqual(p0, p1) self.assertNotEqual(p1, p2) # EWKT self.assertNotEqual(p0, p1.ewkt) self.assertNotEqual(p1, p0.ewkt) self.assertNotEqual(p1, p2.ewkt) # Equivalence with matching SRIDs self.assertEqual(p2, p2) self.assertEqual(p2, p2.ewkt) # WKT contains no SRID so will not equal self.assertNotEqual(p2, p2.wkt) # SRID of 0 self.assertEqual(p0, "SRID=0;POINT (5 23)") self.assertNotEqual(p1, "SRID=0;POINT (5 23)") def test_points(self): "Testing Point objects." prev = fromstr("POINT(0 0)") for p in self.geometries.points: # Creating the point from the WKT pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, "Point") self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(pnt.dims, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(pnt, fromstr(p.wkt)) self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__. # Making sure that the point's X, Y components are what we expect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, "z"): self.assertIs(pnt.hasz, True) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertIs(pnt.hasz, False) self.assertIsNone(pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) # Centroid operation on point should be point itself self.assertEqual(p.centroid, pnt.centroid.tuple) # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(pnt, pnt2) self.assertEqual(pnt, pnt3) # Now testing setting the x and y pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) # Setting via the tuple/coords property pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt # setting the previous geometry def test_point_reverse(self): point = GEOSGeometry("POINT(144.963 -37.8143)", 4326) self.assertEqual(point.srid, 4326) point.reverse() self.assertEqual(point.ewkt, "SRID=4326;POINT (-37.8143 144.963)") def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, "MultiPoint") self.assertEqual(mpnt.geom_typeid, 4) self.assertEqual(mpnt.dims, 0) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) with self.assertRaises(IndexError): mpnt.__getitem__(len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) for p in mpnt: self.assertEqual(p.geom_type, "Point") self.assertEqual(p.geom_typeid, 0) self.assertIs(p.empty, False) self.assertIs(p.valid, True) def test_linestring(self): "Testing LineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.linestrings: ls = fromstr(line.wkt) self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.dims, 1) self.assertIs(ls.empty, False) self.assertIs(ls.ring, False) if hasattr(line, "centroid"): self.assertEqual(line.centroid, ls.centroid.tuple) if hasattr(line, "tup"): self.assertEqual(line.tup, ls.tuple) self.assertEqual(ls, fromstr(line.wkt)) self.assertIs(ls == prev, False) # Use assertIs() to test __eq__. with self.assertRaises(IndexError): ls.__getitem__(len(ls)) prev = ls # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list # Point individual arguments self.assertEqual( ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt ) if numpy: self.assertEqual( ls, LineString(numpy.array(ls.tuple)) ) # as numpy array with self.assertRaisesMessage( TypeError, "Each coordinate should be a sequence (list or tuple)" ): LineString((0, 0)) with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString(numpy.array([(0, 0)])) with mock.patch("django.contrib.gis.geos.linestring.numpy", False): with self.assertRaisesMessage( TypeError, "Invalid initialization input for LineStrings." ): LineString("wrong input") # Test __iter__(). self.assertEqual( list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)] ) def test_linestring_reverse(self): line = GEOSGeometry("LINESTRING(144.963 -37.8143,151.2607 -33.887)", 4326) self.assertEqual(line.srid, 4326) line.reverse() self.assertEqual( line.ewkt, "SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)" ) def _test_is_counterclockwise(self): lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0)) self.assertIs(lr.is_counterclockwise, True) lr.reverse() self.assertIs(lr.is_counterclockwise, False) msg = "Orientation of an empty LinearRing cannot be determined." with self.assertRaisesMessage(ValueError, msg): LinearRing().is_counterclockwise @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise(self): self._test_is_counterclockwise() @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise_geos_error(self): with mock.patch("django.contrib.gis.geos.prototypes.cs_is_ccw") as mocked: mocked.return_value = 0 mocked.func_name = "GEOSCoordSeq_isCCW" msg = 'Error encountered in GEOS C function "GEOSCoordSeq_isCCW".' with self.assertRaisesMessage(GEOSException, msg): LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.6.9") def test_is_counterclockwise_fallback(self): self._test_is_counterclockwise() def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.multilinestrings: ml = fromstr(line.wkt) self.assertEqual(ml.geom_type, "MultiLineString") self.assertEqual(ml.geom_typeid, 5) self.assertEqual(ml.dims, 1) self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9) self.assertEqual(ml, fromstr(line.wkt)) self.assertIs(ml == prev, False) # Use assertIs() to test __eq__. prev = ml for ls in ml: self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertIs(ls.empty, False) with self.assertRaises(IndexError): ml.__getitem__(len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual( ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)) ) def test_linearring(self): "Testing LinearRing objects." for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, "LinearRing") self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.dims, 1) self.assertEqual(rr.n_p, len(lr)) self.assertIs(lr.valid, True) self.assertIs(lr.empty, False) # Creating a LinearRing from a tuple, list, and numpy array self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple))) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 3." ): LinearRing((0, 0), (1, 1), (0, 0)) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing(numpy.array([(0, 0)])) def test_linearring_json(self): self.assertJSONEqual( LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json, '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}', ) def test_polygons_from_bbox(self): "Testing `from_bbox` class method." bbox = (-180, -90, 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) # Testing numerical precision x = 3.14159265358979323 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[-1] self.assertEqual(format(x, ".13f"), format(y, ".13f")) def test_polygons(self): "Testing Polygon objects." prev = fromstr("POINT(0 0)") for p in self.geometries.polygons: # Creating the Polygon, testing its properties. poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, "Polygon") self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.dims, 2) self.assertIs(poly.empty, False) self.assertIs(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) # Testing the geometry equivalence self.assertEqual(poly, fromstr(p.wkt)) # Should not be equal to previous geometry self.assertIs(poly == prev, False) # Use assertIs() to test __eq__. self.assertIs(poly != prev, True) # Use assertIs() to test __ne__. # Testing the exterior ring ring = poly.exterior_ring self.assertEqual(ring.geom_type, "LinearRing") self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices with self.assertRaises(IndexError): poly.__getitem__(len(poly)) with self.assertRaises(IndexError): poly.__setitem__(len(poly), False) with self.assertRaises(IndexError): poly.__getitem__(-1 * len(poly) - 1) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, "LinearRing") self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. with self.assertRaises(TypeError): Polygon(0, [1, 2, 3]) with self.assertRaises(TypeError): Polygon("foo") # Polygon(shell, (hole1, ... holeN)) ext_ring, *int_rings = poly self.assertEqual(poly, Polygon(ext_ring, int_rings)) # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN) ring_tuples = tuple(r.tuple for r in poly) self.assertEqual(poly, Polygon(*ring_tuples)) # Constructing with tuples of LinearRings. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt) self.assertEqual( poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt ) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content) def test_polygon_comparison(self): p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0))) self.assertGreater(p1, p2) self.assertLess(p2, p1) p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0))) p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0))) self.assertGreater(p4, p3) self.assertLess(p3, p4) def test_multipolygons(self): "Testing MultiPolygon objects." fromstr("POINT (0 0)") for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, "MultiPolygon") self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mpoly.dims, 2) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) with self.assertRaises(IndexError): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, "Polygon") self.assertEqual(p.geom_typeid, 3) self.assertIs(p.valid, True) self.assertEqual( mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt ) def test_memory_hijinks(self): "Testing Geometry __del__() on rings and polygons." # #### Memory issues with rings and poly # These tests are needed to ensure sanity with writable geometries. # Getting a polygon with interior rings, and pulling out the interior rings poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] # These deletes should be 'harmless' since they are done on child geometries del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] # Deleting the polygon del poly # Access to these rings is OK since they are clones. str(ring1) str(ring2) def test_coord_seq(self): "Testing Coordinate Sequence objects." for p in self.geometries.polygons: if p.ext_ring_cs: # Constructing the polygon and getting the coordinate sequence poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq self.assertEqual( p.ext_ring_cs, cs.tuple ) # done in the Polygon test too. self.assertEqual( len(p.ext_ring_cs), len(cs) ) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in range(len(p.ext_ring_cs)): c1 = p.ext_ring_cs[i] # Expected value c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with if len(c1) == 2: tset = (5, 23) else: tset = (5, 23, 8) cs[i] = tset # Making sure every set point matches what we expect for j in range(len(tset)): cs[i] = tset self.assertEqual(tset[j], cs[i][j]) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr("POINT (0 0)") with self.assertRaises(GEOSException): g.relate_pattern(0, "invalid pattern, yo") for rg in self.geometries.relate_geoms: a = fromstr(rg.wkt_a) b = fromstr(rg.wkt_b) self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern)) self.assertEqual(rg.pattern, a.relate(b)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) i1 = fromstr(self.geometries.intersect_geoms[i].wkt) self.assertIs(a.intersects(b), True) i2 = a.intersection(b) self.assertTrue(i1.equals(i2)) self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator a &= b # testing __iand__ self.assertTrue(i1.equals(a)) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertTrue(u1.equals(u2)) self.assertTrue(u1.equals(a | b)) # __or__ is union operator a |= b # testing __ior__ self.assertTrue(u1.equals(a)) def test_unary_union(self): "Testing unary_union." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = GeometryCollection(a, b).unary_union self.assertTrue(u1.equals(u2)) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator a -= b # testing __isub__ self.assertTrue(d1.equals(a)) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue( d1.equals(a ^ b) ) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertTrue(d1.equals(a)) def test_buffer(self): bg = self.geometries.buffer_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer(bg.width, quadsegs=1.1) self._test_buffer(self.geometries.buffer_geoms, "buffer") def test_buffer_with_style(self): bg = self.geometries.buffer_with_style_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, quadsegs=1.1) # Can't use a floating-point for the end cap style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, end_cap_style=1.2) # Can't use a end cap style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, end_cap_style=55) # Can't use a floating-point for the join style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, join_style=1.3) # Can't use a join style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, join_style=66) self._test_buffer( itertools.chain( self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms ), "buffer_with_style", ) def _test_buffer(self, geometries, buffer_method_name): for bg in geometries: g = fromstr(bg.wkt) # The buffer we expect exp_buf = fromstr(bg.buffer_wkt) # Constructing our buffer buf_kwargs = { kwarg_name: getattr(bg, kwarg_name) for kwarg_name in ( "width", "quadsegs", "end_cap_style", "join_style", "mitre_limit", ) if hasattr(bg, kwarg_name) } buf = getattr(g, buffer_method_name)(**buf_kwargs) self.assertEqual(exp_buf.num_coords, buf.num_coords) self.assertEqual(len(exp_buf), len(buf)) # Now assuring that each point in the buffer is almost equal for j in range(len(exp_buf)): exp_ring = exp_buf[j] buf_ring = buf[j] self.assertEqual(len(exp_ring), len(buf_ring)) for k in range(len(exp_ring)): # Asserting the X, Y of each point are almost equal (due to # floating point imprecision). self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9) self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9) def test_covers(self): poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0))) self.assertTrue(poly.covers(Point(5, 5))) self.assertFalse(poly.covers(Point(100, 100))) def test_closed(self): ls_closed = LineString((0, 0), (1, 1), (0, 0)) ls_not_closed = LineString((0, 0), (1, 1)) self.assertFalse(ls_not_closed.closed) self.assertTrue(ls_closed.closed) def test_srid(self): "Testing the SRID property and keyword." # Testing SRID keyword on Point pnt = Point(5, 23, srid=4326) self.assertEqual(4326, pnt.srid) pnt.srid = 3084 self.assertEqual(3084, pnt.srid) with self.assertRaises(ctypes.ArgumentError): pnt.srid = "4326" # Testing SRID keyword on fromstr(), and on Polygon rings. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269) self.assertEqual(4269, poly.srid) for ring in poly: self.assertEqual(4269, ring.srid) poly.srid = 4326 self.assertEqual(4326, poly.shell.srid) # Testing SRID keyword on GeometryCollection gc = GeometryCollection( Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021 ) self.assertEqual(32021, gc.srid) for i in range(len(gc)): self.assertEqual(32021, gc[i].srid) # GEOS may get the SRID from HEXEWKB # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS # using `SELECT GeomFromText('POINT (5 23)', 4326);`. hex = "0101000020E610000000000000000014400000000000003740" p1 = fromstr(hex) self.assertEqual(4326, p1.srid) p2 = fromstr(p1.hex) self.assertIsNone(p2.srid) p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) # Testing that geometry SRID could be set to its own value pnt_wo_srid = Point(1, 1) pnt_wo_srid.srid = pnt_wo_srid.srid # Input geometries that have an SRID. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid) self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkt, srid=1) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkb, srid=1) def test_custom_srid(self): """Test with a null srid and a srid unknown to GDAL.""" for srid in [None, 999999]: pnt = Point(111200, 220900, srid=srid) self.assertTrue( pnt.ewkt.startswith( ("SRID=%s;" % srid if srid else "") + "POINT (111200" ) ) self.assertIsInstance(pnt.ogr, gdal.OGRGeometry) self.assertIsNone(pnt.srs) # Test conversion from custom to a known srid c2w = gdal.CoordTransform( gdal.SpatialReference( "+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +datum=WGS84 " "+units=m +no_defs" ), gdal.SpatialReference(4326), ) new_pnt = pnt.transform(c2w, clone=True) self.assertEqual(new_pnt.srid, 4326) self.assertAlmostEqual(new_pnt.x, 1, 1) self.assertAlmostEqual(new_pnt.y, 2, 1) def test_mutable_geometries(self): "Testing the mutability of Polygons and Geometry Collections." # ### Testing the mutability of Polygons ### for p in self.geometries.polygons: poly = fromstr(p.wkt) # Should only be able to use __setitem__ with LinearRing geometries. with self.assertRaises(TypeError): poly.__setitem__(0, LineString((1, 1), (2, 2))) # Constructing the new shell by adding 500 to every point in the old shell. shell_tup = poly.shell.tuple new_coords = [] for point in shell_tup: new_coords.append((point[0] + 500.0, point[1] + 500.0)) new_shell = LinearRing(*tuple(new_coords)) # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) # ### Testing the mutability of Geometry Collections for tg in self.geometries.multipoints: mp = fromstr(tg.wkt) for i in range(len(mp)): # Creating a random point. pnt = mp[i] new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) # MultiPolygons involve much more memory management because each # Polygon w/in the collection has its own rings. for tg in self.geometries.multipolygons: mpoly = fromstr(tg.wkt) for i in range(len(mpoly)): poly = mpoly[i] old_poly = mpoly[i] # Offsetting the each ring in the polygon by 500. for j in range(len(poly)): r = poly[j] for k in range(len(r)): r[k] = (r[k][0] + 500.0, r[k][1] + 500.0) poly[j] = r self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) # Extreme (!!) __setitem__ -- no longer works, have to detect # in the first object that __setitem__ is called in the subsequent # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)? # mpoly[0][0][0] = (3.14, 2.71) # self.assertEqual((3.14, 2.71), mpoly[0][0][0]) # Doing it more slowly.. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0]) # del mpoly def test_point_list_assignment(self): p = Point(0, 0) p[:] = (1, 2, 3) self.assertEqual(p, Point(1, 2, 3)) p[:] = () self.assertEqual(p.wkt, Point()) p[:] = (1, 2) self.assertEqual(p.wkt, Point(1, 2)) with self.assertRaises(ValueError): p[:] = (1,) with self.assertRaises(ValueError): p[:] = (1, 2, 3, 4, 5) def test_linestring_list_assignment(self): ls = LineString((0, 0), (1, 1)) ls[:] = () self.assertEqual(ls, LineString()) ls[:] = ((0, 0), (1, 1), (2, 2)) self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2))) with self.assertRaises(ValueError): ls[:] = (1,) def test_linearring_list_assignment(self): ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) ls[:] = () self.assertEqual(ls, LinearRing()) ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) with self.assertRaises(ValueError): ls[:] = ((0, 0), (1, 1), (2, 2)) def test_polygon_list_assignment(self): pol = Polygon() pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),) self.assertEqual( pol, Polygon( ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), ), ) pol[:] = () self.assertEqual(pol, Polygon()) def test_geometry_collection_list_assignment(self): p = Point() gc = GeometryCollection() gc[:] = [p] self.assertEqual(gc, GeometryCollection(p)) gc[:] = () self.assertEqual(gc, GeometryCollection()) def test_threed(self): "Testing three-dimensional geometries." # Testing a 3D Point pnt = Point(2, 3, 8) self.assertEqual((2.0, 3.0, 8.0), pnt.coords) with self.assertRaises(TypeError): pnt.tuple = (1.0, 2.0) pnt.coords = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), pnt.coords) # Testing a 3D LineString ls = LineString((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)) self.assertEqual(((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)), ls.tuple) with self.assertRaises(TypeError): ls.__setitem__(0, (1.0, 2.0)) ls[0] = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), ls[0]) def test_distance(self): "Testing the distance() function." # Distance to self should be 0. pnt = Point(0, 0) self.assertEqual(0.0, pnt.distance(Point(0, 0))) # Distance should be 1 self.assertEqual(1.0, pnt.distance(Point(0, 1))) # Distance should be ~ sqrt(2) self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11) # Distances are from the closest vertex in each geometry -- # should be 3 (distance from (2, 2) to (5, 2)). ls1 = LineString((0, 0), (1, 1), (2, 2)) ls2 = LineString((5, 2), (6, 1), (7, 0)) self.assertEqual(3, ls1.distance(ls2)) def test_length(self): "Testing the length property." # Points have 0 length. pnt = Point(0, 0) self.assertEqual(0.0, pnt.length) # Should be ~ sqrt(2) ls = LineString((0, 0), (1, 1)) self.assertAlmostEqual(1.41421356237, ls.length, 11) # Should be circumference of Polygon poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) self.assertEqual(4.0, poly.length) # Should be sum of each element's length in collection. mpoly = MultiPolygon(poly.clone(), poly) self.assertEqual(8.0, mpoly.length) def test_emptyCollections(self): "Testing empty geometries and collections." geoms = [ GeometryCollection([]), fromstr("GEOMETRYCOLLECTION EMPTY"), GeometryCollection(), fromstr("POINT EMPTY"), Point(), fromstr("LINESTRING EMPTY"), LineString(), fromstr("POLYGON EMPTY"), Polygon(), fromstr("MULTILINESTRING EMPTY"), MultiLineString(), fromstr("MULTIPOLYGON EMPTY"), MultiPolygon(()), MultiPolygon(), ] if numpy: geoms.append(LineString(numpy.array([]))) for g in geoms: self.assertIs(g.empty, True) # Testing len() and num_geom. if isinstance(g, Polygon): self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g)) else: self.assertEqual(0, g.num_geom) self.assertEqual(0, len(g)) # Testing __getitem__ (doesn't work on Point or Polygon) if isinstance(g, Point): # IndexError is not raised in GEOS 3.8.0. if geos_version_tuple() != (3, 8, 0): with self.assertRaises(IndexError): g.x elif isinstance(g, Polygon): lr = g.shell self.assertEqual("LINEARRING EMPTY", lr.wkt) self.assertEqual(0, len(lr)) self.assertIs(lr.empty, True) with self.assertRaises(IndexError): lr.__getitem__(0) else: with self.assertRaises(IndexError): g.__getitem__(0) def test_collection_dims(self): gc = GeometryCollection([]) self.assertEqual(gc.dims, -1) gc = GeometryCollection(Point(0, 0)) self.assertEqual(gc.dims, 0) gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0)) self.assertEqual(gc.dims, 1) gc = GeometryCollection( LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0), ) self.assertEqual(gc.dims, 2) def test_collections_of_collections(self): "Testing GeometryCollection handling of other collections." # Creating a GeometryCollection WKT string composed of other # collections and polygons. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid] coll.extend(mls.wkt for mls in self.geometries.multilinestrings) coll.extend(p.wkt for p in self.geometries.polygons) coll.extend(mp.wkt for mp in self.geometries.multipoints) gc_wkt = "GEOMETRYCOLLECTION(%s)" % ",".join(coll) # Should construct ok from WKT gc1 = GEOSGeometry(gc_wkt) # Should also construct ok from individual geometry arguments. gc2 = GeometryCollection(*tuple(g for g in gc1)) # And, they should be equal. self.assertEqual(gc1, gc2) def test_gdal(self): "Testing `ogr` and `srs` properties." g1 = fromstr("POINT(5 23)") self.assertIsInstance(g1.ogr, gdal.OGRGeometry) self.assertIsNone(g1.srs) g1_3d = fromstr("POINT(5 23 8)") self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry) self.assertEqual(g1_3d.ogr.z, 8) g2 = fromstr("LINESTRING(0 0, 5 5, 23 23)", srid=4326) self.assertIsInstance(g2.ogr, gdal.OGRGeometry) self.assertIsInstance(g2.srs, gdal.SpatialReference) self.assertEqual(g2.hex, g2.ogr.hex) self.assertEqual("WGS 84", g2.srs.name) def test_copy(self): "Testing use with the Python `copy` module." import copy poly = GEOSGeometry( "POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))" ) cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr) def test_transform(self): "Testing `transform` method." orig = GEOSGeometry("POINT (-104.609 38.255)", 4326) trans = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) # Using a srid, a SpatialReference object, and a CoordTransform object # for transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(gdal.SpatialReference("EPSG:2774")) ct = gdal.CoordTransform( gdal.SpatialReference("WGS84"), gdal.SpatialReference(2774) ) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_3d(self): p3d = GEOSGeometry("POINT (5 23 100)", 4326) p3d.transform(2774) self.assertAlmostEqual(p3d.z, 100, 3) def test_transform_noop(self): """Testing `transform` method (SRID match)""" # transform() should no-op if source & dest SRIDs match, # regardless of whether GDAL is available. g = GEOSGeometry("POINT (-104.609 38.255)", 4326) gt = g.tuple g.transform(4326) self.assertEqual(g.tuple, gt) self.assertEqual(g.srid, 4326) g = GEOSGeometry("POINT (-104.609 38.255)", 4326) g1 = g.transform(4326, clone=True) self.assertEqual(g1.tuple, g.tuple) self.assertEqual(g1.srid, 4326) self.assertIsNot(g1, g, "Clone didn't happen") def test_transform_nosrid(self): """Testing `transform` method (no SRID or negative SRID)""" g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774, clone=True) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774, clone=True) def test_extent(self): "Testing `extent` method." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50)) self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) pnt = Point(5.23, 17.8) # Extent of points is just the point itself repeated. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent) # Testing on the 'real world' Polygon. poly = fromstr(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_pickle(self): "Testing pickling and unpickling support." # Creating a list of test geometries for pickling, # and setting the SRID on some of them. def get_geoms(lst, srid=None): return [GEOSGeometry(tg.wkt, srid) for tg in lst] tgeoms = get_geoms(self.geometries.points) tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326)) tgeoms.extend(get_geoms(self.geometries.polygons, 3084)) tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857)) tgeoms.append(Point(srid=4326)) tgeoms.append(Point()) for geom in tgeoms: s1 = pickle.dumps(geom) g1 = pickle.loads(s1) self.assertEqual(geom, g1) self.assertEqual(geom.srid, g1.srid) def test_prepared(self): "Testing PreparedGeometry support." # Creating a simple multipolygon and getting a prepared version. mpoly = GEOSGeometry( "MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))" ) prep = mpoly.prepared # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] for pnt in pnts: # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt)) self.assertEqual(mpoly.covers(pnt), prep.covers(pnt)) self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)"))) self.assertTrue(prep.disjoint(Point(-5, -5))) poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1))) self.assertTrue(prep.overlaps(poly)) poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0))) self.assertTrue(prep.touches(poly)) poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1))) self.assertTrue(prep.within(poly)) # Original geometry deletion should not crash the prepared one (#21662) del mpoly self.assertTrue(prep.covers(Point(5, 5))) def test_line_merge(self): "Testing line merge support" ref_geoms = ( fromstr("LINESTRING(1 1, 1 1, 3 3)"), fromstr("MULTILINESTRING((1 1, 3 3), (3 3, 4 2))"), ) ref_merged = ( fromstr("LINESTRING(1 1, 3 3)"), fromstr("LINESTRING (1 1, 3 3, 4 2)"), ) for geom, merged in zip(ref_geoms, ref_merged): self.assertEqual(merged, geom.merged) def test_valid_reason(self): "Testing IsValidReason support" g = GEOSGeometry("POINT(0 0)") self.assertTrue(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertEqual(g.valid_reason, "Valid Geometry") g = GEOSGeometry("LINESTRING(0 0, 0 0)") self.assertFalse(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertTrue( g.valid_reason.startswith("Too few points in geometry component") ) def test_linearref(self): "Testing linear referencing" ls = fromstr("LINESTRING(0 0, 0 10, 10 10, 10 0)") mls = fromstr("MULTILINESTRING((0 0, 0 10), (10 0, 10 10))") self.assertEqual(ls.project(Point(0, 20)), 10.0) self.assertEqual(ls.project(Point(7, 6)), 24) self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3) self.assertEqual(ls.interpolate(10), Point(0, 10)) self.assertEqual(ls.interpolate(24), Point(10, 6)) self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10)) self.assertEqual(mls.project(Point(0, 20)), 10) self.assertEqual(mls.project(Point(7, 6)), 16) self.assertEqual(mls.interpolate(9), Point(0, 9)) self.assertEqual(mls.interpolate(17), Point(10, 7)) def test_deconstructible(self): """ Geometry classes should be deconstructible. """ point = Point(4.337844, 50.827537, srid=4326) path, args, kwargs = point.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.point.Point") self.assertEqual(args, (4.337844, 50.827537)) self.assertEqual(kwargs, {"srid": 4326}) ls = LineString(((0, 0), (1, 1))) path, args, kwargs = ls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, (((0, 0), (1, 1)),)) self.assertEqual(kwargs, {}) ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326) path, args, kwargs = ls2.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, ([Point(0, 0), Point(1, 1)],)) self.assertEqual(kwargs, {"srid": 4326}) ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) poly = Polygon(ext_coords, int_coords) path, args, kwargs = poly.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.polygon.Polygon") self.assertEqual(args, (ext_coords, int_coords)) self.assertEqual(kwargs, {}) lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) path, args, kwargs = lr.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LinearRing") self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0))) self.assertEqual(kwargs, {}) mp = MultiPoint(Point(0, 0), Point(1, 1)) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPoint") self.assertEqual(args, (Point(0, 0), Point(1, 1))) self.assertEqual(kwargs, {}) ls1 = LineString((0, 0), (1, 1)) ls2 = LineString((2, 2), (3, 3)) mls = MultiLineString(ls1, ls2) path, args, kwargs = mls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiLineString") self.assertEqual(args, (ls1, ls2)) self.assertEqual(kwargs, {}) p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1))) mp = MultiPolygon(p1, p2) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPolygon") self.assertEqual(args, (p1, p2)) self.assertEqual(kwargs, {}) poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) path, args, kwargs = gc.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.GeometryCollection") self.assertEqual( args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) ) self.assertEqual(kwargs, {}) def test_subclassing(self): """ GEOSGeometry subclass may itself be subclassed without being forced-cast to the parent class during `__init__`. """ class ExtendedPolygon(Polygon): def __init__(self, *args, data=0, **kwargs): super().__init__(*args, **kwargs) self._data = data def __str__(self): return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt) ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3) self.assertEqual(type(ext_poly), ExtendedPolygon) # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__). self.assertEqual( str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))" ) self.assertJSONEqual( ext_poly.json, '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}', ) def test_geos_version_tuple(self): versions = ( (b"3.0.0rc4-CAPI-1.3.3", (3, 0, 0)), (b"3.0.0-CAPI-1.4.1", (3, 0, 0)), (b"3.4.0dev-CAPI-1.8.0", (3, 4, 0)), (b"3.4.0dev-CAPI-1.8.0 r0", (3, 4, 0)), (b"3.6.2-CAPI-1.10.2 4d2925d6", (3, 6, 2)), ) for version_string, version_tuple in versions: with self.subTest(version_string=version_string): with mock.patch( "django.contrib.gis.geos.libgeos.geos_version", lambda: version_string, ): self.assertEqual(geos_version_tuple(), version_tuple) def test_from_gml(self): self.assertEqual( GEOSGeometry("POINT(0 0)"), GEOSGeometry.from_gml( '<gml:Point gml:id="p21" ' 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' "</gml:Point>" ), ) def test_from_ewkt(self): self.assertEqual( GEOSGeometry.from_ewkt("SRID=1;POINT(1 1)"), Point(1, 1, srid=1) ) self.assertEqual(GEOSGeometry.from_ewkt("POINT(1 1)"), Point(1, 1)) def test_from_ewkt_empty_string(self): msg = "Expected WKT but got an empty string." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=1;") def test_from_ewkt_invalid_srid(self): msg = "EWKT has invalid SRID part." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRUD=1;POINT(1 1)") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=WGS84;POINT(1 1)") def test_fromstr_scientific_wkt(self): self.assertEqual(GEOSGeometry("POINT(1.0e-1 1.0e+1)"), Point(0.1, 10)) def test_normalize(self): multipoint = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1)) normalized = MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0)) # Geometry is normalized in-place and nothing is returned. multipoint_1 = multipoint.clone() self.assertIsNone(multipoint_1.normalize()) self.assertEqual(multipoint_1, normalized) # If the `clone` keyword is set, then the geometry is not modified and # a normalized clone of the geometry is returned instead. multipoint_2 = multipoint.normalize(clone=True) self.assertEqual(multipoint_2, normalized) self.assertNotEqual(multipoint, normalized) @skipIf(geos_version_tuple() < (3, 8), "GEOS >= 3.8.0 is required") def test_make_valid(self): poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") self.assertIs(poly.valid, False) valid_poly = poly.make_valid() self.assertIs(valid_poly.valid, True) self.assertNotEqual(valid_poly, poly) valid_poly2 = valid_poly.make_valid() self.assertIs(valid_poly2.valid, True) self.assertEqual(valid_poly, valid_poly2) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.7.3") def test_make_valid_geos_version(self): msg = "GEOSGeometry.make_valid() requires GEOS >= 3.8.0." poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") with self.assertRaisesMessage(GEOSException, msg): poly.make_valid() def test_empty_point(self): p = Point(srid=4326) self.assertEqual(p.ogr.ewkt, p.ewkt) self.assertEqual(p.transform(2774, clone=True), Point(srid=2774)) p.transform(2774) self.assertEqual(p, Point(srid=2774)) def test_linestring_iter(self): ls = LineString((0, 0), (1, 1)) it = iter(ls) # Step into CoordSeq iterator. next(it) ls[:] = [] with self.assertRaises(IndexError): next(it)
40778e9c9c4c361fe1cb951cba72440f490246e44875d1deae5b2d0958bd5a9a
import collections import json import re from functools import partial from itertools import chain from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value from django.db.models.functions import Cast, Random from django.db.models.lookups import Lookup from django.db.models.query_utils import select_related_descend from django.db.models.sql.constants import ( CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE, ) from django.db.models.sql.query import Query, get_order_dir from django.db.models.sql.where import AND from django.db.transaction import TransactionManagementError from django.utils.functional import cached_property from django.utils.hashable import make_hashable from django.utils.regex_helper import _lazy_re_compile class SQLCompiler: # Multiline ordering SQL clause may appear from RawSQL. ordering_parts = _lazy_re_compile( r"^(.*)\s(?:ASC|DESC).*", re.MULTILINE | re.DOTALL, ) def __init__(self, query, connection, using, elide_empty=True): self.query = query self.connection = connection self.using = using # Some queries, e.g. coalesced aggregation, need to be executed even if # they would return an empty result set. self.elide_empty = elide_empty self.quote_cache = {"*": "*"} # The select, klass_info, and annotations are needed by QuerySet.iterator() # these are set as a side-effect of executing the query. Note that we calculate # separately a list of extra select columns needed for grammatical correctness # of the query, but these columns are not included in self.select. self.select = None self.annotation_col_map = None self.klass_info = None self._meta_ordering = None def __repr__(self): return ( f"<{self.__class__.__qualname__} " f"model={self.query.model.__qualname__} " f"connection={self.connection!r} using={self.using!r}>" ) def setup_query(self, with_col_aliases=False): if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map): self.query.get_initial_alias() self.select, self.klass_info, self.annotation_col_map = self.get_select( with_col_aliases=with_col_aliases, ) self.col_count = len(self.select) def pre_sql_setup(self, with_col_aliases=False): """ Do any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ self.setup_query(with_col_aliases=with_col_aliases) order_by = self.get_order_by() self.where, self.having, self.qualify = self.query.where.split_having_qualify( must_group_by=self.query.group_by is not None ) extra_select = self.get_extra_select(order_by, self.select) self.has_extra_select = bool(extra_select) group_by = self.get_group_by(self.select + extra_select, order_by) return extra_select, order_by, group_by def get_group_by(self, select, order_by): """ Return a list of 2-tuples of form (sql, params). The logic of what exactly the GROUP BY clause contains is hard to describe in other words than "if it passes the test suite, then it is correct". """ # Some examples: # SomeModel.objects.annotate(Count('somecol')) # GROUP BY: all fields of the model # # SomeModel.objects.values('name').annotate(Count('somecol')) # GROUP BY: name # # SomeModel.objects.annotate(Count('somecol')).values('name') # GROUP BY: all cols of the model # # SomeModel.objects.values('name', 'pk') # .annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # In fact, the self.query.group_by is the minimal set to GROUP BY. It # can't be ever restricted to a smaller set, but additional columns in # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately # the end result is that it is impossible to force the query to have # a chosen GROUP BY clause - you can almost do this by using the form: # .values(*wanted_cols).annotate(AnAggregate()) # but any later annotations, extra selects, values calls that # refer some column outside of the wanted_cols, order_by, or even # filter calls can alter the GROUP BY clause. # The query.group_by is either None (no GROUP BY at all), True # (group by select fields), or a list of expressions to be added # to the group by. if self.query.group_by is None: return [] expressions = [] group_by_refs = set() if self.query.group_by is not True: # If the group by is set to a list (by .values() call most likely), # then we need to add everything in it to the GROUP BY clause. # Backwards compatibility hack for setting query.group_by. Remove # when we have public API way of forcing the GROUP BY clause. # Converts string references to expressions. for expr in self.query.group_by: if not hasattr(expr, "as_sql"): expr = self.query.resolve_ref(expr) if isinstance(expr, Ref): if expr.refs not in group_by_refs: group_by_refs.add(expr.refs) expressions.append(expr.source) else: expressions.append(expr) # Note that even if the group_by is set, it is only the minimal # set to group by. So, we need to add cols in select, order_by, and # having into the select in any case. selected_expr_indices = {} for index, (expr, _, alias) in enumerate(select, start=1): if alias: selected_expr_indices[expr] = index # Skip members of the select clause that are already explicitly # grouped against. if alias in group_by_refs: continue expressions.extend(expr.get_group_by_cols()) if not self._meta_ordering: for expr, (sql, params, is_ref) in order_by: # Skip references to the SELECT clause, as all expressions in # the SELECT clause are already part of the GROUP BY. if not is_ref: expressions.extend(expr.get_group_by_cols()) having_group_by = self.having.get_group_by_cols() if self.having else () for expr in having_group_by: expressions.append(expr) result = [] seen = set() expressions = self.collapse_group_by(expressions, having_group_by) allows_group_by_select_index = ( self.connection.features.allows_group_by_select_index ) for expr in expressions: try: sql, params = self.compile(expr) except (EmptyResultSet, FullResultSet): continue if ( allows_group_by_select_index and (select_index := selected_expr_indices.get(expr)) is not None ): sql, params = str(select_index), () else: sql, params = expr.select_format(self, sql, params) params_hash = make_hashable(params) if (sql, params_hash) not in seen: result.append((sql, params)) seen.add((sql, params_hash)) return result def collapse_group_by(self, expressions, having): # If the database supports group by functional dependence reduction, # then the expressions can be reduced to the set of selected table # primary keys as all other columns are functionally dependent on them. if self.connection.features.allows_group_by_selected_pks: # Filter out all expressions associated with a table's primary key # present in the grouped columns. This is done by identifying all # tables that have their primary key included in the grouped # columns and removing non-primary key columns referring to them. # Unmanaged models are excluded because they could be representing # database views on which the optimization might not be allowed. pks = { expr for expr in expressions if ( hasattr(expr, "target") and expr.target.primary_key and self.connection.features.allows_group_by_selected_pks_on_model( expr.target.model ) ) } aliases = {expr.alias for expr in pks} expressions = [ expr for expr in expressions if expr in pks or expr in having or getattr(expr, "alias", None) not in aliases ] return expressions def get_select(self, with_col_aliases=False): """ Return three values: - a list of 3-tuples of (expression, (sql, params), alias) - a klass_info structure, - a dictionary of annotations The (sql, params) is what the expression will produce, and alias is the "AS alias" for the column (possibly None). The klass_info structure contains the following information: - The base model of the query. - Which columns for that model are present in the query (by position of the select clause). - related_klass_infos: [f, klass_info] to descent into The annotations is a dictionary of {'attname': column position} values. """ select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items(): annotations[alias] = select_idx select.append((RawSQL(sql, params), alias)) select_idx += 1 assert not (self.query.select and self.query.default_cols) select_mask = self.query.get_select_mask() if self.query.default_cols: cols = self.get_default_columns(select_mask) else: # self.query.select is a special case. These columns never go to # any model. cols = self.query.select if cols: select_list = [] for col in cols: select_list.append(select_idx) select.append((col, None)) select_idx += 1 klass_info = { "model": self.query.model, "select_fields": select_list, } for alias, annotation in self.query.annotation_select.items(): annotations[alias] = select_idx select.append((annotation, alias)) select_idx += 1 if self.query.select_related: related_klass_infos = self.get_related_selections(select, select_mask) klass_info["related_klass_infos"] = related_klass_infos def get_select_from_parent(klass_info): for ki in klass_info["related_klass_infos"]: if ki["from_parent"]: ki["select_fields"] = ( klass_info["select_fields"] + ki["select_fields"] ) get_select_from_parent(ki) get_select_from_parent(klass_info) ret = [] col_idx = 1 for col, alias in select: try: sql, params = self.compile(col) except EmptyResultSet: empty_result_set_value = getattr( col, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: # Select a predicate that's always False. sql, params = "0", () else: sql, params = self.compile(Value(empty_result_set_value)) except FullResultSet: sql, params = self.compile(Value(True)) else: sql, params = col.select_format(self, sql, params) if alias is None and with_col_aliases: alias = f"col{col_idx}" col_idx += 1 ret.append((col, (sql, params), alias)) return ret, klass_info, annotations def _order_by_pairs(self): if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by elif self.query.order_by: ordering = self.query.order_by elif (meta := self.query.get_meta()) and meta.ordering: ordering = meta.ordering self._meta_ordering = ordering else: ordering = [] if self.query.standard_ordering: default_order, _ = ORDER_DIR["ASC"] else: default_order, _ = ORDER_DIR["DESC"] for field in ordering: if hasattr(field, "resolve_expression"): if isinstance(field, Value): # output_field must be resolved for constants. field = Cast(field, field.output_field) if not isinstance(field, OrderBy): field = field.asc() if not self.query.standard_ordering: field = field.copy() field.reverse_ordering() if isinstance(field.expression, F) and ( annotation := self.query.annotation_select.get( field.expression.name ) ): field.expression = Ref(field.expression.name, annotation) yield field, isinstance(field.expression, Ref) continue if field == "?": # random yield OrderBy(Random()), False continue col, order = get_order_dir(field, default_order) descending = order == "DESC" if col in self.query.annotation_select: # Reference to expression in SELECT clause yield ( OrderBy( Ref(col, self.query.annotation_select[col]), descending=descending, ), True, ) continue if col in self.query.annotations: # References to an expression which is masked out of the SELECT # clause. if self.query.combinator and self.select: # Don't use the resolved annotation because other # combinated queries might define it differently. expr = F(col) else: expr = self.query.annotations[col] if isinstance(expr, Value): # output_field must be resolved for constants. expr = Cast(expr, expr.output_field) yield OrderBy(expr, descending=descending), False continue if "." in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split(".", 1) yield ( OrderBy( RawSQL( "%s.%s" % (self.quote_name_unless_alias(table), col), [] ), descending=descending, ), False, ) continue if self.query.extra and col in self.query.extra: if col in self.query.extra_select: yield ( OrderBy( Ref(col, RawSQL(*self.query.extra[col])), descending=descending, ), True, ) else: yield ( OrderBy(RawSQL(*self.query.extra[col]), descending=descending), False, ) else: if self.query.combinator and self.select: # Don't use the first model's field because other # combinated queries might define it differently. yield OrderBy(F(col), descending=descending), False else: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. yield from self.find_ordering_name( field, self.query.get_meta(), default_order=default_order, ) def get_order_by(self): """ Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for the ORDER BY clause. The order_by clause can alter the select clause (for example it can add aliases to clauses that do not yet have one, or it can add totally new select clauses). """ result = [] seen = set() for expr, is_ref in self._order_by_pairs(): resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None) if not is_ref and self.query.combinator and self.select: src = resolved.expression expr_src = expr.expression for sel_expr, _, col_alias in self.select: if src == sel_expr: # When values() is used the exact alias must be used to # reference annotations. if ( self.query.has_select_fields and col_alias in self.query.annotation_select and not ( isinstance(expr_src, F) and col_alias == expr_src.name ) ): continue resolved.set_source_expressions( [Ref(col_alias if col_alias else src.target.column, src)] ) break else: # Add column used in ORDER BY clause to the selected # columns and to each combined query. order_by_idx = len(self.query.select) + 1 col_alias = f"__orderbycol{order_by_idx}" for q in self.query.combined_queries: # If fields were explicitly selected through values() # combined queries cannot be augmented. if q.has_select_fields: raise DatabaseError( "ORDER BY term does not match any column in " "the result set." ) q.add_annotation(expr_src, col_alias) self.query.add_select_col(resolved, col_alias) resolved.set_source_expressions([Ref(col_alias, src)]) sql, params = self.compile(resolved) # Don't add the same column twice, but the order direction is # not taken into account so we strip it. When this entire method # is refactored into expressions, then we can check each part as we # generate it. without_ordering = self.ordering_parts.search(sql)[1] params_hash = make_hashable(params) if (without_ordering, params_hash) in seen: continue seen.add((without_ordering, params_hash)) result.append((resolved, (sql, params, is_ref))) return result def get_extra_select(self, order_by, select): extra_select = [] if self.query.distinct and not self.query.distinct_fields: select_sql = [t[1] for t in select] for expr, (sql, params, is_ref) in order_by: without_ordering = self.ordering_parts.search(sql)[1] if not is_ref and (without_ordering, params) not in select_sql: extra_select.append((expr, (without_ordering, params), None)) return extra_select def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ( (name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select or ( self.query.external_aliases.get(name) and name not in self.query.table_map ) ): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def compile(self, node): vendor_impl = getattr(node, "as_" + self.connection.vendor, None) if vendor_impl: sql, params = vendor_impl(self, self.connection) else: sql, params = node.as_sql(self, self.connection) return sql, params def get_combinator_sql(self, combinator, all): features = self.connection.features compilers = [ query.get_compiler(self.using, self.connection, self.elide_empty) for query in self.query.combined_queries ] if not features.supports_slicing_ordering_in_compound: for compiler in compilers: if compiler.query.is_sliced: raise DatabaseError( "LIMIT/OFFSET not allowed in subqueries of compound statements." ) if compiler.get_order_by(): raise DatabaseError( "ORDER BY not allowed in subqueries of compound statements." ) elif self.query.is_sliced and combinator == "union": for compiler in compilers: # A sliced union cannot have its parts elided as some of them # might be sliced as well and in the event where only a single # part produces a non-empty resultset it might be impossible to # generate valid SQL. compiler.elide_empty = False parts = () for compiler in compilers: try: # If the columns list is limited, then all combined queries # must have the same columns list. Set the selects defined on # the query on all combined queries, if not already set. if not compiler.query.values_select and self.query.values_select: compiler.query = compiler.query.clone() compiler.query.set_values( ( *self.query.extra_select, *self.query.values_select, *self.query.annotation_select, ) ) part_sql, part_args = compiler.as_sql(with_col_aliases=True) if compiler.query.combinator: # Wrap in a subquery if wrapping in parentheses isn't # supported. if not features.supports_parentheses_in_compound: part_sql = "SELECT * FROM ({})".format(part_sql) # Add parentheses when combining with compound query if not # already added for all compound queries. elif ( self.query.subquery or not features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) elif ( self.query.subquery and features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) parts += ((part_sql, part_args),) except EmptyResultSet: # Omit the empty queryset with UNION and with DIFFERENCE if the # first queryset is nonempty. if combinator == "union" or (combinator == "difference" and parts): continue raise if not parts: raise EmptyResultSet combinator_sql = self.connection.ops.set_operators[combinator] if all and combinator == "union": combinator_sql += " ALL" braces = "{}" if not self.query.subquery and features.supports_slicing_ordering_in_compound: braces = "({})" sql_parts, args_parts = zip( *((braces.format(sql), args) for sql, args in parts) ) result = [" {} ".format(combinator_sql).join(sql_parts)] params = [] for part in args_parts: params.extend(part) return result, params def get_qualify_sql(self): where_parts = [] if self.where: where_parts.append(self.where) if self.having: where_parts.append(self.having) inner_query = self.query.clone() inner_query.subquery = True inner_query.where = inner_query.where.__class__(where_parts) # Augment the inner query with any window function references that # might have been masked via values() and alias(). If any masked # aliases are added they'll be masked again to avoid fetching # the data in the `if qual_aliases` branch below. select = { expr: alias for expr, _, alias in self.get_select(with_col_aliases=True)[0] } select_aliases = set(select.values()) qual_aliases = set() replacements = {} def collect_replacements(expressions): while expressions: expr = expressions.pop() if expr in replacements: continue elif select_alias := select.get(expr): replacements[expr] = select_alias elif isinstance(expr, Lookup): expressions.extend(expr.get_source_expressions()) elif isinstance(expr, Ref): if expr.refs not in select_aliases: expressions.extend(expr.get_source_expressions()) else: num_qual_alias = len(qual_aliases) select_alias = f"qual{num_qual_alias}" qual_aliases.add(select_alias) inner_query.add_annotation(expr, select_alias) replacements[expr] = select_alias collect_replacements(list(self.qualify.leaves())) self.qualify = self.qualify.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) order_by = [] for order_by_expr, *_ in self.get_order_by(): collect_replacements(order_by_expr.get_source_expressions()) order_by.append( order_by_expr.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) ) inner_query_compiler = inner_query.get_compiler( self.using, elide_empty=self.elide_empty ) inner_sql, inner_params = inner_query_compiler.as_sql( # The limits must be applied to the outer query to avoid pruning # results too eagerly. with_limits=False, # Force unique aliasing of selected columns to avoid collisions # and make rhs predicates referencing easier. with_col_aliases=True, ) qualify_sql, qualify_params = self.compile(self.qualify) result = [ "SELECT * FROM (", inner_sql, ")", self.connection.ops.quote_name("qualify"), "WHERE", qualify_sql, ] if qual_aliases: # If some select aliases were unmasked for filtering purposes they # must be masked back. cols = [self.connection.ops.quote_name(alias) for alias in select.values()] result = [ "SELECT", ", ".join(cols), "FROM (", *result, ")", self.connection.ops.quote_name("qualify_mask"), ] params = list(inner_params) + qualify_params # As the SQL spec is unclear on whether or not derived tables # ordering must propagate it has to be explicitly repeated on the # outer-most query to ensure it's preserved. if order_by: ordering_sqls = [] for ordering in order_by: ordering_sql, ordering_params = self.compile(ordering) ordering_sqls.append(ordering_sql) params.extend(ordering_params) result.extend(["ORDER BY", ", ".join(ordering_sqls)]) return result, params def as_sql(self, with_limits=True, with_col_aliases=False): """ Create the SQL for this query. Return the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ refcounts_before = self.query.alias_refcount.copy() try: combinator = self.query.combinator extra_select, order_by, group_by = self.pre_sql_setup( with_col_aliases=with_col_aliases or bool(combinator), ) for_update_part = None # Is a LIMIT/OFFSET clause needed? with_limit_offset = with_limits and self.query.is_sliced combinator = self.query.combinator features = self.connection.features if combinator: if not getattr(features, "supports_select_{}".format(combinator)): raise NotSupportedError( "{} is not supported on this database backend.".format( combinator ) ) result, params = self.get_combinator_sql( combinator, self.query.combinator_all ) elif self.qualify: result, params = self.get_qualify_sql() order_by = None else: distinct_fields, distinct_params = self.get_distinct() # This must come after 'select', 'ordering', and 'distinct' # (see docstring of get_from_clause() for details). from_, f_params = self.get_from_clause() try: where, w_params = ( self.compile(self.where) if self.where is not None else ("", []) ) except EmptyResultSet: if self.elide_empty: raise # Use a predicate that's always False. where, w_params = "0 = 1", [] except FullResultSet: where, w_params = "", [] try: having, h_params = ( self.compile(self.having) if self.having is not None else ("", []) ) except FullResultSet: having, h_params = "", [] result = ["SELECT"] params = [] if self.query.distinct: distinct_result, distinct_params = self.connection.ops.distinct_sql( distinct_fields, distinct_params, ) result += distinct_result params += distinct_params out_cols = [] for _, (s_sql, s_params), alias in self.select + extra_select: if alias: s_sql = "%s AS %s" % ( s_sql, self.connection.ops.quote_name(alias), ) params.extend(s_params) out_cols.append(s_sql) result += [", ".join(out_cols)] if from_: result += ["FROM", *from_] elif self.connection.features.bare_select_suffix: result += [self.connection.features.bare_select_suffix] params.extend(f_params) if self.query.select_for_update and features.has_select_for_update: if ( self.connection.get_autocommit() # Don't raise an exception when database doesn't # support transactions, as it's a noop. and features.supports_transactions ): raise TransactionManagementError( "select_for_update cannot be used outside of a transaction." ) if ( with_limit_offset and not features.supports_select_for_update_with_limit ): raise NotSupportedError( "LIMIT/OFFSET is not supported with " "select_for_update on this database backend." ) nowait = self.query.select_for_update_nowait skip_locked = self.query.select_for_update_skip_locked of = self.query.select_for_update_of no_key = self.query.select_for_no_key_update # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the # backend doesn't support it, raise NotSupportedError to # prevent a possible deadlock. if nowait and not features.has_select_for_update_nowait: raise NotSupportedError( "NOWAIT is not supported on this database backend." ) elif skip_locked and not features.has_select_for_update_skip_locked: raise NotSupportedError( "SKIP LOCKED is not supported on this database backend." ) elif of and not features.has_select_for_update_of: raise NotSupportedError( "FOR UPDATE OF is not supported on this database backend." ) elif no_key and not features.has_select_for_no_key_update: raise NotSupportedError( "FOR NO KEY UPDATE is not supported on this " "database backend." ) for_update_part = self.connection.ops.for_update_sql( nowait=nowait, skip_locked=skip_locked, of=self.get_select_for_update_of_arguments(), no_key=no_key, ) if for_update_part and features.for_update_after_from: result.append(for_update_part) if where: result.append("WHERE %s" % where) params.extend(w_params) grouping = [] for g_sql, g_params in group_by: grouping.append(g_sql) params.extend(g_params) if grouping: if distinct_fields: raise NotImplementedError( "annotate() + distinct(fields) is not implemented." ) order_by = order_by or self.connection.ops.force_no_ordering() result.append("GROUP BY %s" % ", ".join(grouping)) if self._meta_ordering: order_by = None if having: result.append("HAVING %s" % having) params.extend(h_params) if self.query.explain_info: result.insert( 0, self.connection.ops.explain_query_prefix( self.query.explain_info.format, **self.query.explain_info.options, ), ) if order_by: ordering = [] for _, (o_sql, o_params, _) in order_by: ordering.append(o_sql) params.extend(o_params) order_by_sql = "ORDER BY %s" % ", ".join(ordering) if combinator and features.requires_compound_order_by_subquery: result = ["SELECT * FROM (", *result, ")", order_by_sql] else: result.append(order_by_sql) if with_limit_offset: result.append( self.connection.ops.limit_offset_sql( self.query.low_mark, self.query.high_mark ) ) if for_update_part and not features.for_update_after_from: result.append(for_update_part) if self.query.subquery and extra_select: # If the query is used as a subquery, the extra selects would # result in more columns than the left-hand side expression is # expecting. This can happen when a subquery uses a combination # of order_by() and distinct(), forcing the ordering expressions # to be selected as well. Wrap the query in another subquery # to exclude extraneous selects. sub_selects = [] sub_params = [] for index, (select, _, alias) in enumerate(self.select, start=1): if alias: sub_selects.append( "%s.%s" % ( self.connection.ops.quote_name("subquery"), self.connection.ops.quote_name(alias), ) ) else: select_clone = select.relabeled_clone( {select.alias: "subquery"} ) subselect, subparams = select_clone.as_sql( self, self.connection ) sub_selects.append(subselect) sub_params.extend(subparams) return "SELECT %s FROM (%s) subquery" % ( ", ".join(sub_selects), " ".join(result), ), tuple(sub_params + params) return " ".join(result), tuple(params) finally: # Finally do cleanup - get rid of the joins we created above. self.query.reset_refcounts(refcounts_before) def get_default_columns( self, select_mask, start_alias=None, opts=None, from_parent=None ): """ Compute the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Return a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, return a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: if (opts := self.query.get_meta()) is None: return result start_alias = start_alias or self.query.get_initial_alias() # The 'seen_models' is used to optimize checking the needed parent # alias for a given field. This also includes None -> start_alias to # be used by local fields. seen_models = {None: start_alias} for field in opts.concrete_fields: model = field.model._meta.concrete_model # A proxy model will have a different model and concrete_model. We # will assign None if the field belongs to this model. if model == opts.model: model = None if ( from_parent and model is not None and issubclass( from_parent._meta.concrete_model, model._meta.concrete_model ) ): # Avoid loading data for already loaded parents. # We end up here in the case select_related() resolution # proceeds from parent model to child model. In that case the # parent model data is already present in the SELECT clause, # and we want to avoid reloading the same data again. continue if select_mask and field not in select_mask: continue alias = self.query.join_parent_model(opts, model, start_alias, seen_models) column = field.get_col(alias) result.append(column) return result def get_distinct(self): """ Return a quoted list of fields to use in DISTINCT ON part of the query. This method can alter the tables in the query, and thus it must be called before get_from_clause(). """ result = [] params = [] opts = self.query.get_meta() for name in self.query.distinct_fields: parts = name.split(LOOKUP_SEP) _, targets, alias, joins, path, _, transform_function = self._setup_joins( parts, opts, None ) targets, alias, _ = self.query.trim_joins(targets, joins, path) for target in targets: if name in self.query.annotation_select: result.append(self.connection.ops.quote_name(name)) else: r, p = self.compile(transform_function(target, alias)) result.append(r) params.append(p) return result, params def find_ordering_name( self, name, opts, alias=None, default_order="ASC", already_seen=None ): """ Return the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) descending = order == "DESC" pieces = name.split(LOOKUP_SEP) ( field, targets, alias, joins, path, opts, transform_function, ) = self._setup_joins(pieces, opts, alias) # If we get to this point and the field is a relation to another model, # append the default ordering for that model unless it is the pk # shortcut or the attribute name of the field that is specified or # there are transforms to process. if ( field.is_relation and opts.ordering and getattr(field, "attname", None) != pieces[-1] and name != "pk" and not getattr(transform_function, "has_transforms", False) ): # Firstly, avoid infinite loops. already_seen = already_seen or set() join_tuple = tuple( getattr(self.query.alias_map[j], "join_cols", None) for j in joins ) if join_tuple in already_seen: raise FieldError("Infinite loop caused by ordering.") already_seen.add(join_tuple) results = [] for item in opts.ordering: if hasattr(item, "resolve_expression") and not isinstance( item, OrderBy ): item = item.desc() if descending else item.asc() if isinstance(item, OrderBy): results.append( (item.prefix_references(f"{name}{LOOKUP_SEP}"), False) ) continue results.extend( (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref) for expr, is_ref in self.find_ordering_name( item, opts, alias, order, already_seen ) ) return results targets, alias, _ = self.query.trim_joins(targets, joins, path) return [ (OrderBy(transform_function(t, alias), descending=descending), False) for t in targets ] def _setup_joins(self, pieces, opts, alias): """ Helper method for get_order_by() and get_distinct(). get_ordering() and get_distinct() must produce same target columns on same input, as the prefixes of get_ordering() and get_distinct() must match. Executing SQL where this is not true is an error. """ alias = alias or self.query.get_initial_alias() field, targets, opts, joins, path, transform_function = self.query.setup_joins( pieces, opts, alias ) alias = joins[-1] return field, targets, alias, joins, path, opts, transform_function def get_from_clause(self): """ Return a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Subclasses, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables that are needed. This means the select columns, ordering, and distinct must be done first. """ result = [] params = [] for alias in tuple(self.query.alias_map): if not self.query.alias_refcount[alias]: continue try: from_clause = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue clause_sql, clause_params = self.compile(from_clause) result.append(clause_sql) params.extend(clause_params) for t in self.query.extra_tables: alias, _ = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # call increments the refcount, so an alias refcount of one means # this is the only reference). if ( alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1 ): result.append(", %s" % self.quote_name_unless_alias(alias)) return result, params def get_related_selections( self, select, select_mask, opts=None, root_alias=None, cur_depth=1, requested=None, restricted=None, ): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ def _get_field_choices(): direct_choices = (f.name for f in opts.fields if f.is_relation) reverse_choices = ( f.field.related_query_name() for f in opts.related_objects if f.field.unique ) return chain( direct_choices, reverse_choices, self.query._filtered_relations ) related_klass_infos = [] if not restricted and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return related_klass_infos if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() # Setup for the case when only particular related fields should be # included in the related selection. fields_found = set() if requested is None: restricted = isinstance(self.query.select_related, dict) if restricted: requested = self.query.select_related def get_related_klass_infos(klass_info, related_klass_infos): klass_info["related_klass_infos"] = related_klass_infos for f in opts.fields: fields_found.add(f.name) if restricted: next = requested.get(f.name, {}) if not f.is_relation: # If a non-related field is used like a relation, # or if a single non-relational field is given. if next or f.name in requested: raise FieldError( "Non-relational field given in select_related: '%s'. " "Choices are: %s" % ( f.name, ", ".join(_get_field_choices()) or "(none)", ) ) else: next = False if not select_related_descend(f, restricted, requested, select_mask): continue related_select_mask = select_mask.get(f) or {} klass_info = { "model": f.remote_field.model, "field": f, "reverse": False, "local_setter": f.set_cached_value, "remote_setter": f.remote_field.set_cached_value if f.unique else lambda x, y: None, "from_parent": False, } related_klass_infos.append(klass_info) select_fields = [] _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias) alias = joins[-1] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=f.remote_field.model._meta ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_klass_infos = self.get_related_selections( select, related_select_mask, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) if restricted: related_fields = [ (o.field, o.related_model) for o in opts.related_objects if o.field.unique and not o.many_to_many ] for related_field, model in related_fields: related_select_mask = select_mask.get(related_field) or {} if not select_related_descend( related_field, restricted, requested, related_select_mask, reverse=True, ): continue related_field_name = related_field.related_query_name() fields_found.add(related_field_name) join_info = self.query.setup_joins( [related_field_name], opts, root_alias ) alias = join_info.joins[-1] from_parent = issubclass(model, opts.model) and model is not opts.model klass_info = { "model": model, "field": related_field, "reverse": True, "local_setter": related_field.remote_field.set_cached_value, "remote_setter": related_field.set_cached_value, "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next = requested.get(related_field.related_query_name(), {}) next_klass_infos = self.get_related_selections( select, related_select_mask, model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) def local_setter(final_field, obj, from_obj): # Set a reverse fk object when relation is non-empty. if from_obj: final_field.remote_field.set_cached_value(from_obj, obj) def remote_setter(name, obj, from_obj): setattr(from_obj, name, obj) for name in list(requested): # Filtered relations work only on the topmost level. if cur_depth > 1: break if name in self.query._filtered_relations: fields_found.add(name) final_field, _, join_opts, joins, _, _ = self.query.setup_joins( [name], opts, root_alias ) model = join_opts.model alias = joins[-1] from_parent = ( issubclass(model, opts.model) and model is not opts.model ) klass_info = { "model": model, "field": final_field, "reverse": True, "local_setter": partial(local_setter, final_field), "remote_setter": partial(remote_setter, name), "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] field_select_mask = select_mask.get((name, final_field)) or {} columns = self.get_default_columns( field_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_requested = requested.get(name, {}) next_klass_infos = self.get_related_selections( select, field_select_mask, opts=model._meta, root_alias=alias, cur_depth=cur_depth + 1, requested=next_requested, restricted=restricted, ) get_related_klass_infos(klass_info, next_klass_infos) fields_not_found = set(requested).difference(fields_found) if fields_not_found: invalid_fields = ("'%s'" % s for s in fields_not_found) raise FieldError( "Invalid field name(s) given in select_related: %s. " "Choices are: %s" % ( ", ".join(invalid_fields), ", ".join(_get_field_choices()) or "(none)", ) ) return related_klass_infos def get_select_for_update_of_arguments(self): """ Return a quoted list of arguments for the SELECT FOR UPDATE OF part of the query. """ def _get_parent_klass_info(klass_info): concrete_model = klass_info["model"]._meta.concrete_model for parent_model, parent_link in concrete_model._meta.parents.items(): parent_list = parent_model._meta.get_parent_list() yield { "model": parent_model, "field": parent_link, "reverse": False, "select_fields": [ select_index for select_index in klass_info["select_fields"] # Selected columns from a model or its parents. if ( self.select[select_index][0].target.model == parent_model or self.select[select_index][0].target.model in parent_list ) ], } def _get_first_selected_col_from_model(klass_info): """ Find the first selected column from a model. If it doesn't exist, don't lock a model. select_fields is filled recursively, so it also contains fields from the parent models. """ concrete_model = klass_info["model"]._meta.concrete_model for select_index in klass_info["select_fields"]: if self.select[select_index][0].target.model == concrete_model: return self.select[select_index][0] def _get_field_choices(): """Yield all allowed field paths in breadth-first search order.""" queue = collections.deque([(None, self.klass_info)]) while queue: parent_path, klass_info = queue.popleft() if parent_path is None: path = [] yield "self" else: field = klass_info["field"] if klass_info["reverse"]: field = field.remote_field path = parent_path + [field.name] yield LOOKUP_SEP.join(path) queue.extend( (path, klass_info) for klass_info in _get_parent_klass_info(klass_info) ) queue.extend( (path, klass_info) for klass_info in klass_info.get("related_klass_infos", []) ) if not self.klass_info: return [] result = [] invalid_names = [] for name in self.query.select_for_update_of: klass_info = self.klass_info if name == "self": col = _get_first_selected_col_from_model(klass_info) else: for part in name.split(LOOKUP_SEP): klass_infos = ( *klass_info.get("related_klass_infos", []), *_get_parent_klass_info(klass_info), ) for related_klass_info in klass_infos: field = related_klass_info["field"] if related_klass_info["reverse"]: field = field.remote_field if field.name == part: klass_info = related_klass_info break else: klass_info = None break if klass_info is None: invalid_names.append(name) continue col = _get_first_selected_col_from_model(klass_info) if col is not None: if self.connection.features.select_for_update_of_column: result.append(self.compile(col)[0]) else: result.append(self.quote_name_unless_alias(col.alias)) if invalid_names: raise FieldError( "Invalid field name(s) given in select_for_update(of=(...)): %s. " "Only relational fields followed in the query are allowed. " "Choices are: %s." % ( ", ".join(invalid_names), ", ".join(_get_field_choices()), ) ) return result def get_converters(self, expressions): converters = {} for i, expression in enumerate(expressions): if expression: backend_converters = self.connection.ops.get_db_converters(expression) field_converters = expression.get_db_converters(self.connection) if backend_converters or field_converters: converters[i] = (backend_converters + field_converters, expression) return converters def apply_converters(self, rows, converters): connection = self.connection converters = list(converters.items()) for row in map(list, rows): for pos, (convs, expression) in converters: value = row[pos] for converter in convs: value = converter(value, expression, connection) row[pos] = value yield row def results_iter( self, results=None, tuple_expected=False, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE, ): """Return an iterator over the results from executing this query.""" if results is None: results = self.execute_sql( MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size ) fields = [s[0] for s in self.select[0 : self.col_count]] converters = self.get_converters(fields) rows = chain.from_iterable(results) if converters: rows = self.apply_converters(rows, converters) if tuple_expected: rows = map(tuple, rows) return rows def has_results(self): """ Backends (e.g. NoSQL) can override this in order to use optimized versions of "query has any results." """ return bool(self.execute_sql(SINGLE)) def execute_sql( self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): """ Run the query against the database and return the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ result_type = result_type or NO_RESULTS try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return iter([]) else: return if chunked_fetch: cursor = self.connection.chunked_cursor() else: cursor = self.connection.cursor() try: cursor.execute(sql, params) except Exception: # Might fail for server-side cursors (e.g. connection closed) cursor.close() raise if result_type == CURSOR: # Give the caller the cursor to process and close. return cursor if result_type == SINGLE: try: val = cursor.fetchone() if val: return val[0 : self.col_count] return val finally: # done with the cursor cursor.close() if result_type == NO_RESULTS: cursor.close() return result = cursor_iter( cursor, self.connection.features.empty_fetchmany_value, self.col_count if self.has_extra_select else None, chunk_size, ) if not chunked_fetch or not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. Use chunked_fetch if requested, # unless the database doesn't support it. return list(result) return result def as_subquery_condition(self, alias, columns, compiler): qn = compiler.quote_name_unless_alias qn2 = self.connection.ops.quote_name for index, select_col in enumerate(self.query.select): lhs_sql, lhs_params = self.compile(select_col) rhs = "%s.%s" % (qn(alias), qn2(columns[index])) self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND) sql, params = self.as_sql() return "EXISTS (%s)" % sql, params def explain_query(self): result = list(self.execute_sql()) # Some backends return 1 item tuples with strings, and others return # tuples with integers and strings. Flatten them out into strings. format_ = self.query.explain_info.format output_formatter = json.dumps if format_ and format_.lower() == "json" else str for row in result[0]: if not isinstance(row, str): yield " ".join(output_formatter(c) for c in row) else: yield row class SQLInsertCompiler(SQLCompiler): returning_fields = None returning_params = () def field_as_sql(self, field, val): """ Take a field and a value intended to be saved on that field, and return placeholder SQL and accompanying params. Check for raw values, expressions, and fields with get_placeholder() defined in that order. When field is None, consider the value raw and use it as the placeholder, with no corresponding parameters returned. """ if field is None: # A field value of None means the value is raw. sql, params = val, [] elif hasattr(val, "as_sql"): # This is an expression, let's compile it. sql, params = self.compile(val) elif hasattr(field, "get_placeholder"): # Some fields (e.g. geo fields) need special munging before # they can be inserted. sql, params = field.get_placeholder(val, self, self.connection), [val] else: # Return the common case for the placeholder sql, params = "%s", [val] # The following hook is only used by Oracle Spatial, which sometimes # needs to yield 'NULL' and [] as its placeholder and params instead # of '%s' and [None]. The 'NULL' placeholder is produced earlier by # OracleOperations.get_geom_placeholder(). The following line removes # the corresponding None parameter. See ticket #10888. params = self.connection.ops.modify_insert_params(sql, params) return sql, params def prepare_value(self, field, value): """ Prepare a value to be used in a query by resolving it if it is an expression and otherwise calling the field's get_db_prep_save(). """ if hasattr(value, "resolve_expression"): value = value.resolve_expression( self.query, allow_joins=False, for_save=True ) # Don't allow values containing Col expressions. They refer to # existing columns on a row, but in the case of insert the row # doesn't exist yet. if value.contains_column_references: raise ValueError( 'Failed to insert expression "%s" on %s. F() expressions ' "can only be used to update, not to insert." % (value, field) ) if value.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, value) ) if value.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query (%s=%r)." % (field.name, value) ) return field.get_db_prep_save(value, connection=self.connection) def pre_save_val(self, field, obj): """ Get the given field's value off the given obj. pre_save() is used for things like auto_now on DateTimeField. Skip it if this is a raw query. """ if self.query.raw: return getattr(obj, field.attname) return field.pre_save(obj, add=True) def assemble_as_sql(self, fields, value_rows): """ Take a sequence of N fields and a sequence of M rows of values, and generate placeholder SQL and parameters for each field and value. Return a pair containing: * a sequence of M rows of N SQL placeholder strings, and * a sequence of M rows of corresponding parameter values. Each placeholder string may contain any number of '%s' interpolation strings, and each parameter row will contain exactly as many params as the total number of '%s's in the corresponding placeholder row. """ if not value_rows: return [], [] # list of (sql, [params]) tuples for each object to be saved # Shape: [n_objs][n_fields][2] rows_of_fields_as_sql = ( (self.field_as_sql(field, v) for field, v in zip(fields, row)) for row in value_rows ) # tuple like ([sqls], [[params]s]) for each object to be saved # Shape: [n_objs][2][n_fields] sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql) # Extract separate lists for placeholders and params. # Each of these has shape [n_objs][n_fields] placeholder_rows, param_rows = zip(*sql_and_param_pair_rows) # Params for each field are still lists, and need to be flattened. param_rows = [[p for ps in row for p in ps] for row in param_rows] return placeholder_rows, param_rows def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.get_meta() insert_statement = self.connection.ops.insert_statement( on_conflict=self.query.on_conflict, ) result = ["%s %s" % (insert_statement, qn(opts.db_table))] fields = self.query.fields or [opts.pk] result.append("(%s)" % ", ".join(qn(f.column) for f in fields)) if self.query.fields: value_rows = [ [ self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields ] for obj in self.query.objs ] else: # An empty object. value_rows = [ [self.connection.ops.pk_default_value()] for _ in self.query.objs ] fields = [None] # Currently the backends just accept values when generating bulk # queries and generate their own placeholders. Doing that isn't # necessary and it should be possible to use placeholders and # expressions in bulk inserts too. can_bulk = ( not self.returning_fields and self.connection.features.has_bulk_insert ) placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows) on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql( fields, self.query.on_conflict, (f.column for f in self.query.update_fields), (f.column for f in self.query.unique_fields), ) if ( self.returning_fields and self.connection.features.can_return_columns_from_insert ): if self.connection.features.can_return_rows_from_bulk_insert: result.append( self.connection.ops.bulk_insert_sql(fields, placeholder_rows) ) params = param_rows else: result.append("VALUES (%s)" % ", ".join(placeholder_rows[0])) params = [param_rows[0]] if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) # Skip empty r_sql to allow subclasses to customize behavior for # 3rd party backends. Refs #19096. r_sql, self.returning_params = self.connection.ops.return_insert_columns( self.returning_fields ) if r_sql: result.append(r_sql) params += [self.returning_params] return [(" ".join(result), tuple(chain.from_iterable(params)))] if can_bulk: result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows)) if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [(" ".join(result), tuple(p for ps in param_rows for p in ps))] else: if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [ (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals) for p, vals in zip(placeholder_rows, param_rows) ] def execute_sql(self, returning_fields=None): assert not ( returning_fields and len(self.query.objs) != 1 and not self.connection.features.can_return_rows_from_bulk_insert ) opts = self.query.get_meta() self.returning_fields = returning_fields with self.connection.cursor() as cursor: for sql, params in self.as_sql(): cursor.execute(sql, params) if not self.returning_fields: return [] if ( self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1 ): rows = self.connection.ops.fetch_returned_insert_rows(cursor) elif self.connection.features.can_return_columns_from_insert: assert len(self.query.objs) == 1 rows = [ self.connection.ops.fetch_returned_insert_columns( cursor, self.returning_params, ) ] else: rows = [ ( self.connection.ops.last_insert_id( cursor, opts.db_table, opts.pk.column, ), ) ] cols = [field.get_col(opts.db_table) for field in self.returning_fields] converters = self.get_converters(cols) if converters: rows = list(self.apply_converters(rows, converters)) return rows class SQLDeleteCompiler(SQLCompiler): @cached_property def single_alias(self): # Ensure base table is in aliases. self.query.get_initial_alias() return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1 @classmethod def _expr_refs_base_model(cls, expr, base_model): if isinstance(expr, Query): return expr.model == base_model if not hasattr(expr, "get_source_expressions"): return False return any( cls._expr_refs_base_model(source_expr, base_model) for source_expr in expr.get_source_expressions() ) @cached_property def contains_self_reference_subquery(self): return any( self._expr_refs_base_model(expr, self.query.model) for expr in chain( self.query.annotations.values(), self.query.where.children ) ) def _as_sql(self, query): delete = "DELETE FROM %s" % self.quote_name_unless_alias(query.base_table) try: where, params = self.compile(query.where) except FullResultSet: return delete, () return f"{delete} WHERE {where}", tuple(params) def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ if self.single_alias and not self.contains_self_reference_subquery: return self._as_sql(self.query) innerq = self.query.clone() innerq.__class__ = Query innerq.clear_select_clause() pk = self.query.model._meta.pk innerq.select = [pk.get_col(self.query.get_initial_alias())] outerq = Query(self.query.model) if not self.connection.features.update_can_self_select: # Force the materialization of the inner query to allow reference # to the target table on MySQL. sql, params = innerq.get_compiler(connection=self.connection).as_sql() innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params) outerq.add_filter("pk__in", innerq) return self._as_sql(outerq) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ self.pre_sql_setup() if not self.query.values: return "", () qn = self.quote_name_unless_alias values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, "resolve_expression"): val = val.resolve_expression( self.query, allow_joins=False, for_save=True ) if val.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, val) ) if val.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query " "(%s=%r)." % (field.name, val) ) elif hasattr(val, "prepare_database_save"): if field.remote_field: val = val.prepare_database_save(field) else: raise TypeError( "Tried to update field %s with a model instance, %r. " "Use a value compatible with %s." % (field, val, field.__class__.__name__) ) val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, "get_placeholder"): placeholder = field.get_placeholder(val, self, self.connection) else: placeholder = "%s" name = field.column if hasattr(val, "as_sql"): sql, params = self.compile(val) values.append("%s = %s" % (qn(name), placeholder % sql)) update_params.extend(params) elif val is not None: values.append("%s = %s" % (qn(name), placeholder)) update_params.append(val) else: values.append("%s = NULL" % qn(name)) table = self.query.base_table result = [ "UPDATE %s SET" % qn(table), ", ".join(values), ] try: where, params = self.compile(self.query.where) except FullResultSet: params = [] else: result.append("WHERE %s" % where) return " ".join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, munge the "where" conditions to match the format required for (portable) SQL updates. If multiple updates are required, pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ refcounts_before = self.query.alias_refcount.copy() # Ensure base table is in the query self.query.get_initial_alias() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return query = self.query.chain(klass=Query) query.select_related = False query.clear_ordering(force=True) query.extra = {} query.select = [] meta = query.get_meta() fields = [meta.pk.name] related_ids_index = [] for related in self.query.related_updates: if all( path.join_field.primary_key for path in meta.get_path_to_parent(related) ): # If a primary key chain exists to the targeted related update, # then the meta.pk value can be used for it. related_ids_index.append((related, 0)) else: # This branch will only be reached when updating a field of an # ancestor that is not part of the primary key chain of a MTI # tree. related_ids_index.append((related, len(fields))) fields.append(related._meta.pk.name) query.add_fields(fields) super().pre_sql_setup() must_pre_select = ( count > 1 and not self.connection.features.update_can_self_select ) # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.clear_where() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] related_ids = collections.defaultdict(list) for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend(r[0] for r in rows) for parent, index in related_ids_index: related_ids[parent].extend(r[index] for r in rows) self.query.add_filter("pk__in", idents) self.query.related_ids = related_ids else: # The fast path. Filters and updates in one query. self.query.add_filter("pk__in", query) self.query.reset_refcounts(refcounts_before) class SQLAggregateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ sql, params = [], [] for annotation in self.query.annotation_select.values(): ann_sql, ann_params = self.compile(annotation) ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params) sql.append(ann_sql) params.extend(ann_params) self.col_count = len(self.query.annotation_select) sql = ", ".join(sql) params = tuple(params) inner_query_sql, inner_query_params = self.query.inner_query.get_compiler( self.using, elide_empty=self.elide_empty, ).as_sql(with_col_aliases=True) sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql) params += inner_query_params return sql, params def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close()
a3742b403553bef9b0a73827dbd5d40679c8f20721a1601609e32ee139f14119
""" This module contains the spatial lookup types, and the `get_geo_where_clause` routine for Oracle Spatial. Please note that WKT support is broken on the XE version, and thus this backend will not work on such platforms. Specifically, XE lacks support for an internal JVM, and Java libraries are required to use the WKT constructors. """ import re from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.oracle.adapter import OracleSpatialAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.geos.geometry import GEOSGeometry, GEOSGeometryBase from django.contrib.gis.geos.prototypes.io import wkb_r from django.contrib.gis.measure import Distance from django.db.backends.oracle.operations import DatabaseOperations DEFAULT_TOLERANCE = "0.05" class SDOOperator(SpatialOperator): sql_template = "%(func)s(%(lhs)s, %(rhs)s) = 'TRUE'" class SDODWithin(SpatialOperator): sql_template = "SDO_WITHIN_DISTANCE(%(lhs)s, %(rhs)s, %%s) = 'TRUE'" class SDODisjoint(SpatialOperator): sql_template = ( "SDO_GEOM.RELATE(%%(lhs)s, 'DISJOINT', %%(rhs)s, %s) = 'DISJOINT'" % DEFAULT_TOLERANCE ) class SDORelate(SpatialOperator): sql_template = "SDO_RELATE(%(lhs)s, %(rhs)s, 'mask=%(mask)s') = 'TRUE'" def check_relate_argument(self, arg): masks = ( "TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|" "CONTAINS|COVERS|ANYINTERACT|ON" ) mask_regex = re.compile(r"^(%s)(\+(%s))*$" % (masks, masks), re.I) if not isinstance(arg, str) or not mask_regex.match(arg): raise ValueError('Invalid SDO_RELATE mask: "%s"' % arg) def as_sql(self, connection, lookup, template_params, sql_params): template_params["mask"] = sql_params[-1] return super().as_sql(connection, lookup, template_params, sql_params[:-1]) class OracleOperations(BaseSpatialOperations, DatabaseOperations): name = "oracle" oracle = True disallowed_aggregates = (models.Collect, models.Extent3D, models.MakeLine) Adapter = OracleSpatialAdapter extent = "SDO_AGGR_MBR" unionagg = "SDO_AGGR_UNION" from_text = "SDO_GEOMETRY" function_names = { "Area": "SDO_GEOM.SDO_AREA", "AsGeoJSON": "SDO_UTIL.TO_GEOJSON", "AsWKB": "SDO_UTIL.TO_WKBGEOMETRY", "AsWKT": "SDO_UTIL.TO_WKTGEOMETRY", "BoundingCircle": "SDO_GEOM.SDO_MBC", "Centroid": "SDO_GEOM.SDO_CENTROID", "Difference": "SDO_GEOM.SDO_DIFFERENCE", "Distance": "SDO_GEOM.SDO_DISTANCE", "Envelope": "SDO_GEOM_MBR", "FromWKB": "SDO_UTIL.FROM_WKBGEOMETRY", "FromWKT": "SDO_UTIL.FROM_WKTGEOMETRY", "Intersection": "SDO_GEOM.SDO_INTERSECTION", "IsValid": "SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT", "Length": "SDO_GEOM.SDO_LENGTH", "NumGeometries": "SDO_UTIL.GETNUMELEM", "NumPoints": "SDO_UTIL.GETNUMVERTICES", "Perimeter": "SDO_GEOM.SDO_LENGTH", "PointOnSurface": "SDO_GEOM.SDO_POINTONSURFACE", "Reverse": "SDO_UTIL.REVERSE_LINESTRING", "SymDifference": "SDO_GEOM.SDO_XOR", "Transform": "SDO_CS.TRANSFORM", "Union": "SDO_GEOM.SDO_UNION", } # We want to get SDO Geometries as WKT because it is much easier to # instantiate GEOS proxies from WKT than SDO_GEOMETRY(...) strings. # However, this adversely affects performance (i.e., Java is called # to convert to WKT on every query). If someone wishes to write a # SDO_GEOMETRY(...) parser in Python, let me know =) select = "SDO_UTIL.TO_WKBGEOMETRY(%s)" gis_operators = { "contains": SDOOperator(func="SDO_CONTAINS"), "coveredby": SDOOperator(func="SDO_COVEREDBY"), "covers": SDOOperator(func="SDO_COVERS"), "disjoint": SDODisjoint(), "intersects": SDOOperator( func="SDO_OVERLAPBDYINTERSECT" ), # TODO: Is this really the same as ST_Intersects()? "equals": SDOOperator(func="SDO_EQUAL"), "exact": SDOOperator(func="SDO_EQUAL"), "overlaps": SDOOperator(func="SDO_OVERLAPS"), "same_as": SDOOperator(func="SDO_EQUAL"), # Oracle uses a different syntax, e.g., 'mask=inside+touch' "relate": SDORelate(), "touches": SDOOperator(func="SDO_TOUCH"), "within": SDOOperator(func="SDO_INSIDE"), "dwithin": SDODWithin(), } unsupported_functions = { "AsKML", "AsSVG", "Azimuth", "ClosestPoint", "ForcePolygonCW", "GeoHash", "GeometryDistance", "IsEmpty", "LineLocatePoint", "MakeValid", "MemSize", "Scale", "SnapToGrid", "Translate", } def geo_quote_name(self, name): return super().geo_quote_name(name).upper() def convert_extent(self, clob): if clob: # Generally, Oracle returns a polygon for the extent -- however, # it can return a single point if there's only one Point in the # table. ext_geom = GEOSGeometry(memoryview(clob.read())) gtype = str(ext_geom.geom_type) if gtype == "Polygon": # Construct the 4-tuple from the coordinates in the polygon. shell = ext_geom.shell ll, ur = shell[0][:2], shell[2][:2] elif gtype == "Point": ll = ext_geom.coords[:2] ur = ll else: raise Exception( "Unexpected geometry type returned for extent: %s" % gtype ) xmin, ymin = ll xmax, ymax = ur return (xmin, ymin, xmax, ymax) else: return None def geo_db_type(self, f): """ Return the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it's the same for all geometry types. """ return "MDSYS.SDO_GEOMETRY" def get_distance(self, f, value, lookup_type): """ Return the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them. """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr( value, Distance.unit_attname(f.units_name(self.connection)) ) else: dist_param = value # dwithin lookups on Oracle require a special string parameter # that starts with "distance=". if lookup_type == "dwithin": dist_param = "distance=%s" % dist_param return [dist_param] def get_geom_placeholder(self, f, value, compiler): if value is None: return "NULL" return super().get_geom_placeholder(f, value, compiler) def spatial_aggregate_name(self, agg_name): """ Return the spatial aggregate SQL name. """ agg_name = "unionagg" if agg_name.lower() == "union" else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.oracle.models import OracleGeometryColumns return OracleGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.oracle.models import OracleSpatialRefSys return OracleSpatialRefSys def modify_insert_params(self, placeholder, params): """Drop out insert parameters for NULL placeholder. Needed for Oracle Spatial backend due to #10888. """ if placeholder == "NULL": return [] return super().modify_insert_params(placeholder, params) def get_geometry_converter(self, expression): read = wkb_r().read srid = expression.output_field.srid if srid == -1: srid = None geom_class = expression.output_field.geom_class def converter(value, expression, connection): if value is not None: geom = GEOSGeometryBase(read(memoryview(value.read())), geom_class) if srid: geom.srid = srid return geom return converter def get_area_att_for_field(self, field): return "sq_m"
39ae908a6824168e63921a36a5e37172bafdca84238c0424edfb2e65d7a48c52
import copy import datetime import functools import inspect from collections import defaultdict from decimal import Decimal from types import NoneType from uuid import UUID from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError, connection from django.db.models import fields from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import Q from django.utils.deconstruct import deconstructible from django.utils.functional import cached_property from django.utils.hashable import make_hashable class SQLiteNumericMixin: """ Some expressions with output_field=DecimalField() must be cast to numeric to be properly filtered. """ def as_sqlite(self, compiler, connection, **extra_context): sql, params = self.as_sql(compiler, connection, **extra_context) try: if self.output_field.get_internal_type() == "DecimalField": sql = "CAST(%s AS NUMERIC)" % sql except FieldError: pass return sql, params class Combinable: """ Provide the ability to combine one or two objects with some connector. For example F('foo') + F('bar'). """ # Arithmetic connectors ADD = "+" SUB = "-" MUL = "*" DIV = "/" POW = "^" # The following is a quoted % operator - it is quoted because it can be # used in strings that also have parameter substitution. MOD = "%%" # Bitwise operators - note that these are generated by .bitand() # and .bitor(), the '&' and '|' are reserved for boolean operator # usage. BITAND = "&" BITOR = "|" BITLEFTSHIFT = "<<" BITRIGHTSHIFT = ">>" BITXOR = "#" def _combine(self, other, connector, reversed): if not hasattr(other, "resolve_expression"): # everything must be resolvable to an expression other = Value(other) if reversed: return CombinedExpression(other, connector, self) return CombinedExpression(self, connector, other) ############# # OPERATORS # ############# def __neg__(self): return self._combine(-1, self.MUL, False) def __add__(self, other): return self._combine(other, self.ADD, False) def __sub__(self, other): return self._combine(other, self.SUB, False) def __mul__(self, other): return self._combine(other, self.MUL, False) def __truediv__(self, other): return self._combine(other, self.DIV, False) def __mod__(self, other): return self._combine(other, self.MOD, False) def __pow__(self, other): return self._combine(other, self.POW, False) def __and__(self, other): if getattr(self, "conditional", False) and getattr(other, "conditional", False): return Q(self) & Q(other) raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def bitand(self, other): return self._combine(other, self.BITAND, False) def bitleftshift(self, other): return self._combine(other, self.BITLEFTSHIFT, False) def bitrightshift(self, other): return self._combine(other, self.BITRIGHTSHIFT, False) def __xor__(self, other): if getattr(self, "conditional", False) and getattr(other, "conditional", False): return Q(self) ^ Q(other) raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def bitxor(self, other): return self._combine(other, self.BITXOR, False) def __or__(self, other): if getattr(self, "conditional", False) and getattr(other, "conditional", False): return Q(self) | Q(other) raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def bitor(self, other): return self._combine(other, self.BITOR, False) def __radd__(self, other): return self._combine(other, self.ADD, True) def __rsub__(self, other): return self._combine(other, self.SUB, True) def __rmul__(self, other): return self._combine(other, self.MUL, True) def __rtruediv__(self, other): return self._combine(other, self.DIV, True) def __rmod__(self, other): return self._combine(other, self.MOD, True) def __rpow__(self, other): return self._combine(other, self.POW, True) def __rand__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __ror__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __rxor__(self, other): raise NotImplementedError( "Use .bitand(), .bitor(), and .bitxor() for bitwise logical operations." ) def __invert__(self): return NegatedExpression(self) class BaseExpression: """Base class for all query expressions.""" empty_result_set_value = NotImplemented # aggregate specific fields is_summary = False _output_field_resolved_to_none = False # Can the expression be used in a WHERE clause? filterable = True # Can the expression can be used as a source expression in Window? window_compatible = False def __init__(self, output_field=None): if output_field is not None: self.output_field = output_field def __getstate__(self): state = self.__dict__.copy() state.pop("convert_value", None) return state def get_db_converters(self, connection): return ( [] if self.convert_value is self._convert_value_noop else [self.convert_value] ) + self.output_field.get_db_converters(connection) def get_source_expressions(self): return [] def set_source_expressions(self, exprs): assert not exprs def _parse_expressions(self, *expressions): return [ arg if hasattr(arg, "resolve_expression") else (F(arg) if isinstance(arg, str) else Value(arg)) for arg in expressions ] def as_sql(self, compiler, connection): """ Responsible for returning a (sql, [params]) tuple to be included in the current query. Different backends can provide their own implementation, by providing an `as_{vendor}` method and patching the Expression: ``` def override_as_sql(self, compiler, connection): # custom logic return super().as_sql(compiler, connection) setattr(Expression, 'as_' + connection.vendor, override_as_sql) ``` Arguments: * compiler: the query compiler responsible for generating the query. Must have a compile method, returning a (sql, [params]) tuple. Calling compiler(value) will return a quoted `value`. * connection: the database connection used for the current query. Return: (sql, params) Where `sql` is a string containing ordered sql parameters to be replaced with the elements of the list `params`. """ raise NotImplementedError("Subclasses must implement as_sql()") @cached_property def contains_aggregate(self): return any( expr and expr.contains_aggregate for expr in self.get_source_expressions() ) @cached_property def contains_over_clause(self): return any( expr and expr.contains_over_clause for expr in self.get_source_expressions() ) @cached_property def contains_column_references(self): return any( expr and expr.contains_column_references for expr in self.get_source_expressions() ) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): """ Provide the chance to do any preprocessing or validation before being added to the query. Arguments: * query: the backend query implementation * allow_joins: boolean allowing or denying use of joins in this query * reuse: a set of reusable joins for multijoins * summarize: a terminal aggregate clause * for_save: whether this expression about to be used in a save or update Return: an Expression to be added to the query. """ c = self.copy() c.is_summary = summarize c.set_source_expressions( [ expr.resolve_expression(query, allow_joins, reuse, summarize) if expr else None for expr in c.get_source_expressions() ] ) return c @property def conditional(self): return isinstance(self.output_field, fields.BooleanField) @property def field(self): return self.output_field @cached_property def output_field(self): """Return the output type of this expressions.""" output_field = self._resolve_output_field() if output_field is None: self._output_field_resolved_to_none = True raise FieldError("Cannot resolve expression type, unknown output_field") return output_field @cached_property def _output_field_or_none(self): """ Return the output field of this expression, or None if _resolve_output_field() didn't return an output type. """ try: return self.output_field except FieldError: if not self._output_field_resolved_to_none: raise def _resolve_output_field(self): """ Attempt to infer the output type of the expression. As a guess, if the output fields of all source fields match then simply infer the same type here. If a source's output field resolves to None, exclude it from this check. If all sources are None, then an error is raised higher up the stack in the output_field property. """ # This guess is mostly a bad idea, but there is quite a lot of code # (especially 3rd party Func subclasses) that depend on it, we'd need a # deprecation path to fix it. sources_iter = ( source for source in self.get_source_fields() if source is not None ) for output_field in sources_iter: for source in sources_iter: if not isinstance(output_field, source.__class__): raise FieldError( "Expression contains mixed types: %s, %s. You must " "set output_field." % ( output_field.__class__.__name__, source.__class__.__name__, ) ) return output_field @staticmethod def _convert_value_noop(value, expression, connection): return value @cached_property def convert_value(self): """ Expressions provide their own converters because users have the option of manually specifying the output_field which may be a different type from the one the database returns. """ field = self.output_field internal_type = field.get_internal_type() if internal_type == "FloatField": return ( lambda value, expression, connection: None if value is None else float(value) ) elif internal_type.endswith("IntegerField"): return ( lambda value, expression, connection: None if value is None else int(value) ) elif internal_type == "DecimalField": return ( lambda value, expression, connection: None if value is None else Decimal(value) ) return self._convert_value_noop def get_lookup(self, lookup): return self.output_field.get_lookup(lookup) def get_transform(self, name): return self.output_field.get_transform(name) def relabeled_clone(self, change_map): clone = self.copy() clone.set_source_expressions( [ e.relabeled_clone(change_map) if e is not None else None for e in self.get_source_expressions() ] ) return clone def replace_expressions(self, replacements): if replacement := replacements.get(self): return replacement clone = self.copy() source_expressions = clone.get_source_expressions() clone.set_source_expressions( [ expr.replace_expressions(replacements) if expr else None for expr in source_expressions ] ) return clone def get_refs(self): refs = set() for expr in self.get_source_expressions(): refs |= expr.get_refs() return refs def copy(self): return copy.copy(self) def prefix_references(self, prefix): clone = self.copy() clone.set_source_expressions( [ F(f"{prefix}{expr.name}") if isinstance(expr, F) else expr.prefix_references(prefix) for expr in self.get_source_expressions() ] ) return clone def get_group_by_cols(self): if not self.contains_aggregate: return [self] cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def get_source_fields(self): """Return the underlying field types used by this aggregate.""" return [e._output_field_or_none for e in self.get_source_expressions()] def asc(self, **kwargs): return OrderBy(self, **kwargs) def desc(self, **kwargs): return OrderBy(self, descending=True, **kwargs) def reverse_ordering(self): return self def flatten(self): """ Recursively yield this expression and all subexpressions, in depth-first order. """ yield self for expr in self.get_source_expressions(): if expr: if hasattr(expr, "flatten"): yield from expr.flatten() else: yield expr def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, EXISTS expressions need to be wrapped in CASE WHEN on Oracle. """ if hasattr(self.output_field, "select_format"): return self.output_field.select_format(compiler, sql, params) return sql, params @deconstructible class Expression(BaseExpression, Combinable): """An expression that can be combined with other expressions.""" @cached_property def identity(self): constructor_signature = inspect.signature(self.__init__) args, kwargs = self._constructor_args signature = constructor_signature.bind_partial(*args, **kwargs) signature.apply_defaults() arguments = signature.arguments.items() identity = [self.__class__] for arg, value in arguments: if isinstance(value, fields.Field): if value.name and value.model: value = (value.model._meta.label, value.name) else: value = type(value) else: value = make_hashable(value) identity.append((arg, value)) return tuple(identity) def __eq__(self, other): if not isinstance(other, Expression): return NotImplemented return other.identity == self.identity def __hash__(self): return hash(self.identity) # Type inference for CombinedExpression.output_field. # Missing items will result in FieldError, by design. # # The current approach for NULL is based on lowest common denominator behavior # i.e. if one of the supported databases is raising an error (rather than # return NULL) for `val <op> NULL`, then Django raises FieldError. _connector_combinations = [ # Numeric operations - operands of same type. { connector: [ (fields.IntegerField, fields.IntegerField, fields.IntegerField), (fields.FloatField, fields.FloatField, fields.FloatField), (fields.DecimalField, fields.DecimalField, fields.DecimalField), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, # Behavior for DIV with integer arguments follows Postgres/SQLite, # not MySQL/Oracle. Combinable.DIV, Combinable.MOD, Combinable.POW, ) }, # Numeric operations - operands of different type. { connector: [ (fields.IntegerField, fields.DecimalField, fields.DecimalField), (fields.DecimalField, fields.IntegerField, fields.DecimalField), (fields.IntegerField, fields.FloatField, fields.FloatField), (fields.FloatField, fields.IntegerField, fields.FloatField), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV, Combinable.MOD, ) }, # Bitwise operators. { connector: [ (fields.IntegerField, fields.IntegerField, fields.IntegerField), ] for connector in ( Combinable.BITAND, Combinable.BITOR, Combinable.BITLEFTSHIFT, Combinable.BITRIGHTSHIFT, Combinable.BITXOR, ) }, # Numeric with NULL. { connector: [ (field_type, NoneType, field_type), (NoneType, field_type, field_type), ] for connector in ( Combinable.ADD, Combinable.SUB, Combinable.MUL, Combinable.DIV, Combinable.MOD, Combinable.POW, ) for field_type in (fields.IntegerField, fields.DecimalField, fields.FloatField) }, # Date/DateTimeField/DurationField/TimeField. { Combinable.ADD: [ # Date/DateTimeField. (fields.DateField, fields.DurationField, fields.DateTimeField), (fields.DateTimeField, fields.DurationField, fields.DateTimeField), (fields.DurationField, fields.DateField, fields.DateTimeField), (fields.DurationField, fields.DateTimeField, fields.DateTimeField), # DurationField. (fields.DurationField, fields.DurationField, fields.DurationField), # TimeField. (fields.TimeField, fields.DurationField, fields.TimeField), (fields.DurationField, fields.TimeField, fields.TimeField), ], }, { Combinable.SUB: [ # Date/DateTimeField. (fields.DateField, fields.DurationField, fields.DateTimeField), (fields.DateTimeField, fields.DurationField, fields.DateTimeField), (fields.DateField, fields.DateField, fields.DurationField), (fields.DateField, fields.DateTimeField, fields.DurationField), (fields.DateTimeField, fields.DateField, fields.DurationField), (fields.DateTimeField, fields.DateTimeField, fields.DurationField), # DurationField. (fields.DurationField, fields.DurationField, fields.DurationField), # TimeField. (fields.TimeField, fields.DurationField, fields.TimeField), (fields.TimeField, fields.TimeField, fields.DurationField), ], }, ] _connector_combinators = defaultdict(list) def register_combinable_fields(lhs, connector, rhs, result): """ Register combinable types: lhs <connector> rhs -> result e.g. register_combinable_fields( IntegerField, Combinable.ADD, FloatField, FloatField ) """ _connector_combinators[connector].append((lhs, rhs, result)) for d in _connector_combinations: for connector, field_types in d.items(): for lhs, rhs, result in field_types: register_combinable_fields(lhs, connector, rhs, result) @functools.lru_cache(maxsize=128) def _resolve_combined_type(connector, lhs_type, rhs_type): combinators = _connector_combinators.get(connector, ()) for combinator_lhs_type, combinator_rhs_type, combined_type in combinators: if issubclass(lhs_type, combinator_lhs_type) and issubclass( rhs_type, combinator_rhs_type ): return combined_type class CombinedExpression(SQLiteNumericMixin, Expression): def __init__(self, lhs, connector, rhs, output_field=None): super().__init__(output_field=output_field) self.connector = connector self.lhs = lhs self.rhs = rhs def __repr__(self): return "<{}: {}>".format(self.__class__.__name__, self) def __str__(self): return "{} {} {}".format(self.lhs, self.connector, self.rhs) def get_source_expressions(self): return [self.lhs, self.rhs] def set_source_expressions(self, exprs): self.lhs, self.rhs = exprs def _resolve_output_field(self): # We avoid using super() here for reasons given in # Expression._resolve_output_field() combined_type = _resolve_combined_type( self.connector, type(self.lhs._output_field_or_none), type(self.rhs._output_field_or_none), ) if combined_type is None: raise FieldError( f"Cannot infer type of {self.connector!r} expression involving these " f"types: {self.lhs.output_field.__class__.__name__}, " f"{self.rhs.output_field.__class__.__name__}. You must set " f"output_field." ) return combined_type() def as_sql(self, compiler, connection): expressions = [] expression_params = [] sql, params = compiler.compile(self.lhs) expressions.append(sql) expression_params.extend(params) sql, params = compiler.compile(self.rhs) expressions.append(sql) expression_params.extend(params) # order of precedence expression_wrapper = "(%s)" sql = connection.ops.combine_expression(self.connector, expressions) return expression_wrapper % sql, expression_params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): lhs = self.lhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) rhs = self.rhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) if not isinstance(self, (DurationExpression, TemporalSubtraction)): try: lhs_type = lhs.output_field.get_internal_type() except (AttributeError, FieldError): lhs_type = None try: rhs_type = rhs.output_field.get_internal_type() except (AttributeError, FieldError): rhs_type = None if "DurationField" in {lhs_type, rhs_type} and lhs_type != rhs_type: return DurationExpression( self.lhs, self.connector, self.rhs ).resolve_expression( query, allow_joins, reuse, summarize, for_save, ) datetime_fields = {"DateField", "DateTimeField", "TimeField"} if ( self.connector == self.SUB and lhs_type in datetime_fields and lhs_type == rhs_type ): return TemporalSubtraction(self.lhs, self.rhs).resolve_expression( query, allow_joins, reuse, summarize, for_save, ) c = self.copy() c.is_summary = summarize c.lhs = lhs c.rhs = rhs return c class DurationExpression(CombinedExpression): def compile(self, side, compiler, connection): try: output = side.output_field except FieldError: pass else: if output.get_internal_type() == "DurationField": sql, params = compiler.compile(side) return connection.ops.format_for_duration_arithmetic(sql), params return compiler.compile(side) def as_sql(self, compiler, connection): if connection.features.has_native_duration_field: return super().as_sql(compiler, connection) connection.ops.check_expression_support(self) expressions = [] expression_params = [] sql, params = self.compile(self.lhs, compiler, connection) expressions.append(sql) expression_params.extend(params) sql, params = self.compile(self.rhs, compiler, connection) expressions.append(sql) expression_params.extend(params) # order of precedence expression_wrapper = "(%s)" sql = connection.ops.combine_duration_expression(self.connector, expressions) return expression_wrapper % sql, expression_params def as_sqlite(self, compiler, connection, **extra_context): sql, params = self.as_sql(compiler, connection, **extra_context) if self.connector in {Combinable.MUL, Combinable.DIV}: try: lhs_type = self.lhs.output_field.get_internal_type() rhs_type = self.rhs.output_field.get_internal_type() except (AttributeError, FieldError): pass else: allowed_fields = { "DecimalField", "DurationField", "FloatField", "IntegerField", } if lhs_type not in allowed_fields or rhs_type not in allowed_fields: raise DatabaseError( f"Invalid arguments for operator {self.connector}." ) return sql, params class TemporalSubtraction(CombinedExpression): output_field = fields.DurationField() def __init__(self, lhs, rhs): super().__init__(lhs, self.SUB, rhs) def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) lhs = compiler.compile(self.lhs) rhs = compiler.compile(self.rhs) return connection.ops.subtract_temporals( self.lhs.output_field.get_internal_type(), lhs, rhs ) @deconstructible(path="django.db.models.F") class F(Combinable): """An object capable of resolving references to existing query objects.""" def __init__(self, name): """ Arguments: * name: the name of the field this expression references """ self.name = name def __repr__(self): return "{}({})".format(self.__class__.__name__, self.name) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): return query.resolve_ref(self.name, allow_joins, reuse, summarize) def replace_expressions(self, replacements): return replacements.get(self, self) def asc(self, **kwargs): return OrderBy(self, **kwargs) def desc(self, **kwargs): return OrderBy(self, descending=True, **kwargs) def __eq__(self, other): return self.__class__ == other.__class__ and self.name == other.name def __hash__(self): return hash(self.name) def copy(self): return copy.copy(self) class ResolvedOuterRef(F): """ An object that contains a reference to an outer query. In this case, the reference to the outer query has been resolved because the inner query has been used as a subquery. """ contains_aggregate = False contains_over_clause = False def as_sql(self, *args, **kwargs): raise ValueError( "This queryset contains a reference to an outer query and may " "only be used in a subquery." ) def resolve_expression(self, *args, **kwargs): col = super().resolve_expression(*args, **kwargs) # FIXME: Rename possibly_multivalued to multivalued and fix detection # for non-multivalued JOINs (e.g. foreign key fields). This should take # into account only many-to-many and one-to-many relationships. col.possibly_multivalued = LOOKUP_SEP in self.name return col def relabeled_clone(self, relabels): return self def get_group_by_cols(self): return [] class OuterRef(F): contains_aggregate = False def resolve_expression(self, *args, **kwargs): if isinstance(self.name, self.__class__): return self.name return ResolvedOuterRef(self.name) def relabeled_clone(self, relabels): return self @deconstructible(path="django.db.models.Func") class Func(SQLiteNumericMixin, Expression): """An SQL function call.""" function = None template = "%(function)s(%(expressions)s)" arg_joiner = ", " arity = None # The number of arguments the function accepts. def __init__(self, *expressions, output_field=None, **extra): if self.arity is not None and len(expressions) != self.arity: raise TypeError( "'%s' takes exactly %s %s (%s given)" % ( self.__class__.__name__, self.arity, "argument" if self.arity == 1 else "arguments", len(expressions), ) ) super().__init__(output_field=output_field) self.source_expressions = self._parse_expressions(*expressions) self.extra = extra def __repr__(self): args = self.arg_joiner.join(str(arg) for arg in self.source_expressions) extra = {**self.extra, **self._get_repr_options()} if extra: extra = ", ".join( str(key) + "=" + str(val) for key, val in sorted(extra.items()) ) return "{}({}, {})".format(self.__class__.__name__, args, extra) return "{}({})".format(self.__class__.__name__, args) def _get_repr_options(self): """Return a dict of extra __init__() options to include in the repr.""" return {} def get_source_expressions(self): return self.source_expressions def set_source_expressions(self, exprs): self.source_expressions = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize for pos, arg in enumerate(c.source_expressions): c.source_expressions[pos] = arg.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def as_sql( self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context, ): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: try: arg_sql, arg_params = compiler.compile(arg) except EmptyResultSet: empty_result_set_value = getattr( arg, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: raise arg_sql, arg_params = compiler.compile(Value(empty_result_set_value)) except FullResultSet: arg_sql, arg_params = compiler.compile(Value(True)) sql_parts.append(arg_sql) params.extend(arg_params) data = {**self.extra, **extra_context} # Use the first supplied value in this order: the parameter to this # method, a value supplied in __init__()'s **extra (the value in # `data`), or the value defined on the class. if function is not None: data["function"] = function else: data.setdefault("function", self.function) template = template or data.get("template", self.template) arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner) data["expressions"] = data["field"] = arg_joiner.join(sql_parts) return template % data, params def copy(self): copy = super().copy() copy.source_expressions = self.source_expressions[:] copy.extra = self.extra.copy() return copy @deconstructible(path="django.db.models.Value") class Value(SQLiteNumericMixin, Expression): """Represent a wrapped value as a node within an expression.""" # Provide a default value for `for_save` in order to allow unresolved # instances to be compiled until a decision is taken in #25425. for_save = False def __init__(self, value, output_field=None): """ Arguments: * value: the value this expression represents. The value will be added into the sql parameter list and properly quoted. * output_field: an instance of the model field type that this expression will return, such as IntegerField() or CharField(). """ super().__init__(output_field=output_field) self.value = value def __repr__(self): return f"{self.__class__.__name__}({self.value!r})" def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) val = self.value output_field = self._output_field_or_none if output_field is not None: if self.for_save: val = output_field.get_db_prep_save(val, connection=connection) else: val = output_field.get_db_prep_value(val, connection=connection) if hasattr(output_field, "get_placeholder"): return output_field.get_placeholder(val, compiler, connection), [val] if val is None: # cx_Oracle does not always convert None to the appropriate # NULL type (like in case expressions using numbers), so we # use a literal SQL NULL return "NULL", [] return "%s", [val] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = super().resolve_expression(query, allow_joins, reuse, summarize, for_save) c.for_save = for_save return c def get_group_by_cols(self): return [] def _resolve_output_field(self): if isinstance(self.value, str): return fields.CharField() if isinstance(self.value, bool): return fields.BooleanField() if isinstance(self.value, int): return fields.IntegerField() if isinstance(self.value, float): return fields.FloatField() if isinstance(self.value, datetime.datetime): return fields.DateTimeField() if isinstance(self.value, datetime.date): return fields.DateField() if isinstance(self.value, datetime.time): return fields.TimeField() if isinstance(self.value, datetime.timedelta): return fields.DurationField() if isinstance(self.value, Decimal): return fields.DecimalField() if isinstance(self.value, bytes): return fields.BinaryField() if isinstance(self.value, UUID): return fields.UUIDField() @property def empty_result_set_value(self): return self.value class RawSQL(Expression): def __init__(self, sql, params, output_field=None): if output_field is None: output_field = fields.Field() self.sql, self.params = sql, params super().__init__(output_field=output_field) def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.sql, self.params) def as_sql(self, compiler, connection): return "(%s)" % self.sql, self.params def get_group_by_cols(self): return [self] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # Resolve parents fields used in raw SQL. if query.model: for parent in query.model._meta.get_parent_list(): for parent_field in parent._meta.local_fields: _, column_name = parent_field.get_attname_column() if column_name.lower() in self.sql.lower(): query.resolve_ref( parent_field.name, allow_joins, reuse, summarize ) break return super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) class Star(Expression): def __repr__(self): return "'*'" def as_sql(self, compiler, connection): return "*", [] class Col(Expression): contains_column_references = True possibly_multivalued = False def __init__(self, alias, target, output_field=None): if output_field is None: output_field = target super().__init__(output_field=output_field) self.alias, self.target = alias, target def __repr__(self): alias, target = self.alias, self.target identifiers = (alias, str(target)) if alias else (str(target),) return "{}({})".format(self.__class__.__name__, ", ".join(identifiers)) def as_sql(self, compiler, connection): alias, column = self.alias, self.target.column identifiers = (alias, column) if alias else (column,) sql = ".".join(map(compiler.quote_name_unless_alias, identifiers)) return sql, [] def relabeled_clone(self, relabels): if self.alias is None: return self return self.__class__( relabels.get(self.alias, self.alias), self.target, self.output_field ) def get_group_by_cols(self): return [self] def get_db_converters(self, connection): if self.target == self.output_field: return self.output_field.get_db_converters(connection) return self.output_field.get_db_converters( connection ) + self.target.get_db_converters(connection) class Ref(Expression): """ Reference to column alias of the query. For example, Ref('sum_cost') in qs.annotate(sum_cost=Sum('cost')) query. """ def __init__(self, refs, source): super().__init__() self.refs, self.source = refs, source def __repr__(self): return "{}({}, {})".format(self.__class__.__name__, self.refs, self.source) def get_source_expressions(self): return [self.source] def set_source_expressions(self, exprs): (self.source,) = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # The sub-expression `source` has already been resolved, as this is # just a reference to the name of `source`. return self def get_refs(self): return {self.refs} def relabeled_clone(self, relabels): return self def as_sql(self, compiler, connection): return connection.ops.quote_name(self.refs), [] def get_group_by_cols(self): return [self] class ExpressionList(Func): """ An expression containing multiple expressions. Can be used to provide a list of expressions as an argument to another expression, like a partition clause. """ template = "%(expressions)s" def __init__(self, *expressions, **extra): if not expressions: raise ValueError( "%s requires at least one expression." % self.__class__.__name__ ) super().__init__(*expressions, **extra) def __str__(self): return self.arg_joiner.join(str(arg) for arg in self.source_expressions) def as_sqlite(self, compiler, connection, **extra_context): # Casting to numeric is unnecessary. return self.as_sql(compiler, connection, **extra_context) class OrderByList(Func): template = "ORDER BY %(expressions)s" def __init__(self, *expressions, **extra): expressions = ( ( OrderBy(F(expr[1:]), descending=True) if isinstance(expr, str) and expr[0] == "-" else expr ) for expr in expressions ) super().__init__(*expressions, **extra) def as_sql(self, *args, **kwargs): if not self.source_expressions: return "", () return super().as_sql(*args, **kwargs) def get_group_by_cols(self): group_by_cols = [] for order_by in self.get_source_expressions(): group_by_cols.extend(order_by.get_group_by_cols()) return group_by_cols @deconstructible(path="django.db.models.ExpressionWrapper") class ExpressionWrapper(SQLiteNumericMixin, Expression): """ An expression that can wrap another expression so that it can provide extra context to the inner expression, such as the output_field. """ def __init__(self, expression, output_field): super().__init__(output_field=output_field) self.expression = expression def set_source_expressions(self, exprs): self.expression = exprs[0] def get_source_expressions(self): return [self.expression] def get_group_by_cols(self): if isinstance(self.expression, Expression): expression = self.expression.copy() expression.output_field = self.output_field return expression.get_group_by_cols() # For non-expressions e.g. an SQL WHERE clause, the entire # `expression` must be included in the GROUP BY clause. return super().get_group_by_cols() def as_sql(self, compiler, connection): return compiler.compile(self.expression) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.expression) class NegatedExpression(ExpressionWrapper): """The logical negation of a conditional expression.""" def __init__(self, expression): super().__init__(expression, output_field=fields.BooleanField()) def __invert__(self): return self.expression.copy() def as_sql(self, compiler, connection): try: sql, params = super().as_sql(compiler, connection) except EmptyResultSet: features = compiler.connection.features if not features.supports_boolean_expr_in_select_clause: return "1=1", () return compiler.compile(Value(True)) ops = compiler.connection.ops # Some database backends (e.g. Oracle) don't allow EXISTS() and filters # to be compared to another expression unless they're wrapped in a CASE # WHEN. if not ops.conditional_expression_supported_in_where_clause(self.expression): return f"CASE WHEN {sql} = 0 THEN 1 ELSE 0 END", params return f"NOT {sql}", params def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): resolved = super().resolve_expression( query, allow_joins, reuse, summarize, for_save ) if not getattr(resolved.expression, "conditional", False): raise TypeError("Cannot negate non-conditional expressions.") return resolved def select_format(self, compiler, sql, params): # Wrap boolean expressions with a CASE WHEN expression if a database # backend (e.g. Oracle) doesn't support boolean expression in SELECT or # GROUP BY list. expression_supported_in_where_clause = ( compiler.connection.ops.conditional_expression_supported_in_where_clause ) if ( not compiler.connection.features.supports_boolean_expr_in_select_clause # Avoid double wrapping. and expression_supported_in_where_clause(self.expression) ): sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql) return sql, params @deconstructible(path="django.db.models.When") class When(Expression): template = "WHEN %(condition)s THEN %(result)s" # This isn't a complete conditional expression, must be used in Case(). conditional = False def __init__(self, condition=None, then=None, **lookups): if lookups: if condition is None: condition, lookups = Q(**lookups), None elif getattr(condition, "conditional", False): condition, lookups = Q(condition, **lookups), None if condition is None or not getattr(condition, "conditional", False) or lookups: raise TypeError( "When() supports a Q object, a boolean expression, or lookups " "as a condition." ) if isinstance(condition, Q) and not condition: raise ValueError("An empty Q() can't be used as a When() condition.") super().__init__(output_field=None) self.condition = condition self.result = self._parse_expressions(then)[0] def __str__(self): return "WHEN %r THEN %r" % (self.condition, self.result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_source_expressions(self): return [self.condition, self.result] def set_source_expressions(self, exprs): self.condition, self.result = exprs def get_source_fields(self): # We're only interested in the fields of the result expressions. return [self.result._output_field_or_none] def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize if hasattr(c.condition, "resolve_expression"): c.condition = c.condition.resolve_expression( query, allow_joins, reuse, summarize, False ) c.result = c.result.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def as_sql(self, compiler, connection, template=None, **extra_context): connection.ops.check_expression_support(self) template_params = extra_context sql_params = [] condition_sql, condition_params = compiler.compile(self.condition) template_params["condition"] = condition_sql result_sql, result_params = compiler.compile(self.result) template_params["result"] = result_sql template = template or self.template return template % template_params, ( *sql_params, *condition_params, *result_params, ) def get_group_by_cols(self): # This is not a complete expression and cannot be used in GROUP BY. cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols @deconstructible(path="django.db.models.Case") class Case(SQLiteNumericMixin, Expression): """ An SQL searched CASE expression: CASE WHEN n > 0 THEN 'positive' WHEN n < 0 THEN 'negative' ELSE 'zero' END """ template = "CASE %(cases)s ELSE %(default)s END" case_joiner = " " def __init__(self, *cases, default=None, output_field=None, **extra): if not all(isinstance(case, When) for case in cases): raise TypeError("Positional arguments must all be When objects.") super().__init__(output_field) self.cases = list(cases) self.default = self._parse_expressions(default)[0] self.extra = extra def __str__(self): return "CASE %s, ELSE %r" % ( ", ".join(str(c) for c in self.cases), self.default, ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_source_expressions(self): return self.cases + [self.default] def set_source_expressions(self, exprs): *self.cases, self.default = exprs def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize for pos, case in enumerate(c.cases): c.cases[pos] = case.resolve_expression( query, allow_joins, reuse, summarize, for_save ) c.default = c.default.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def copy(self): c = super().copy() c.cases = c.cases[:] return c def as_sql( self, compiler, connection, template=None, case_joiner=None, **extra_context ): connection.ops.check_expression_support(self) if not self.cases: return compiler.compile(self.default) template_params = {**self.extra, **extra_context} case_parts = [] sql_params = [] default_sql, default_params = compiler.compile(self.default) for case in self.cases: try: case_sql, case_params = compiler.compile(case) except EmptyResultSet: continue except FullResultSet: default_sql, default_params = compiler.compile(case.result) break case_parts.append(case_sql) sql_params.extend(case_params) if not case_parts: return default_sql, default_params case_joiner = case_joiner or self.case_joiner template_params["cases"] = case_joiner.join(case_parts) template_params["default"] = default_sql sql_params.extend(default_params) template = template or template_params.get("template", self.template) sql = template % template_params if self._output_field_or_none is not None: sql = connection.ops.unification_cast_sql(self.output_field) % sql return sql, sql_params def get_group_by_cols(self): if not self.cases: return self.default.get_group_by_cols() return super().get_group_by_cols() class Subquery(BaseExpression, Combinable): """ An explicit subquery. It may contain OuterRef() references to the outer query which will be resolved when it is applied to that query. """ template = "(%(subquery)s)" contains_aggregate = False empty_result_set_value = None def __init__(self, queryset, output_field=None, **extra): # Allow the usage of both QuerySet and sql.Query objects. self.query = getattr(queryset, "query", queryset).clone() self.query.subquery = True self.extra = extra super().__init__(output_field) def get_source_expressions(self): return [self.query] def set_source_expressions(self, exprs): self.query = exprs[0] def _resolve_output_field(self): return self.query.output_field def copy(self): clone = super().copy() clone.query = clone.query.clone() return clone @property def external_aliases(self): return self.query.external_aliases def get_external_cols(self): return self.query.get_external_cols() def as_sql(self, compiler, connection, template=None, **extra_context): connection.ops.check_expression_support(self) template_params = {**self.extra, **extra_context} subquery_sql, sql_params = self.query.as_sql(compiler, connection) template_params["subquery"] = subquery_sql[1:-1] template = template or template_params.get("template", self.template) sql = template % template_params return sql, sql_params def get_group_by_cols(self): return self.query.get_group_by_cols(wrapper=self) class Exists(Subquery): template = "EXISTS(%(subquery)s)" output_field = fields.BooleanField() empty_result_set_value = False def __init__(self, queryset, **kwargs): super().__init__(queryset, **kwargs) self.query = self.query.exists() def select_format(self, compiler, sql, params): # Wrap EXISTS() with a CASE WHEN expression if a database backend # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP # BY list. if not compiler.connection.features.supports_boolean_expr_in_select_clause: sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql) return sql, params @deconstructible(path="django.db.models.OrderBy") class OrderBy(Expression): template = "%(expression)s %(ordering)s" conditional = False def __init__(self, expression, descending=False, nulls_first=None, nulls_last=None): if nulls_first and nulls_last: raise ValueError("nulls_first and nulls_last are mutually exclusive") if nulls_first is False or nulls_last is False: raise ValueError("nulls_first and nulls_last values must be True or None.") self.nulls_first = nulls_first self.nulls_last = nulls_last self.descending = descending if not hasattr(expression, "resolve_expression"): raise ValueError("expression must be an expression type") self.expression = expression def __repr__(self): return "{}({}, descending={})".format( self.__class__.__name__, self.expression, self.descending ) def set_source_expressions(self, exprs): self.expression = exprs[0] def get_source_expressions(self): return [self.expression] def as_sql(self, compiler, connection, template=None, **extra_context): template = template or self.template if connection.features.supports_order_by_nulls_modifier: if self.nulls_last: template = "%s NULLS LAST" % template elif self.nulls_first: template = "%s NULLS FIRST" % template else: if self.nulls_last and not ( self.descending and connection.features.order_by_nulls_first ): template = "%%(expression)s IS NULL, %s" % template elif self.nulls_first and not ( not self.descending and connection.features.order_by_nulls_first ): template = "%%(expression)s IS NOT NULL, %s" % template connection.ops.check_expression_support(self) expression_sql, params = compiler.compile(self.expression) placeholders = { "expression": expression_sql, "ordering": "DESC" if self.descending else "ASC", **extra_context, } params *= template.count("%(expression)s") return (template % placeholders).rstrip(), params def as_oracle(self, compiler, connection): # Oracle doesn't allow ORDER BY EXISTS() or filters unless it's wrapped # in a CASE WHEN. if connection.ops.conditional_expression_supported_in_where_clause( self.expression ): copy = self.copy() copy.expression = Case( When(self.expression, then=True), default=False, ) return copy.as_sql(compiler, connection) return self.as_sql(compiler, connection) def get_group_by_cols(self): cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def reverse_ordering(self): self.descending = not self.descending if self.nulls_first: self.nulls_last = True self.nulls_first = None elif self.nulls_last: self.nulls_first = True self.nulls_last = None return self def asc(self): self.descending = False def desc(self): self.descending = True class Window(SQLiteNumericMixin, Expression): template = "%(expression)s OVER (%(window)s)" # Although the main expression may either be an aggregate or an # expression with an aggregate function, the GROUP BY that will # be introduced in the query as a result is not desired. contains_aggregate = False contains_over_clause = True def __init__( self, expression, partition_by=None, order_by=None, frame=None, output_field=None, ): self.partition_by = partition_by self.order_by = order_by self.frame = frame if not getattr(expression, "window_compatible", False): raise ValueError( "Expression '%s' isn't compatible with OVER clauses." % expression.__class__.__name__ ) if self.partition_by is not None: if not isinstance(self.partition_by, (tuple, list)): self.partition_by = (self.partition_by,) self.partition_by = ExpressionList(*self.partition_by) if self.order_by is not None: if isinstance(self.order_by, (list, tuple)): self.order_by = OrderByList(*self.order_by) elif isinstance(self.order_by, (BaseExpression, str)): self.order_by = OrderByList(self.order_by) else: raise ValueError( "Window.order_by must be either a string reference to a " "field, an expression, or a list or tuple of them." ) super().__init__(output_field=output_field) self.source_expression = self._parse_expressions(expression)[0] def _resolve_output_field(self): return self.source_expression.output_field def get_source_expressions(self): return [self.source_expression, self.partition_by, self.order_by, self.frame] def set_source_expressions(self, exprs): self.source_expression, self.partition_by, self.order_by, self.frame = exprs def as_sql(self, compiler, connection, template=None): connection.ops.check_expression_support(self) if not connection.features.supports_over_clause: raise NotSupportedError("This backend does not support window expressions.") expr_sql, params = compiler.compile(self.source_expression) window_sql, window_params = [], () if self.partition_by is not None: sql_expr, sql_params = self.partition_by.as_sql( compiler=compiler, connection=connection, template="PARTITION BY %(expressions)s", ) window_sql.append(sql_expr) window_params += tuple(sql_params) if self.order_by is not None: order_sql, order_params = compiler.compile(self.order_by) window_sql.append(order_sql) window_params += tuple(order_params) if self.frame: frame_sql, frame_params = compiler.compile(self.frame) window_sql.append(frame_sql) window_params += tuple(frame_params) template = template or self.template return ( template % {"expression": expr_sql, "window": " ".join(window_sql).strip()}, (*params, *window_params), ) def as_sqlite(self, compiler, connection): if isinstance(self.output_field, fields.DecimalField): # Casting to numeric must be outside of the window expression. copy = self.copy() source_expressions = copy.get_source_expressions() source_expressions[0].output_field = fields.FloatField() copy.set_source_expressions(source_expressions) return super(Window, copy).as_sqlite(compiler, connection) return self.as_sql(compiler, connection) def __str__(self): return "{} OVER ({}{}{})".format( str(self.source_expression), "PARTITION BY " + str(self.partition_by) if self.partition_by else "", str(self.order_by or ""), str(self.frame or ""), ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_group_by_cols(self): group_by_cols = [] if self.partition_by: group_by_cols.extend(self.partition_by.get_group_by_cols()) if self.order_by is not None: group_by_cols.extend(self.order_by.get_group_by_cols()) return group_by_cols class WindowFrame(Expression): """ Model the frame clause in window expressions. There are two types of frame clauses which are subclasses, however, all processing and validation (by no means intended to be complete) is done here. Thus, providing an end for a frame is optional (the default is UNBOUNDED FOLLOWING, which is the last row in the frame). """ template = "%(frame_type)s BETWEEN %(start)s AND %(end)s" def __init__(self, start=None, end=None): self.start = Value(start) self.end = Value(end) def set_source_expressions(self, exprs): self.start, self.end = exprs def get_source_expressions(self): return [self.start, self.end] def as_sql(self, compiler, connection): connection.ops.check_expression_support(self) start, end = self.window_frame_start_end( connection, self.start.value, self.end.value ) return ( self.template % { "frame_type": self.frame_type, "start": start, "end": end, }, [], ) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def get_group_by_cols(self): return [] def __str__(self): if self.start.value is not None and self.start.value < 0: start = "%d %s" % (abs(self.start.value), connection.ops.PRECEDING) elif self.start.value is not None and self.start.value == 0: start = connection.ops.CURRENT_ROW else: start = connection.ops.UNBOUNDED_PRECEDING if self.end.value is not None and self.end.value > 0: end = "%d %s" % (self.end.value, connection.ops.FOLLOWING) elif self.end.value is not None and self.end.value == 0: end = connection.ops.CURRENT_ROW else: end = connection.ops.UNBOUNDED_FOLLOWING return self.template % { "frame_type": self.frame_type, "start": start, "end": end, } def window_frame_start_end(self, connection, start, end): raise NotImplementedError("Subclasses must implement window_frame_start_end().") class RowRange(WindowFrame): frame_type = "ROWS" def window_frame_start_end(self, connection, start, end): return connection.ops.window_frame_rows_start_end(start, end) class ValueRange(WindowFrame): frame_type = "RANGE" def window_frame_start_end(self, connection, start, end): return connection.ops.window_frame_range_start_end(start, end)
0a418328ac6c640b347382c42f519f9b6cb8e542464588722da3f08a0c57a45b
import datetime import posixpath from django import forms from django.core import checks from django.core.files.base import File from django.core.files.images import ImageFile from django.core.files.storage import Storage, default_storage from django.core.files.utils import validate_file_name from django.db.models import signals from django.db.models.fields import Field from django.db.models.query_utils import DeferredAttribute from django.db.models.utils import AltersData from django.utils.translation import gettext_lazy as _ class FieldFile(File, AltersData): def __init__(self, instance, field, name): super().__init__(None, name) self.instance = instance self.field = field self.storage = field.storage self._committed = True def __eq__(self, other): # Older code may be expecting FileField values to be simple strings. # By overriding the == operator, it can remain backwards compatibility. if hasattr(other, "name"): return self.name == other.name return self.name == other def __hash__(self): return hash(self.name) # The standard File contains most of the necessary properties, but # FieldFiles can be instantiated without a name, so that needs to # be checked for here. def _require_file(self): if not self: raise ValueError( "The '%s' attribute has no file associated with it." % self.field.name ) def _get_file(self): self._require_file() if getattr(self, "_file", None) is None: self._file = self.storage.open(self.name, "rb") return self._file def _set_file(self, file): self._file = file def _del_file(self): del self._file file = property(_get_file, _set_file, _del_file) @property def path(self): self._require_file() return self.storage.path(self.name) @property def url(self): self._require_file() return self.storage.url(self.name) @property def size(self): self._require_file() if not self._committed: return self.file.size return self.storage.size(self.name) def open(self, mode="rb"): self._require_file() if getattr(self, "_file", None) is None: self.file = self.storage.open(self.name, mode) else: self.file.open(mode) return self # open() doesn't alter the file's contents, but it does reset the pointer open.alters_data = True # In addition to the standard File API, FieldFiles have extra methods # to further manipulate the underlying file, as well as update the # associated model instance. def save(self, name, content, save=True): name = self.field.generate_filename(self.instance, name) self.name = self.storage.save(name, content, max_length=self.field.max_length) setattr(self.instance, self.field.attname, self.name) self._committed = True # Save the object because it has changed, unless save is False if save: self.instance.save() save.alters_data = True def delete(self, save=True): if not self: return # Only close the file if it's already open, which we know by the # presence of self._file if hasattr(self, "_file"): self.close() del self.file self.storage.delete(self.name) self.name = None setattr(self.instance, self.field.attname, self.name) self._committed = False if save: self.instance.save() delete.alters_data = True @property def closed(self): file = getattr(self, "_file", None) return file is None or file.closed def close(self): file = getattr(self, "_file", None) if file is not None: file.close() def __getstate__(self): # FieldFile needs access to its associated model field, an instance and # the file's name. Everything else will be restored later, by # FileDescriptor below. return { "name": self.name, "closed": False, "_committed": True, "_file": None, "instance": self.instance, "field": self.field, } def __setstate__(self, state): self.__dict__.update(state) self.storage = self.field.storage class FileDescriptor(DeferredAttribute): """ The descriptor for the file attribute on the model instance. Return a FieldFile when accessed so you can write code like:: >>> from myapp.models import MyModel >>> instance = MyModel.objects.get(pk=1) >>> instance.file.size Assign a file object on assignment so you can do:: >>> with open('/path/to/hello.world') as f: ... instance.file = File(f) """ def __get__(self, instance, cls=None): if instance is None: return self # This is slightly complicated, so worth an explanation. # instance.file needs to ultimately return some instance of `File`, # probably a subclass. Additionally, this returned object needs to have # the FieldFile API so that users can easily do things like # instance.file.path and have that delegated to the file storage engine. # Easy enough if we're strict about assignment in __set__, but if you # peek below you can see that we're not. So depending on the current # value of the field we have to dynamically construct some sort of # "thing" to return. # The instance dict contains whatever was originally assigned # in __set__. file = super().__get__(instance, cls) # If this value is a string (instance.file = "path/to/file") or None # then we simply wrap it with the appropriate attribute class according # to the file field. [This is FieldFile for FileFields and # ImageFieldFile for ImageFields; it's also conceivable that user # subclasses might also want to subclass the attribute class]. This # object understands how to convert a path to a file, and also how to # handle None. if isinstance(file, str) or file is None: attr = self.field.attr_class(instance, self.field, file) instance.__dict__[self.field.attname] = attr # Other types of files may be assigned as well, but they need to have # the FieldFile interface added to them. Thus, we wrap any other type of # File inside a FieldFile (well, the field's attr_class, which is # usually FieldFile). elif isinstance(file, File) and not isinstance(file, FieldFile): file_copy = self.field.attr_class(instance, self.field, file.name) file_copy.file = file file_copy._committed = False instance.__dict__[self.field.attname] = file_copy # Finally, because of the (some would say boneheaded) way pickle works, # the underlying FieldFile might not actually itself have an associated # file. So we need to reset the details of the FieldFile in those cases. elif isinstance(file, FieldFile) and not hasattr(file, "field"): file.instance = instance file.field = self.field file.storage = self.field.storage # Make sure that the instance is correct. elif isinstance(file, FieldFile) and instance is not file.instance: file.instance = instance # That was fun, wasn't it? return instance.__dict__[self.field.attname] def __set__(self, instance, value): instance.__dict__[self.field.attname] = value class FileField(Field): # The class to wrap instance attributes in. Accessing the file object off # the instance will always return an instance of attr_class. attr_class = FieldFile # The descriptor to use for accessing the attribute off of the class. descriptor_class = FileDescriptor description = _("File") def __init__( self, verbose_name=None, name=None, upload_to="", storage=None, **kwargs ): self._primary_key_set_explicitly = "primary_key" in kwargs self.storage = storage or default_storage if callable(self.storage): # Hold a reference to the callable for deconstruct(). self._storage_callable = self.storage self.storage = self.storage() if not isinstance(self.storage, Storage): raise TypeError( "%s.storage must be a subclass/instance of %s.%s" % ( self.__class__.__qualname__, Storage.__module__, Storage.__qualname__, ) ) self.upload_to = upload_to kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), *self._check_upload_to(), ] def _check_primary_key(self): if self._primary_key_set_explicitly: return [ checks.Error( "'primary_key' is not a valid argument for a %s." % self.__class__.__name__, obj=self, id="fields.E201", ) ] else: return [] def _check_upload_to(self): if isinstance(self.upload_to, str) and self.upload_to.startswith("/"): return [ checks.Error( "%s's 'upload_to' argument must be a relative path, not an " "absolute path." % self.__class__.__name__, obj=self, id="fields.E202", hint="Remove the leading slash.", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 100: del kwargs["max_length"] kwargs["upload_to"] = self.upload_to storage = getattr(self, "_storage_callable", self.storage) if storage is not default_storage: kwargs["storage"] = storage return name, path, args, kwargs def get_internal_type(self): return "FileField" def get_prep_value(self, value): value = super().get_prep_value(value) # Need to convert File objects provided via a form to string for # database insertion. if value is None: return None return str(value) def pre_save(self, model_instance, add): file = super().pre_save(model_instance, add) if file and not file._committed: # Commit the file to storage prior to saving the model file.save(file.name, file.file, save=False) return file def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) setattr(cls, self.attname, self.descriptor_class(self)) def generate_filename(self, instance, filename): """ Apply (if callable) or prepend (if a string) upload_to to the filename, then delegate further processing of the name to the storage backend. Until the storage layer, all file paths are expected to be Unix style (with forward slashes). """ if callable(self.upload_to): filename = self.upload_to(instance, filename) else: dirname = datetime.datetime.now().strftime(str(self.upload_to)) filename = posixpath.join(dirname, filename) filename = validate_file_name(filename, allow_relative_path=True) return self.storage.generate_filename(filename) def save_form_data(self, instance, data): # Important: None means "no change", other false value means "clear" # This subtle distinction (rather than a more explicit marker) is # needed because we need to consume values that are also sane for a # regular (non Model-) Form to find in its cleaned_data dictionary. if data is not None: # This value will be converted to str and stored in the # database, so leaving False as-is is not acceptable. setattr(instance, self.name, data or "") def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FileField, "max_length": self.max_length, **kwargs, } ) class ImageFileDescriptor(FileDescriptor): """ Just like the FileDescriptor, but for ImageFields. The only difference is assigning the width/height to the width_field/height_field, if appropriate. """ def __set__(self, instance, value): previous_file = instance.__dict__.get(self.field.attname) super().__set__(instance, value) # To prevent recalculating image dimensions when we are instantiating # an object from the database (bug #11084), only update dimensions if # the field had a value before this assignment. Since the default # value for FileField subclasses is an instance of field.attr_class, # previous_file will only be None when we are called from # Model.__init__(). The ImageField.update_dimension_fields method # hooked up to the post_init signal handles the Model.__init__() cases. # Assignment happening outside of Model.__init__() will trigger the # update right here. if previous_file is not None: self.field.update_dimension_fields(instance, force=True) class ImageFieldFile(ImageFile, FieldFile): def delete(self, save=True): # Clear the image dimensions cache if hasattr(self, "_dimensions_cache"): del self._dimensions_cache super().delete(save) class ImageField(FileField): attr_class = ImageFieldFile descriptor_class = ImageFileDescriptor description = _("Image") def __init__( self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs, ): self.width_field, self.height_field = width_field, height_field super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_image_library_installed(), ] def _check_image_library_installed(self): try: from PIL import Image # NOQA except ImportError: return [ checks.Error( "Cannot use ImageField because Pillow is not installed.", hint=( "Get Pillow at https://pypi.org/project/Pillow/ " 'or run command "python -m pip install Pillow".' ), obj=self, id="fields.E210", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.width_field: kwargs["width_field"] = self.width_field if self.height_field: kwargs["height_field"] = self.height_field return name, path, args, kwargs def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) # Attach update_dimension_fields so that dimension fields declared # after their corresponding image field don't stay cleared by # Model.__init__, see bug #11196. # Only run post-initialization dimension update on non-abstract models if not cls._meta.abstract: signals.post_init.connect(self.update_dimension_fields, sender=cls) def update_dimension_fields(self, instance, force=False, *args, **kwargs): """ Update field's width and height fields, if defined. This method is hooked up to model's post_init signal to update dimensions after instantiating a model instance. However, dimensions won't be updated if the dimensions fields are already populated. This avoids unnecessary recalculation when loading an object from the database. Dimensions can be forced to update with force=True, which is how ImageFileDescriptor.__set__ calls this method. """ # Nothing to update if the field doesn't have dimension fields or if # the field is deferred. has_dimension_fields = self.width_field or self.height_field if not has_dimension_fields or self.attname not in instance.__dict__: return # getattr will call the ImageFileDescriptor's __get__ method, which # coerces the assigned value into an instance of self.attr_class # (ImageFieldFile in this case). file = getattr(instance, self.attname) # Nothing to update if we have no file and not being forced to update. if not file and not force: return dimension_fields_filled = not ( (self.width_field and not getattr(instance, self.width_field)) or (self.height_field and not getattr(instance, self.height_field)) ) # When both dimension fields have values, we are most likely loading # data from the database or updating an image field that already had # an image stored. In the first case, we don't want to update the # dimension fields because we are already getting their values from the # database. In the second case, we do want to update the dimensions # fields and will skip this return because force will be True since we # were called from ImageFileDescriptor.__set__. if dimension_fields_filled and not force: return # file should be an instance of ImageFieldFile or should be None. if file: width = file.width height = file.height else: # No file, so clear dimensions fields. width = None height = None # Update the width and height fields. if self.width_field: setattr(instance, self.width_field, width) if self.height_field: setattr(instance, self.height_field, height) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.ImageField, **kwargs, } )
9e24561bf3acccb3876a13e367a255d69bb1dabfa48a5ed54252f879559f18b5
from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.ddl_references import IndexColumns from django.db.backends.postgresql.psycopg_any import sql from django.db.backends.utils import strip_quotes class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): # Setting all constraints to IMMEDIATE to allow changing data in the same # transaction. sql_update_with_default = ( "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL" "; SET CONSTRAINTS ALL IMMEDIATE" ) sql_alter_sequence_type = "ALTER SEQUENCE IF EXISTS %(sequence)s AS %(type)s" sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE" sql_create_index = ( "CREATE INDEX %(name)s ON %(table)s%(using)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_create_index_concurrently = ( "CREATE INDEX CONCURRENTLY %(name)s ON %(table)s%(using)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_delete_index = "DROP INDEX IF EXISTS %(name)s" sql_delete_index_concurrently = "DROP INDEX CONCURRENTLY IF EXISTS %(name)s" # Setting the constraint to IMMEDIATE to allow changing data in the same # transaction. sql_create_column_inline_fk = ( "CONSTRAINT %(name)s REFERENCES %(to_table)s(%(to_column)s)%(deferrable)s" "; SET CONSTRAINTS %(namespace)s%(name)s IMMEDIATE" ) # Setting the constraint to IMMEDIATE runs any deferred checks to allow # dropping it in the same transaction. sql_delete_fk = ( "SET CONSTRAINTS %(name)s IMMEDIATE; " "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s" ) sql_delete_procedure = "DROP FUNCTION %(procedure)s(%(param_types)s)" def execute(self, sql, params=()): # Merge the query client-side, as PostgreSQL won't do it server-side. if params is None: return super().execute(sql, params) sql = self.connection.ops.compose_sql(str(sql), params) # Don't let the superclass touch anything. return super().execute(sql, None) sql_add_identity = ( "ALTER TABLE %(table)s ALTER COLUMN %(column)s ADD " "GENERATED BY DEFAULT AS IDENTITY" ) sql_drop_indentity = ( "ALTER TABLE %(table)s ALTER COLUMN %(column)s DROP IDENTITY IF EXISTS" ) def quote_value(self, value): if isinstance(value, str): value = value.replace("%", "%%") return sql.quote(value, self.connection.connection) def _field_indexes_sql(self, model, field): output = super()._field_indexes_sql(model, field) like_index_statement = self._create_like_index_sql(model, field) if like_index_statement is not None: output.append(like_index_statement) return output def _field_data_type(self, field): if field.is_relation: return field.rel_db_type(self.connection) return self.connection.data_types.get( field.get_internal_type(), field.db_type(self.connection), ) def _field_base_data_types(self, field): # Yield base data types for array fields. if field.base_field.get_internal_type() == "ArrayField": yield from self._field_base_data_types(field.base_field) else: yield self._field_data_type(field.base_field) def _create_like_index_sql(self, model, field): """ Return the statement to create an index with varchar operator pattern when the column type is 'varchar' or 'text', otherwise return None. """ db_type = field.db_type(connection=self.connection) if db_type is not None and (field.db_index or field.unique): # Fields with database column types of `varchar` and `text` need # a second index that specifies their operator class, which is # needed when performing correct LIKE queries outside the # C locale. See #12234. # # The same doesn't apply to array fields such as varchar[size] # and text[size], so skip them. if "[" in db_type: return None # Non-deterministic collations on Postgresql don't support indexes # for operator classes varchar_pattern_ops/text_pattern_ops. if getattr(field, "db_collation", None): return None if db_type.startswith("varchar"): return self._create_index_sql( model, fields=[field], suffix="_like", opclasses=["varchar_pattern_ops"], ) elif db_type.startswith("text"): return self._create_index_sql( model, fields=[field], suffix="_like", opclasses=["text_pattern_ops"], ) return None def _using_sql(self, new_field, old_field): using_sql = " USING %(column)s::%(type)s" new_internal_type = new_field.get_internal_type() old_internal_type = old_field.get_internal_type() if new_internal_type == "ArrayField" and new_internal_type == old_internal_type: # Compare base data types for array fields. if list(self._field_base_data_types(old_field)) != list( self._field_base_data_types(new_field) ): return using_sql elif self._field_data_type(old_field) != self._field_data_type(new_field): return using_sql return "" def _get_sequence_name(self, table, column): with self.connection.cursor() as cursor: for sequence in self.connection.introspection.get_sequences(cursor, table): if sequence["column"] == column: return sequence["name"] return None def _alter_column_type_sql( self, model, old_field, new_field, new_type, old_collation, new_collation ): # Drop indexes on varchar/text/citext columns that are changing to a # different type. old_db_params = old_field.db_parameters(connection=self.connection) old_type = old_db_params["type"] if (old_field.db_index or old_field.unique) and ( (old_type.startswith("varchar") and not new_type.startswith("varchar")) or (old_type.startswith("text") and not new_type.startswith("text")) or (old_type.startswith("citext") and not new_type.startswith("citext")) ): index_name = self._create_index_name( model._meta.db_table, [old_field.column], suffix="_like" ) self.execute(self._delete_index_sql(model, index_name)) self.sql_alter_column_type = ( "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s" ) # Cast when data type changed. if using_sql := self._using_sql(new_field, old_field): self.sql_alter_column_type += using_sql new_internal_type = new_field.get_internal_type() old_internal_type = old_field.get_internal_type() # Make ALTER TYPE with IDENTITY make sense. table = strip_quotes(model._meta.db_table) auto_field_types = { "AutoField", "BigAutoField", "SmallAutoField", } old_is_auto = old_internal_type in auto_field_types new_is_auto = new_internal_type in auto_field_types if new_is_auto and not old_is_auto: column = strip_quotes(new_field.column) return ( ( self.sql_alter_column_type % { "column": self.quote_name(column), "type": new_type, "collation": "", }, [], ), [ ( self.sql_add_identity % { "table": self.quote_name(table), "column": self.quote_name(column), }, [], ), ], ) elif old_is_auto and not new_is_auto: # Drop IDENTITY if exists (pre-Django 4.1 serial columns don't have # it). self.execute( self.sql_drop_indentity % { "table": self.quote_name(table), "column": self.quote_name(strip_quotes(new_field.column)), } ) column = strip_quotes(new_field.column) fragment, _ = super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) # Drop the sequence if exists (Django 4.1+ identity columns don't # have it). other_actions = [] if sequence_name := self._get_sequence_name(table, column): other_actions = [ ( self.sql_delete_sequence % { "sequence": self.quote_name(sequence_name), }, [], ) ] return fragment, other_actions elif new_is_auto and old_is_auto and old_internal_type != new_internal_type: fragment, _ = super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) column = strip_quotes(new_field.column) db_types = { "AutoField": "integer", "BigAutoField": "bigint", "SmallAutoField": "smallint", } # Alter the sequence type if exists (Django 4.1+ identity columns # don't have it). other_actions = [] if sequence_name := self._get_sequence_name(table, column): other_actions = [ ( self.sql_alter_sequence_type % { "sequence": self.quote_name(sequence_name), "type": db_types[new_internal_type], }, [], ), ] return fragment, other_actions else: return super()._alter_column_type_sql( model, old_field, new_field, new_type, old_collation, new_collation ) def _alter_column_collation_sql( self, model, new_field, new_type, new_collation, old_field ): sql = self.sql_alter_column_collate # Cast when data type changed. if using_sql := self._using_sql(new_field, old_field): sql += using_sql return ( sql % { "column": self.quote_name(new_field.column), "type": new_type, "collation": " " + self._collate_sql(new_collation) if new_collation else "", }, [], ) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): super()._alter_field( model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict, ) # Added an index? Create any PostgreSQL-specific indexes. if (not (old_field.db_index or old_field.unique) and new_field.db_index) or ( not old_field.unique and new_field.unique ): like_index_statement = self._create_like_index_sql(model, new_field) if like_index_statement is not None: self.execute(like_index_statement) # Removed an index? Drop any PostgreSQL-specific indexes. if old_field.unique and not (new_field.db_index or new_field.unique): index_to_remove = self._create_index_name( model._meta.db_table, [old_field.column], suffix="_like" ) self.execute(self._delete_index_sql(model, index_to_remove)) def _index_columns(self, table, columns, col_suffixes, opclasses): if opclasses: return IndexColumns( table, columns, self.quote_name, col_suffixes=col_suffixes, opclasses=opclasses, ) return super()._index_columns(table, columns, col_suffixes, opclasses) def add_index(self, model, index, concurrently=False): self.execute( index.create_sql(model, self, concurrently=concurrently), params=None ) def remove_index(self, model, index, concurrently=False): self.execute(index.remove_sql(model, self, concurrently=concurrently)) def _delete_index_sql(self, model, name, sql=None, concurrently=False): sql = ( self.sql_delete_index_concurrently if concurrently else self.sql_delete_index ) return super()._delete_index_sql(model, name, sql) def _create_index_sql( self, model, *, fields=None, name=None, suffix="", using="", db_tablespace=None, col_suffixes=(), sql=None, opclasses=(), condition=None, concurrently=False, include=None, expressions=None, ): sql = sql or ( self.sql_create_index if not concurrently else self.sql_create_index_concurrently ) return super()._create_index_sql( model, fields=fields, name=name, suffix=suffix, using=using, db_tablespace=db_tablespace, col_suffixes=col_suffixes, sql=sql, opclasses=opclasses, condition=condition, include=include, expressions=expressions, )
84134d4324d658b0c87873ce494d6dd2a5341a731a7c6732a0292737e4b452b5
""" Base classes for writing management commands (named commands which can be executed through ``django-admin`` or ``manage.py``). """ import argparse import os import sys from argparse import ArgumentParser, HelpFormatter from functools import partial from io import TextIOBase import django from django.core import checks from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style, no_style from django.db import DEFAULT_DB_ALIAS, connections ALL_CHECKS = "__all__" class CommandError(Exception): """ Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. """ def __init__(self, *args, returncode=1, **kwargs): self.returncode = returncode super().__init__(*args, **kwargs) class SystemCheckError(CommandError): """ The system check framework detected unrecoverable errors. """ pass class CommandParser(ArgumentParser): """ Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically. """ def __init__( self, *, missing_args_message=None, called_from_command_line=None, **kwargs ): self.missing_args_message = missing_args_message self.called_from_command_line = called_from_command_line super().__init__(**kwargs) def parse_args(self, args=None, namespace=None): # Catch missing argument for a better error message if self.missing_args_message and not ( args or any(not arg.startswith("-") for arg in args) ): self.error(self.missing_args_message) return super().parse_args(args, namespace) def error(self, message): if self.called_from_command_line: super().error(message) else: raise CommandError("Error: %s" % message) def add_subparsers(self, **kwargs): parser_class = kwargs.get("parser_class", type(self)) if issubclass(parser_class, CommandParser): kwargs["parser_class"] = partial( parser_class, called_from_command_line=self.called_from_command_line, ) return super().add_subparsers(**kwargs) def handle_default_options(options): """ Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands. """ if options.settings: os.environ["DJANGO_SETTINGS_MODULE"] = options.settings if options.pythonpath: sys.path.insert(0, options.pythonpath) def no_translations(handle_func): """Decorator that forces a command to run with translations deactivated.""" def wrapper(*args, **kwargs): from django.utils import translation saved_locale = translation.get_language() translation.deactivate_all() try: res = handle_func(*args, **kwargs) finally: if saved_locale is not None: translation.activate(saved_locale) return res return wrapper class DjangoHelpFormatter(HelpFormatter): """ Customized formatter so that command-specific arguments appear in the --help output before arguments common to all commands. """ show_last = { "--version", "--verbosity", "--traceback", "--settings", "--pythonpath", "--no-color", "--force-color", "--skip-checks", } def _reordered_actions(self, actions): return sorted( actions, key=lambda a: set(a.option_strings) & self.show_last != set() ) def add_usage(self, usage, actions, *args, **kwargs): super().add_usage(usage, self._reordered_actions(actions), *args, **kwargs) def add_arguments(self, actions): super().add_arguments(self._reordered_actions(actions)) class OutputWrapper(TextIOBase): """ Wrapper around stdout/stderr """ @property def style_func(self): return self._style_func @style_func.setter def style_func(self, style_func): if style_func and self.isatty(): self._style_func = style_func else: self._style_func = lambda x: x def __init__(self, out, ending="\n"): self._out = out self.style_func = None self.ending = ending def __getattr__(self, name): return getattr(self._out, name) def flush(self): if hasattr(self._out, "flush"): self._out.flush() def isatty(self): return hasattr(self._out, "isatty") and self._out.isatty() def write(self, msg="", style_func=None, ending=None): ending = self.ending if ending is None else ending if ending and not msg.endswith(ending): msg += ending style_func = style_func or self.style_func self._out.write(style_func(msg)) class BaseCommand: """ The base class from which all management commands ultimately derive. Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don't need to change any of that behavior, consider using one of the subclasses defined in this file. If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows: 1. ``django-admin`` or ``manage.py`` loads the command class and calls its ``run_from_argv()`` method. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get an ``ArgumentParser`` for the arguments, parses them, performs any environment changes requested by options like ``pythonpath``, and then calls the ``execute()`` method, passing the parsed arguments. 3. The ``execute()`` method attempts to carry out the command by calling the ``handle()`` method with the parsed arguments; any output produced by ``handle()`` will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``. 4. If ``handle()`` or ``execute()`` raised any exception (e.g. ``CommandError``), ``run_from_argv()`` will instead print an error message to ``stderr``. Thus, the ``handle()`` method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in ``handle()``, or perform some additional parsing work in ``handle()`` and then delegate from it to more specialized methods as needed. Several attributes affect behavior at various steps along the way: ``help`` A short description of the command, which will be printed in help messages. ``output_transaction`` A boolean indicating whether the command outputs SQL statements; if ``True``, the output will automatically be wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is ``False``. ``requires_migrations_checks`` A boolean; if ``True``, the command prints a warning if the set of migrations on disk don't match the migrations in the database. ``requires_system_checks`` A list or tuple of tags, e.g. [Tags.staticfiles, Tags.models]. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value '__all__' can be used to specify that all system checks should be performed. Default value is '__all__'. To validate an individual application's models rather than all applications' models, call ``self.check(app_configs)`` from ``handle()``, where ``app_configs`` is the list of application's configuration provided by the app registry. ``stealth_options`` A tuple of any options the command uses which aren't defined by the argument parser. """ # Metadata about this command. help = "" # Configuration shortcuts that alter various logic. _called_from_command_line = False output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;" requires_migrations_checks = False requires_system_checks = "__all__" # Arguments, common to all commands, which aren't defined by the argument # parser. base_stealth_options = ("stderr", "stdout") # Command-specific options not defined by the argument parser. stealth_options = () suppressed_base_arguments = set() def __init__(self, stdout=None, stderr=None, no_color=False, force_color=False): self.stdout = OutputWrapper(stdout or sys.stdout) self.stderr = OutputWrapper(stderr or sys.stderr) if no_color and force_color: raise CommandError("'no_color' and 'force_color' can't be used together.") if no_color: self.style = no_style() else: self.style = color_style(force_color) self.stderr.style_func = self.style.ERROR if ( not isinstance(self.requires_system_checks, (list, tuple)) and self.requires_system_checks != ALL_CHECKS ): raise TypeError("requires_system_checks must be a list or tuple.") def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version. """ return django.get_version() def create_parser(self, prog_name, subcommand, **kwargs): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ kwargs.setdefault("formatter_class", DjangoHelpFormatter) parser = CommandParser( prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None, missing_args_message=getattr(self, "missing_args_message", None), called_from_command_line=getattr(self, "_called_from_command_line", None), **kwargs, ) self.add_base_argument( parser, "--version", action="version", version=self.get_version(), help="Show program's version number and exit.", ) self.add_base_argument( parser, "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help=( "Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, " "3=very verbose output" ), ) self.add_base_argument( parser, "--settings", help=( "The Python path to a settings module, e.g. " '"myproject.settings.main". If this isn\'t provided, the ' "DJANGO_SETTINGS_MODULE environment variable will be used." ), ) self.add_base_argument( parser, "--pythonpath", help=( "A directory to add to the Python path, e.g. " '"/home/djangoprojects/myproject".' ), ) self.add_base_argument( parser, "--traceback", action="store_true", help="Raise on CommandError exceptions.", ) self.add_base_argument( parser, "--no-color", action="store_true", help="Don't colorize the command output.", ) self.add_base_argument( parser, "--force-color", action="store_true", help="Force colorization of the command output.", ) if self.requires_system_checks: parser.add_argument( "--skip-checks", action="store_true", help="Skip system checks.", ) self.add_arguments(parser) return parser def add_arguments(self, parser): """ Entry point for subclassed commands to add custom arguments. """ pass def add_base_argument(self, parser, *args, **kwargs): """ Call the parser's add_argument() method, suppressing the help text according to BaseCommand.suppressed_base_arguments. """ for arg in args: if arg in self.suppressed_base_arguments: kwargs["help"] = argparse.SUPPRESS break parser.add_argument(*args, **kwargs) def print_help(self, prog_name, subcommand): """ Print the help message for this command, derived from ``self.usage()``. """ parser = self.create_parser(prog_name, subcommand) parser.print_help() def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. """ self._called_from_command_line = True parser = self.create_parser(argv[0], argv[1]) options = parser.parse_args(argv[2:]) cmd_options = vars(options) # Move positional args out of options to mimic legacy optparse args = cmd_options.pop("args", ()) handle_default_options(options) try: self.execute(*args, **cmd_options) except CommandError as e: if options.traceback: raise # SystemCheckError takes care of its own formatting. if isinstance(e, SystemCheckError): self.stderr.write(str(e), lambda x: x) else: self.stderr.write("%s: %s" % (e.__class__.__name__, e)) sys.exit(e.returncode) finally: try: connections.close_all() except ImproperlyConfigured: # Ignore if connections aren't setup at this point (e.g. no # configured settings). pass def execute(self, *args, **options): """ Try to execute this command, performing system checks if needed (as controlled by the ``requires_system_checks`` attribute, except if force-skipped). """ if options["force_color"] and options["no_color"]: raise CommandError( "The --no-color and --force-color options can't be used together." ) if options["force_color"]: self.style = color_style(force_color=True) elif options["no_color"]: self.style = no_style() self.stderr.style_func = None if options.get("stdout"): self.stdout = OutputWrapper(options["stdout"]) if options.get("stderr"): self.stderr = OutputWrapper(options["stderr"]) if self.requires_system_checks and not options["skip_checks"]: if self.requires_system_checks == ALL_CHECKS: self.check() else: self.check(tags=self.requires_system_checks) if self.requires_migrations_checks: self.check_migrations() output = self.handle(*args, **options) if output: if self.output_transaction: connection = connections[options.get("database", DEFAULT_DB_ALIAS)] output = "%s\n%s\n%s" % ( self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()), output, self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()), ) self.stdout.write(output) return output def check( self, app_configs=None, tags=None, display_num_errors=False, include_deployment_checks=False, fail_level=checks.ERROR, databases=None, ): """ Use the system check framework to validate entire Django project. Raise CommandError for any serious message (error or critical errors). If there are only light messages (like warnings), print them to stderr and don't raise an exception. """ all_issues = checks.run_checks( app_configs=app_configs, tags=tags, include_deployment_checks=include_deployment_checks, databases=databases, ) header, body, footer = "", "", "" visible_issue_count = 0 # excludes silenced warnings if all_issues: debugs = [ e for e in all_issues if e.level < checks.INFO and not e.is_silenced() ] infos = [ e for e in all_issues if checks.INFO <= e.level < checks.WARNING and not e.is_silenced() ] warnings = [ e for e in all_issues if checks.WARNING <= e.level < checks.ERROR and not e.is_silenced() ] errors = [ e for e in all_issues if checks.ERROR <= e.level < checks.CRITICAL and not e.is_silenced() ] criticals = [ e for e in all_issues if checks.CRITICAL <= e.level and not e.is_silenced() ] sorted_issues = [ (criticals, "CRITICALS"), (errors, "ERRORS"), (warnings, "WARNINGS"), (infos, "INFOS"), (debugs, "DEBUGS"), ] for issues, group_name in sorted_issues: if issues: visible_issue_count += len(issues) formatted = ( self.style.ERROR(str(e)) if e.is_serious() else self.style.WARNING(str(e)) for e in issues ) formatted = "\n".join(sorted(formatted)) body += "\n%s:\n%s\n" % (group_name, formatted) if visible_issue_count: header = "System check identified some issues:\n" if display_num_errors: if visible_issue_count: footer += "\n" footer += "System check identified %s (%s silenced)." % ( "no issues" if visible_issue_count == 0 else "1 issue" if visible_issue_count == 1 else "%s issues" % visible_issue_count, len(all_issues) - visible_issue_count, ) if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer raise SystemCheckError(msg) else: msg = header + body + footer if msg: if visible_issue_count: self.stderr.write(msg, lambda x: x) else: self.stdout.write(msg) def check_migrations(self): """ Print a warning if the set of migrations on disk don't match the migrations in the database. """ from django.db.migrations.executor import MigrationExecutor try: executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) except ImproperlyConfigured: # No databases are configured (or the dummy one) return plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) if plan: apps_waiting_migration = sorted( {migration.app_label for migration, backwards in plan} ) self.stdout.write( self.style.NOTICE( "\nYou have %(unapplied_migration_count)s unapplied migration(s). " "Your project may not work properly until you apply the " "migrations for app(s): %(apps_waiting_migration)s." % { "unapplied_migration_count": len(plan), "apps_waiting_migration": ", ".join(apps_waiting_migration), } ) ) self.stdout.write( self.style.NOTICE("Run 'python manage.py migrate' to apply them.") ) def handle(self, *args, **options): """ The actual logic of the command. Subclasses must implement this method. """ raise NotImplementedError( "subclasses of BaseCommand must provide a handle() method" ) class AppCommand(BaseCommand): """ A management command which takes one or more installed application labels as arguments, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_app_config()``, which will be called once for each application. """ missing_args_message = "Enter at least one application label." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="+", help="One or more application label.", ) def handle(self, *app_labels, **options): from django.apps import apps try: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] except (LookupError, ImportError) as e: raise CommandError( "%s. Are you sure your INSTALLED_APPS setting is correct?" % e ) output = [] for app_config in app_configs: app_output = self.handle_app_config(app_config, **options) if app_output: output.append(app_output) return "\n".join(output) def handle_app_config(self, app_config, **options): """ Perform the command's actions for app_config, an AppConfig instance corresponding to an application label given on the command line. """ raise NotImplementedError( "Subclasses of AppCommand must provide a handle_app_config() method." ) class LabelCommand(BaseCommand): """ A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_label()``, which will be called once for each label. If the arguments should be names of installed applications, use ``AppCommand`` instead. """ label = "label" missing_args_message = "Enter at least one %s." % label def add_arguments(self, parser): parser.add_argument("args", metavar=self.label, nargs="+") def handle(self, *labels, **options): output = [] for label in labels: label_output = self.handle_label(label, **options) if label_output: output.append(label_output) return "\n".join(output) def handle_label(self, label, **options): """ Perform the command's actions for ``label``, which will be the string as given on the command line. """ raise NotImplementedError( "subclasses of LabelCommand must provide a handle_label() method" )
06054333a5035e08b896b4f2cfeecd7fdb1f9c7b372c318b95613795e15685ee
import base64 import binascii import functools import hashlib import importlib import math import warnings from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.crypto import ( RANDOM_STRING_CHARS, constant_time_compare, get_random_string, pbkdf2, ) from django.utils.deprecation import RemovedInDjango51Warning from django.utils.module_loading import import_string from django.utils.translation import gettext_noop as _ UNUSABLE_PASSWORD_PREFIX = "!" # This will never be a valid encoded hash UNUSABLE_PASSWORD_SUFFIX_LENGTH = ( 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX ) def is_password_usable(encoded): """ Return True if this password wasn't generated by User.set_unusable_password(), i.e. make_password(None). """ return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX) def check_password(password, encoded, setter=None, preferred="default"): """ Return a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if password is None or not is_password_usable(encoded): return False preferred = get_hasher(preferred) try: hasher = identify_hasher(encoded) except ValueError: # encoded is gibberish or uses a hasher that's no longer installed. return False hasher_changed = hasher.algorithm != preferred.algorithm must_update = hasher_changed or preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) # If the hasher didn't change (we don't protect against enumeration if it # does) and the password should get updated, try to close the timing gap # between the work factor of the current encoded password and the default # work factor. if not is_correct and not hasher_changed and must_update: hasher.harden_runtime(password, encoded) if setter and is_correct and must_update: setter(password) return is_correct def make_password(password, salt=None, hasher="default"): """ Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Additional random string reduces chances of gaining access to staff or superuser accounts. See ticket #20079 for more info. """ if password is None: return UNUSABLE_PASSWORD_PREFIX + get_random_string( UNUSABLE_PASSWORD_SUFFIX_LENGTH ) if not isinstance(password, (bytes, str)): raise TypeError( "Password must be a string or bytes, got %s." % type(password).__qualname__ ) hasher = get_hasher(hasher) salt = salt or hasher.salt() return hasher.encode(password, salt) @functools.lru_cache def get_hashers(): hashers = [] for hasher_path in settings.PASSWORD_HASHERS: hasher_cls = import_string(hasher_path) hasher = hasher_cls() if not getattr(hasher, "algorithm"): raise ImproperlyConfigured( "hasher doesn't specify an algorithm name: %s" % hasher_path ) hashers.append(hasher) return hashers @functools.lru_cache def get_hashers_by_algorithm(): return {hasher.algorithm: hasher for hasher in get_hashers()} @receiver(setting_changed) def reset_hashers(*, setting, **kwargs): if setting == "PASSWORD_HASHERS": get_hashers.cache_clear() get_hashers_by_algorithm.cache_clear() def get_hasher(algorithm="default"): """ Return an instance of a loaded password hasher. If algorithm is 'default', return the default hasher. Lazily import hashers specified in the project's settings file if needed. """ if hasattr(algorithm, "algorithm"): return algorithm elif algorithm == "default": return get_hashers()[0] else: hashers = get_hashers_by_algorithm() try: return hashers[algorithm] except KeyError: raise ValueError( "Unknown password hashing algorithm '%s'. " "Did you specify it in the PASSWORD_HASHERS " "setting?" % algorithm ) def identify_hasher(encoded): """ Return an instance of a loaded password hasher. Identify hasher algorithm by examining encoded hash, and call get_hasher() to return hasher. Raise ValueError if algorithm cannot be identified, or if hasher is not loaded. """ # Ancient versions of Django created plain MD5 passwords and accepted # MD5 passwords with an empty salt. if (len(encoded) == 32 and "$" not in encoded) or ( len(encoded) == 37 and encoded.startswith("md5$$") ): algorithm = "unsalted_md5" # Ancient versions of Django accepted SHA1 passwords with an empty salt. elif len(encoded) == 46 and encoded.startswith("sha1$$"): algorithm = "unsalted_sha1" else: algorithm = encoded.split("$", 1)[0] return get_hasher(algorithm) def mask_hash(hash, show=6, char="*"): """ Return the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked def must_update_salt(salt, expected_entropy): # Each character in the salt provides log_2(len(alphabet)) bits of entropy. return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy class BasePasswordHasher: """ Abstract base class for password hashers When creating your own hasher, you need to override algorithm, verify(), encode() and safe_summary(). PasswordHasher objects are immutable. """ algorithm = None library = None salt_entropy = 128 def _load_library(self): if self.library is not None: if isinstance(self.library, (tuple, list)): name, mod_path = self.library else: mod_path = self.library try: module = importlib.import_module(mod_path) except ImportError as e: raise ValueError( "Couldn't load %r algorithm library: %s" % (self.__class__.__name__, e) ) return module raise ValueError( "Hasher %r doesn't specify a library attribute" % self.__class__.__name__ ) def salt(self): """ Generate a cryptographically secure nonce salt in ASCII with an entropy of at least `salt_entropy` bits. """ # Each character in the salt provides # log_2(len(alphabet)) bits of entropy. char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS))) return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS) def verify(self, password, encoded): """Check if the given password is correct.""" raise NotImplementedError( "subclasses of BasePasswordHasher must provide a verify() method" ) def _check_encode_args(self, password, salt): if password is None: raise TypeError("password must be provided.") if not salt or "$" in salt: raise ValueError("salt must be provided and cannot contain $.") def encode(self, password, salt): """ Create an encoded database value. The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide an encode() method" ) def decode(self, encoded): """ Return a decoded database value. The result is a dictionary and should contain `algorithm`, `hash`, and `salt`. Extra keys can be algorithm specific like `iterations` or `work_factor`. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide a decode() method." ) def safe_summary(self, encoded): """ Return a summary of safe values. The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide a safe_summary() method" ) def must_update(self, encoded): return False def harden_runtime(self, password, encoded): """ Bridge the runtime gap between the work factor supplied in `encoded` and the work factor suggested by this hasher. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and `self.iterations` is 30000, this method should run password through another 10000 iterations of PBKDF2. Similar approaches should exist for any hasher that has a work factor. If not, this method should be defined as a no-op to silence the warning. """ warnings.warn( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) class PBKDF2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the PBKDF2 algorithm (recommended) Configured to use PBKDF2 + HMAC + SHA256. The result is a 64 byte binary string. Iterations may be changed safely but you must rename the algorithm if you change SHA256. """ algorithm = "pbkdf2_sha256" iterations = 720000 digest = hashlib.sha256 def encode(self, password, salt, iterations=None): self._check_encode_args(password, salt) iterations = iterations or self.iterations hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = base64.b64encode(hash).decode("ascii").strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) def decode(self, encoded): algorithm, iterations, salt, hash = encoded.split("$", 3) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "iterations": int(iterations), "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"], decoded["iterations"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("iterations"): decoded["iterations"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) update_salt = must_update_salt(decoded["salt"], self.salt_entropy) return (decoded["iterations"] != self.iterations) or update_salt def harden_runtime(self, password, encoded): decoded = self.decode(encoded) extra_iterations = self.iterations - decoded["iterations"] if extra_iterations > 0: self.encode(password, decoded["salt"], extra_iterations) class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): """ Alternate PBKDF2 hasher which uses SHA1, the default PRF recommended by PKCS #5. This is compatible with other implementations of PBKDF2, such as openssl's PKCS5_PBKDF2_HMAC_SHA1(). """ algorithm = "pbkdf2_sha1" digest = hashlib.sha1 class Argon2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the argon2 algorithm. This is the winner of the Password Hashing Competition 2013-2015 (https://password-hashing.net). It requires the argon2-cffi library which depends on native C code and might cause portability issues. """ algorithm = "argon2" library = "argon2" time_cost = 2 memory_cost = 102400 parallelism = 8 def encode(self, password, salt): argon2 = self._load_library() params = self.params() data = argon2.low_level.hash_secret( password.encode(), salt.encode(), time_cost=params.time_cost, memory_cost=params.memory_cost, parallelism=params.parallelism, hash_len=params.hash_len, type=params.type, ) return self.algorithm + data.decode("ascii") def decode(self, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm params = argon2.extract_parameters("$" + rest) variety, *_, b64salt, hash = rest.split("$") # Add padding. b64salt += "=" * (-len(b64salt) % 4) salt = base64.b64decode(b64salt).decode("latin1") return { "algorithm": algorithm, "hash": hash, "memory_cost": params.memory_cost, "parallelism": params.parallelism, "salt": salt, "time_cost": params.time_cost, "variety": variety, "version": params.version, "params": params, } def verify(self, password, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm try: return argon2.PasswordHasher().verify("$" + rest, password) except argon2.exceptions.VerificationError: return False def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("variety"): decoded["variety"], _("version"): decoded["version"], _("memory cost"): decoded["memory_cost"], _("time cost"): decoded["time_cost"], _("parallelism"): decoded["parallelism"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) current_params = decoded["params"] new_params = self.params() # Set salt_len to the salt_len of the current parameters because salt # is explicitly passed to argon2. new_params.salt_len = current_params.salt_len update_salt = must_update_salt(decoded["salt"], self.salt_entropy) return (current_params != new_params) or update_salt def harden_runtime(self, password, encoded): # The runtime for Argon2 is too complicated to implement a sensible # hardening algorithm. pass def params(self): argon2 = self._load_library() # salt_len is a noop, because we provide our own salt. return argon2.Parameters( type=argon2.low_level.Type.ID, version=argon2.low_level.ARGON2_VERSION, salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH, hash_len=argon2.DEFAULT_HASH_LENGTH, time_cost=self.time_cost, memory_cost=self.memory_cost, parallelism=self.parallelism, ) class BCryptSHA256PasswordHasher(BasePasswordHasher): """ Secure password hashing using the bcrypt algorithm (recommended) This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. """ algorithm = "bcrypt_sha256" digest = hashlib.sha256 library = ("bcrypt", "bcrypt") rounds = 12 def salt(self): bcrypt = self._load_library() return bcrypt.gensalt(self.rounds) def encode(self, password, salt): bcrypt = self._load_library() password = password.encode() # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None: # Use binascii.hexlify() because a hex encoded bytestring is str. password = binascii.hexlify(self.digest(password).digest()) data = bcrypt.hashpw(password, salt) return "%s$%s" % (self.algorithm, data.decode("ascii")) def decode(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split("$", 4) assert algorithm == self.algorithm return { "algorithm": algorithm, "algostr": algostr, "checksum": data[22:], "salt": data[:22], "work_factor": int(work_factor), } def verify(self, password, encoded): algorithm, data = encoded.split("$", 1) assert algorithm == self.algorithm encoded_2 = self.encode(password, data.encode("ascii")) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("work factor"): decoded["work_factor"], _("salt"): mask_hash(decoded["salt"]), _("checksum"): mask_hash(decoded["checksum"]), } def must_update(self, encoded): decoded = self.decode(encoded) return decoded["work_factor"] != self.rounds def harden_runtime(self, password, encoded): _, data = encoded.split("$", 1) salt = data[:29] # Length of the salt in bcrypt. rounds = data.split("$")[2] # work factor is logarithmic, adding one doubles the load. diff = 2 ** (self.rounds - int(rounds)) - 1 while diff > 0: self.encode(password, salt.encode("ascii")) diff -= 1 class BCryptPasswordHasher(BCryptSHA256PasswordHasher): """ Secure password hashing using the bcrypt algorithm This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. This hasher does not first hash the password which means it is subject to bcrypt's 72 bytes password truncation. Most use cases should prefer the BCryptSHA256PasswordHasher. """ algorithm = "bcrypt" digest = None class ScryptPasswordHasher(BasePasswordHasher): """ Secure password hashing using the Scrypt algorithm. """ algorithm = "scrypt" block_size = 8 maxmem = 0 parallelism = 1 work_factor = 2**14 def encode(self, password, salt, n=None, r=None, p=None): self._check_encode_args(password, salt) n = n or self.work_factor r = r or self.block_size p = p or self.parallelism hash_ = hashlib.scrypt( password.encode(), salt=salt.encode(), n=n, r=r, p=p, maxmem=self.maxmem, dklen=64, ) hash_ = base64.b64encode(hash_).decode("ascii").strip() return "%s$%d$%s$%d$%d$%s" % (self.algorithm, n, salt, r, p, hash_) def decode(self, encoded): algorithm, work_factor, salt, block_size, parallelism, hash_ = encoded.split( "$", 6 ) assert algorithm == self.algorithm return { "algorithm": algorithm, "work_factor": int(work_factor), "salt": salt, "block_size": int(block_size), "parallelism": int(parallelism), "hash": hash_, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode( password, decoded["salt"], decoded["work_factor"], decoded["block_size"], decoded["parallelism"], ) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("work factor"): decoded["work_factor"], _("block size"): decoded["block_size"], _("parallelism"): decoded["parallelism"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return ( decoded["work_factor"] != self.work_factor or decoded["block_size"] != self.block_size or decoded["parallelism"] != self.parallelism ) def harden_runtime(self, password, encoded): # The runtime for Scrypt is too complicated to implement a sensible # hardening algorithm. pass # RemovedInDjango51Warning. class SHA1PasswordHasher(BasePasswordHasher): """ The SHA1 password hashing algorithm (not recommended) """ algorithm = "sha1" def __init__(self, *args, **kwargs): warnings.warn( "django.contrib.auth.hashers.SHA1PasswordHasher is deprecated.", RemovedInDjango51Warning, stacklevel=2, ) super().__init__(*args, **kwargs) def encode(self, password, salt): self._check_encode_args(password, salt) hash = hashlib.sha1((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("salt"): mask_hash(decoded["salt"], show=2), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return must_update_salt(decoded["salt"], self.salt_entropy) def harden_runtime(self, password, encoded): pass class MD5PasswordHasher(BasePasswordHasher): """ The Salted MD5 password hashing algorithm (not recommended) """ algorithm = "md5" def encode(self, password, salt): self._check_encode_args(password, salt) hash = hashlib.md5((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("salt"): mask_hash(decoded["salt"], show=2), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return must_update_salt(decoded["salt"], self.salt_entropy) def harden_runtime(self, password, encoded): pass # RemovedInDjango51Warning. class UnsaltedSHA1PasswordHasher(BasePasswordHasher): """ Very insecure algorithm that you should *never* use; store SHA1 hashes with an empty salt. This class is implemented because Django used to accept such password hashes. Some older Django installs still have these values lingering around so we need to handle and upgrade them properly. """ algorithm = "unsalted_sha1" def __init__(self, *args, **kwargs): warnings.warn( "django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher is deprecated.", RemovedInDjango51Warning, stacklevel=2, ) super().__init__(*args, **kwargs) def salt(self): return "" def encode(self, password, salt): if salt != "": raise ValueError("salt must be empty.") hash = hashlib.sha1(password.encode()).hexdigest() return "sha1$$%s" % hash def decode(self, encoded): assert encoded.startswith("sha1$$") return { "algorithm": self.algorithm, "hash": encoded[6:], "salt": None, } def verify(self, password, encoded): encoded_2 = self.encode(password, "") return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("hash"): mask_hash(decoded["hash"]), } def harden_runtime(self, password, encoded): pass # RemovedInDjango51Warning. class UnsaltedMD5PasswordHasher(BasePasswordHasher): """ Incredibly insecure algorithm that you should *never* use; stores unsalted MD5 hashes without the algorithm prefix, also accepts MD5 hashes with an empty salt. This class is implemented because Django used to store passwords this way and to accept such password hashes. Some older Django installs still have these values lingering around so we need to handle and upgrade them properly. """ algorithm = "unsalted_md5" def __init__(self, *args, **kwargs): warnings.warn( "django.contrib.auth.hashers.UnsaltedMD5PasswordHasher is deprecated.", RemovedInDjango51Warning, stacklevel=2, ) super().__init__(*args, **kwargs) def salt(self): return "" def encode(self, password, salt): if salt != "": raise ValueError("salt must be empty.") return hashlib.md5(password.encode()).hexdigest() def decode(self, encoded): return { "algorithm": self.algorithm, "hash": encoded, "salt": None, } def verify(self, password, encoded): if len(encoded) == 37: encoded = encoded.removeprefix("md5$$") encoded_2 = self.encode(password, "") return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("hash"): mask_hash(decoded["hash"], show=3), } def harden_runtime(self, password, encoded): pass
7fc738b227bcc60c2bd678ec8d73d4cdd105cfe68480b03fe4a3ae3d5355e553
from unittest import mock, skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, BasePasswordHasher, BCryptPasswordHasher, BCryptSHA256PasswordHasher, MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase, ignore_warnings from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango51Warning try: import bcrypt except ImportError: bcrypt = None try: import argon2 except ImportError: argon2 = None # scrypt requires OpenSSL 1.1+ try: import hashlib scrypt = hashlib.scrypt except ImportError: scrypt = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1 @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPass(SimpleTestCase): def test_simple(self): encoded = make_password("lètmein") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) # Blank passwords blank_encoded = make_password("") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) def test_bytes(self): encoded = make_password(b"bytes_password") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password(b"bytes_password", encoded), True) def test_invalid_password(self): msg = "Password must be a string or bytes, got int." with self.assertRaisesMessage(TypeError, msg): make_password(1) def test_pbkdf2(self): encoded = make_password("lètmein", "seasalt", "pbkdf2_sha256") self.assertEqual( encoded, "pbkdf2_sha256$720000$seasalt$eDupbcisD1UuIiou3hMuMu8oe/XwnpDw45r6AA5iv0E=", ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256") # Blank passwords blank_encoded = make_password("", "seasalt", "pbkdf2_sha256") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("pbkdf2_sha256") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "pbkdf2_sha256") encoded_strong_salt = make_password("lètmein", hasher.salt(), "pbkdf2_sha256") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.SHA1PasswordHasher"] ) def test_sha1(self): encoded = make_password("lètmein", "seasalt", "sha1") self.assertEqual( encoded, "sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8" ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "sha1") # Blank passwords blank_encoded = make_password("", "seasalt", "sha1") self.assertTrue(blank_encoded.startswith("sha1$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("sha1") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "sha1") encoded_strong_salt = make_password("lètmein", hasher.salt(), "sha1") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.SHA1PasswordHasher"] ) def test_sha1_deprecation_warning(self): msg = "django.contrib.auth.hashers.SHA1PasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_hasher("sha1") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"] ) def test_md5(self): encoded = make_password("lètmein", "seasalt", "md5") self.assertEqual(encoded, "md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "md5") # Blank passwords blank_encoded = make_password("", "seasalt", "md5") self.assertTrue(blank_encoded.startswith("md5$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("md5") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "md5") encoded_strong_salt = make_password("lètmein", hasher.salt(), "md5") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5(self): encoded = make_password("lètmein", "", "unsalted_md5") self.assertEqual(encoded, "88a434c88cca4e900f7874cd98123f43") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5") # Alternate unsalted syntax alt_encoded = "md5$$%s" % encoded self.assertTrue(is_password_usable(alt_encoded)) self.assertTrue(check_password("lètmein", alt_encoded)) self.assertFalse(check_password("lètmeinz", alt_encoded)) # Blank passwords blank_encoded = make_password("", "", "unsalted_md5") self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5_encode_invalid_salt(self): hasher = get_hasher("unsalted_md5") msg = "salt must be empty." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="salt") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5_deprecation_warning(self): msg = "django.contrib.auth.hashers.UnsaltedMD5PasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_hasher("unsalted_md5") @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1(self): encoded = make_password("lètmein", "", "unsalted_sha1") self.assertEqual(encoded, "sha1$$6d138ca3ae545631b3abd71a4f076ce759c5700b") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_sha1") # Raw SHA1 isn't acceptable alt_encoded = encoded[6:] self.assertFalse(check_password("lètmein", alt_encoded)) # Blank passwords blank_encoded = make_password("", "", "unsalted_sha1") self.assertTrue(blank_encoded.startswith("sha1$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1_encode_invalid_salt(self): hasher = get_hasher("unsalted_sha1") msg = "salt must be empty." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="salt") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1_deprecation_warning(self): msg = "django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_hasher("unsalted_sha1") @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_sha256(self): encoded = make_password("lètmein", hasher="bcrypt_sha256") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt_sha256$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") # password truncation no longer works password = ( "VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5" "JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN" ) encoded = make_password(password, hasher="bcrypt_sha256") self.assertTrue(check_password(password, encoded)) self.assertFalse(check_password(password[:72], encoded)) # Blank passwords blank_encoded = make_password("", hasher="bcrypt_sha256") self.assertTrue(blank_encoded.startswith("bcrypt_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt(self): encoded = make_password("lètmein", hasher="bcrypt") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt") # Blank passwords blank_encoded = make_password("", hasher="bcrypt") self.assertTrue(blank_encoded.startswith("bcrypt$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_upgrade(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) self.assertNotEqual(hasher.rounds, 4) old_rounds = hasher.rounds try: # Generate a password with 4 rounds. hasher.rounds = 4 encoded = make_password("letmein", hasher="bcrypt") rounds = hasher.safe_summary(encoded)["work factor"] self.assertEqual(rounds, 4) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... hasher.rounds = old_rounds # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertTrue(state["upgraded"]) finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_harden_runtime(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) with mock.patch.object(hasher, "rounds", 4): encoded = make_password("letmein", hasher="bcrypt") with mock.patch.object(hasher, "rounds", 6), mock.patch.object( hasher, "encode", side_effect=hasher.encode ): hasher.harden_runtime("wrong_password", encoded) # Increasing rounds from 4 to 6 means an increase of 4 in workload, # therefore hardening should run 3 times to make the timing the # same (the original encode() call already ran once). self.assertEqual(hasher.encode.call_count, 3) # Get the original salt (includes the original workload factor) algorithm, data = encoded.split("$", 1) expected_call = (("wrong_password", data[:29].encode()),) self.assertEqual(hasher.encode.call_args_list, [expected_call] * 3) def test_unusable(self): encoded = make_password(None) self.assertEqual( len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH, ) self.assertFalse(is_password_usable(encoded)) self.assertFalse(check_password(None, encoded)) self.assertFalse(check_password(encoded, encoded)) self.assertFalse(check_password(UNUSABLE_PASSWORD_PREFIX, encoded)) self.assertFalse(check_password("", encoded)) self.assertFalse(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) with self.assertRaisesMessage(ValueError, "Unknown password hashing algorith"): identify_hasher(encoded) # Assert that the unusable passwords actually contain a random part. # This might fail one day due to a hash collision. self.assertNotEqual(encoded, make_password(None), "Random password collision?") def test_unspecified_password(self): """ Makes sure specifying no plain password with a valid encoded password returns `False`. """ self.assertFalse(check_password(None, make_password("lètmein"))) def test_bad_algorithm(self): msg = ( "Unknown password hashing algorithm '%s'. Did you specify it in " "the PASSWORD_HASHERS setting?" ) with self.assertRaisesMessage(ValueError, msg % "lolcat"): make_password("lètmein", hasher="lolcat") with self.assertRaisesMessage(ValueError, msg % "lolcat"): identify_hasher("lolcat$salt$hash") def test_is_password_usable(self): passwords = ("lètmein_badencoded", "", None) for password in passwords: with self.subTest(password=password): self.assertIs(is_password_usable(password), True) def test_low_level_pbkdf2(self): hasher = PBKDF2PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha256$720000$" "seasalt2$e8hbsPnTo9qWhT3xYfKWoRth0h0J3360yb/tipPhPtY=", ) self.assertTrue(hasher.verify("lètmein", encoded)) def test_low_level_pbkdf2_sha1(self): hasher = PBKDF2SHA1PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha1$720000$seasalt2$2DDbzziqCtfldrRSNAaF8oA9OMw=" ) self.assertTrue(hasher.verify("lètmein", encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_salt_check(self): hasher = BCryptPasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @skipUnless(bcrypt, "bcrypt not installed") def test_bcryptsha256_salt_check(self): hasher = BCryptSHA256PasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_upgrade(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("pbkdf2_sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(password): state["upgraded"] = True self.assertTrue(check_password("lètmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_no_upgrade(self): encoded = make_password("lètmein") state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_no_upgrade_on_incorrect_pass(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("pbkdf2_sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) def test_pbkdf2_upgrade(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) old_iterations = hasher.iterations try: # Generate a password with 1 iteration. hasher.iterations = 1 encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and ... hasher.iterations = old_iterations # ... check if the password would get updated to the new iteration count. self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) finally: hasher.iterations = old_iterations def test_pbkdf2_harden_runtime(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) with mock.patch.object(hasher, "iterations", 1): encoded = make_password("letmein") with mock.patch.object(hasher, "iterations", 6), mock.patch.object( hasher, "encode", side_effect=hasher.encode ): hasher.harden_runtime("wrong_password", encoded) # Encode should get called once ... self.assertEqual(hasher.encode.call_count, 1) # ... with the original salt and 5 iterations. algorithm, iterations, salt, hash = encoded.split("$", 3) expected_call = (("wrong_password", salt, 5),) self.assertEqual(hasher.encode.call_args, expected_call) def test_pbkdf2_upgrade_new_hasher(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) state = {"upgraded": False} def setter(password): state["upgraded"] = True with self.settings( PASSWORD_HASHERS=["auth_tests.test_hashers.PBKDF2SingleIterationHasher"] ): encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and check if the password would get # updated to the new iteration count. with self.settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "auth_tests.test_hashers.PBKDF2SingleIterationHasher", ] ): self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_check_password_calls_harden_runtime(self): hasher = get_hasher("default") encoded = make_password("letmein") with mock.patch.object(hasher, "harden_runtime"), mock.patch.object( hasher, "must_update", return_value=True ): # Correct password supplied, no hardening needed check_password("letmein", encoded) self.assertEqual(hasher.harden_runtime.call_count, 0) # Wrong password supplied, hardening needed check_password("wrong_password", encoded) self.assertEqual(hasher.harden_runtime.call_count, 1) def test_encode_invalid_salt(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] msg = "salt must be provided and cannot contain $." for hasher_class in hasher_classes: hasher = hasher_class() for salt in [None, "", "sea$salt"]: with self.subTest(hasher_class.__name__, salt=salt): with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt) def test_encode_password_required(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] msg = "password must be provided." for hasher_class in hasher_classes: hasher = hasher_class() with self.subTest(hasher_class.__name__): with self.assertRaisesMessage(TypeError, msg): hasher.encode(None, "seasalt") class BasePasswordHasherTests(SimpleTestCase): not_implemented_msg = "subclasses of BasePasswordHasher must provide %s() method" def setUp(self): self.hasher = BasePasswordHasher() def test_load_library_no_algorithm(self): msg = "Hasher 'BasePasswordHasher' doesn't specify a library attribute" with self.assertRaisesMessage(ValueError, msg): self.hasher._load_library() def test_load_library_importerror(self): PlainHasher = type( "PlainHasher", (BasePasswordHasher,), {"algorithm": "plain", "library": "plain"}, ) msg = "Couldn't load 'PlainHasher' algorithm library: No module named 'plain'" with self.assertRaisesMessage(ValueError, msg): PlainHasher()._load_library() def test_attributes(self): self.assertIsNone(self.hasher.algorithm) self.assertIsNone(self.hasher.library) def test_encode(self): msg = self.not_implemented_msg % "an encode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.encode("password", "salt") def test_decode(self): msg = self.not_implemented_msg % "a decode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.decode("encoded") def test_harden_runtime(self): msg = ( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) with self.assertWarnsMessage(Warning, msg): self.hasher.harden_runtime("password", "encoded") def test_must_update(self): self.assertIs(self.hasher.must_update("encoded"), False) def test_safe_summary(self): msg = self.not_implemented_msg % "a safe_summary" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.safe_summary("encoded") def test_verify(self): msg = self.not_implemented_msg % "a verify" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.verify("password", "encoded") @skipUnless(argon2, "argon2-cffi not installed") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassArgon2(SimpleTestCase): def test_argon2(self): encoded = make_password("lètmein", hasher="argon2") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("argon2$argon2id$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "argon2") # Blank passwords blank_encoded = make_password("", hasher="argon2") self.assertTrue(blank_encoded.startswith("argon2$argon2id$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Old hashes without version attribute encoded = ( "argon2$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO" "4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg" ) self.assertTrue(check_password("secret", encoded)) self.assertFalse(check_password("wrong", encoded)) # Old hashes with version attribute. encoded = "argon2$argon2i$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$YC9+jJCrQhs5R6db7LlN8Q" self.assertIs(check_password("secret", encoded), True) self.assertIs(check_password("wrong", encoded), False) # Salt entropy check. hasher = get_hasher("argon2") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "argon2") encoded_strong_salt = make_password("lètmein", hasher.salt(), "argon2") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) def test_argon2_decode(self): salt = "abcdefghijk" encoded = make_password("lètmein", salt=salt, hasher="argon2") hasher = get_hasher("argon2") decoded = hasher.decode(encoded) self.assertEqual(decoded["memory_cost"], hasher.memory_cost) self.assertEqual(decoded["parallelism"], hasher.parallelism) self.assertEqual(decoded["salt"], salt) self.assertEqual(decoded["time_cost"], hasher.time_cost) def test_argon2_upgrade(self): self._test_argon2_upgrade("time_cost", "time cost", 1) self._test_argon2_upgrade("memory_cost", "memory cost", 64) self._test_argon2_upgrade("parallelism", "parallelism", 1) def test_argon2_version_upgrade(self): hasher = get_hasher("argon2") state = {"upgraded": False} encoded = ( "argon2$argon2id$v=19$m=102400,t=2,p=8$Y041dExhNkljRUUy$TMa6A8fPJh" "CAUXRhJXCXdw" ) def setter(password): state["upgraded"] = True old_m = hasher.memory_cost old_t = hasher.time_cost old_p = hasher.parallelism try: hasher.memory_cost = 8 hasher.time_cost = 1 hasher.parallelism = 1 self.assertTrue(check_password("secret", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: hasher.memory_cost = old_m hasher.time_cost = old_t hasher.parallelism = old_p def _test_argon2_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("argon2") self.assertEqual("argon2", hasher.algorithm) self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to 1 setattr(hasher, attr, new_value) encoded = make_password("letmein", hasher="argon2") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... setattr(hasher, attr, old_value) # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: setattr(hasher, attr, old_value) @skipUnless(scrypt, "scrypt not available") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassScrypt(SimpleTestCase): def test_scrypt(self): encoded = make_password("lètmein", "seasalt", "scrypt") self.assertEqual( encoded, "scrypt$16384$seasalt$8$1$Qj3+9PPyRjSJIebHnG81TMjsqtaIGxNQG/aEB/NY" "afTJ7tibgfYz71m0ldQESkXFRkdVCBhhY8mx7rQwite/Pw==", ) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password("lètmein", encoded), True) self.assertIs(check_password("lètmeinz", encoded), False) self.assertEqual(identify_hasher(encoded).algorithm, "scrypt") # Blank passwords. blank_encoded = make_password("", "seasalt", "scrypt") self.assertIs(blank_encoded.startswith("scrypt$"), True) self.assertIs(is_password_usable(blank_encoded), True) self.assertIs(check_password("", blank_encoded), True) self.assertIs(check_password(" ", blank_encoded), False) def test_scrypt_decode(self): encoded = make_password("lètmein", "seasalt", "scrypt") hasher = get_hasher("scrypt") decoded = hasher.decode(encoded) tests = [ ("block_size", hasher.block_size), ("parallelism", hasher.parallelism), ("salt", "seasalt"), ("work_factor", hasher.work_factor), ] for key, excepted in tests: with self.subTest(key=key): self.assertEqual(decoded[key], excepted) def _test_scrypt_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("scrypt") self.assertEqual(hasher.algorithm, "scrypt") self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to the new value. setattr(hasher, attr, new_value) encoded = make_password("lètmein", "seasalt", "scrypt") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No update is triggered. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], False) # Revert to the old value. setattr(hasher, attr, old_value) # Password is updated. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], True) finally: setattr(hasher, attr, old_value) def test_scrypt_upgrade(self): tests = [ ("work_factor", "work factor", 2**11), ("block_size", "block size", 10), ("parallelism", "parallelism", 2), ] for attr, summary_key, new_value in tests: with self.subTest(attr=attr): self._test_scrypt_upgrade(attr, summary_key, new_value)
eb3dd90a53d66c2dfe2ada4a1f3eabc25db743977019bd61878bae6a34610348
import os from argparse import ArgumentDefaultsHelpFormatter from io import StringIO from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django.apps import apps from django.core import management from django.core.checks import Tags from django.core.management import BaseCommand, CommandError, find_commands from django.core.management.utils import ( find_command, get_random_secret_key, is_ignored_path, normalize_path_patterns, popen_wrapper, ) from django.db import connection from django.test import SimpleTestCase, override_settings from django.test.utils import captured_stderr, extend_sys_path from django.utils import translation from .management.commands import dance # A minimal set of apps to avoid system checks running on all apps. @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "user_commands", ], ) class CommandTests(SimpleTestCase): def test_command(self): out = StringIO() management.call_command("dance", stdout=out) self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue()) def test_command_style(self): out = StringIO() management.call_command("dance", style="Jive", stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) # Passing options as arguments also works (thanks argparse) management.call_command("dance", "--style", "Jive", stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) def test_language_preserved(self): with translation.override("fr"): management.call_command("dance", verbosity=0) self.assertEqual(translation.get_language(), "fr") def test_explode(self): """An unknown command raises CommandError""" with self.assertRaisesMessage(CommandError, "Unknown command: 'explode'"): management.call_command(("explode",)) def test_system_exit(self): """Exception raised in a command should raise CommandError with call_command, but SystemExit when run from command line """ with self.assertRaises(CommandError) as cm: management.call_command("dance", example="raise") self.assertEqual(cm.exception.returncode, 3) dance.Command.requires_system_checks = [] try: with captured_stderr() as stderr, self.assertRaises(SystemExit) as cm: management.ManagementUtility( ["manage.py", "dance", "--example=raise"] ).execute() self.assertEqual(cm.exception.code, 3) finally: dance.Command.requires_system_checks = "__all__" self.assertIn("CommandError", stderr.getvalue()) def test_no_translations_deactivate_translations(self): """ When the Command handle method is decorated with @no_translations, translations are deactivated inside the command. """ current_locale = translation.get_language() with translation.override("pl"): result = management.call_command("no_translations") self.assertIsNone(result) self.assertEqual(translation.get_language(), current_locale) def test_find_command_without_PATH(self): """ find_command should still work when the PATH environment variable doesn't exist (#22256). """ current_path = os.environ.pop("PATH", None) try: self.assertIsNone(find_command("_missing_")) finally: if current_path is not None: os.environ["PATH"] = current_path def test_discover_commands_in_eggs(self): """ Management commands can also be loaded from Python eggs. """ egg_dir = "%s/eggs" % os.path.dirname(__file__) egg_name = "%s/basic.egg" % egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=["commandegg"]): cmds = find_commands( os.path.join(apps.get_app_config("commandegg").path, "management") ) self.assertEqual(cmds, ["eggcommand"]) def test_call_command_option_parsing(self): """ When passing the long option name to call_command, the available option key is the option dest name (#22985). """ out = StringIO() management.call_command("dance", stdout=out, opt_3=True) self.assertIn("option3", out.getvalue()) self.assertNotIn("opt_3", out.getvalue()) self.assertNotIn("opt-3", out.getvalue()) def test_call_command_option_parsing_non_string_arg(self): """ It should be possible to pass non-string arguments to call_command. """ out = StringIO() management.call_command("dance", 1, verbosity=0, stdout=out) self.assertIn("You passed 1 as a positional argument.", out.getvalue()) def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self): out = StringIO() management.call_command("hal", "--empty", stdout=out) self.assertEqual(out.getvalue(), "\nDave, I can't do that.\n") def test_calling_command_with_app_labels_and_parameters_should_be_ok(self): out = StringIO() management.call_command("hal", "myapp", "--verbosity", "3", stdout=out) self.assertIn( "Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue() ) def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok( self, ): out = StringIO() management.call_command("hal", "--verbosity", "3", "myapp", stdout=out) self.assertIn( "Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue() ) def test_calling_a_command_with_no_app_labels_and_parameters_raise_command_error( self, ): with self.assertRaises(CommandError): management.call_command("hal") def test_output_transaction(self): output = management.call_command( "transaction", stdout=StringIO(), no_color=True ) self.assertTrue( output.strip().startswith(connection.ops.start_transaction_sql()) ) self.assertTrue(output.strip().endswith(connection.ops.end_transaction_sql())) def test_call_command_no_checks(self): """ By default, call_command should not trigger the check framework, unless specifically asked. """ self.counter = 0 def patched_check(self_, **kwargs): self.counter += 1 self.kwargs = kwargs saved_check = BaseCommand.check BaseCommand.check = patched_check try: management.call_command("dance", verbosity=0) self.assertEqual(self.counter, 0) management.call_command("dance", verbosity=0, skip_checks=False) self.assertEqual(self.counter, 1) self.assertEqual(self.kwargs, {}) finally: BaseCommand.check = saved_check def test_requires_system_checks_empty(self): with mock.patch( "django.core.management.base.BaseCommand.check" ) as mocked_check: management.call_command("no_system_checks") self.assertIs(mocked_check.called, False) def test_requires_system_checks_specific(self): with mock.patch( "django.core.management.base.BaseCommand.check" ) as mocked_check: management.call_command("specific_system_checks", skip_checks=False) mocked_check.assert_called_once_with(tags=[Tags.staticfiles, Tags.models]) def test_requires_system_checks_invalid(self): class Command(BaseCommand): requires_system_checks = "x" msg = "requires_system_checks must be a list or tuple." with self.assertRaisesMessage(TypeError, msg): Command() def test_check_migrations(self): requires_migrations_checks = dance.Command.requires_migrations_checks self.assertIs(requires_migrations_checks, False) try: with mock.patch.object(BaseCommand, "check_migrations") as check_migrations: management.call_command("dance", verbosity=0) self.assertFalse(check_migrations.called) dance.Command.requires_migrations_checks = True management.call_command("dance", verbosity=0) self.assertTrue(check_migrations.called) finally: dance.Command.requires_migrations_checks = requires_migrations_checks def test_call_command_unrecognized_option(self): msg = ( "Unknown option(s) for dance command: unrecognized. Valid options " "are: example, force_color, help, integer, no_color, opt_3, " "option3, pythonpath, settings, skip_checks, stderr, stdout, " "style, traceback, verbosity, version." ) with self.assertRaisesMessage(TypeError, msg): management.call_command("dance", unrecognized=1) msg = ( "Unknown option(s) for dance command: unrecognized, unrecognized2. " "Valid options are: example, force_color, help, integer, no_color, " "opt_3, option3, pythonpath, settings, skip_checks, stderr, " "stdout, style, traceback, verbosity, version." ) with self.assertRaisesMessage(TypeError, msg): management.call_command("dance", unrecognized=1, unrecognized2=1) def test_call_command_with_required_parameters_in_options(self): out = StringIO() management.call_command( "required_option", need_me="foo", needme2="bar", stdout=out ) self.assertIn("need_me", out.getvalue()) self.assertIn("needme2", out.getvalue()) def test_call_command_with_required_parameters_in_mixed_options(self): out = StringIO() management.call_command( "required_option", "--need-me=foo", needme2="bar", stdout=out ) self.assertIn("need_me", out.getvalue()) self.assertIn("needme2", out.getvalue()) def test_command_add_arguments_after_common_arguments(self): out = StringIO() management.call_command("common_args", stdout=out) self.assertIn("Detected that --version already exists", out.getvalue()) def test_mutually_exclusive_group_required_options(self): out = StringIO() management.call_command("mutually_exclusive_required", foo_id=1, stdout=out) self.assertIn("foo_id", out.getvalue()) management.call_command( "mutually_exclusive_required", foo_name="foo", stdout=out ) self.assertIn("foo_name", out.getvalue()) msg = ( "Error: one of the arguments --foo-id --foo-name --foo-list " "--append_const --const --count --flag_false --flag_true is " "required" ) with self.assertRaisesMessage(CommandError, msg): management.call_command("mutually_exclusive_required", stdout=out) def test_mutually_exclusive_group_required_const_options(self): tests = [ ("append_const", [42]), ("const", 31), ("count", 1), ("flag_false", False), ("flag_true", True), ] for arg, value in tests: out = StringIO() expected_output = "%s=%s" % (arg, value) with self.subTest(arg=arg): management.call_command( "mutually_exclusive_required", "--%s" % arg, stdout=out, ) self.assertIn(expected_output, out.getvalue()) out.truncate(0) management.call_command( "mutually_exclusive_required", **{arg: value, "stdout": out}, ) self.assertIn(expected_output, out.getvalue()) def test_mutually_exclusive_group_required_with_same_dest_options(self): tests = [ {"until": "2"}, {"for": "1", "until": "2"}, ] msg = ( "Cannot pass the dest 'until' that matches multiple arguments via " "**options." ) for options in tests: with self.subTest(options=options): with self.assertRaisesMessage(TypeError, msg): management.call_command( "mutually_exclusive_required_with_same_dest", **options, ) def test_mutually_exclusive_group_required_with_same_dest_args(self): tests = [ ("--until=1",), ("--until", 1), ("--for=1",), ("--for", 1), ] for args in tests: out = StringIO() with self.subTest(options=args): management.call_command( "mutually_exclusive_required_with_same_dest", *args, stdout=out, ) output = out.getvalue() self.assertIn("until=1", output) def test_required_list_option(self): tests = [ (("--foo-list", [1, 2]), {}), ((), {"foo_list": [1, 2]}), ] for command in ["mutually_exclusive_required", "required_list_option"]: for args, kwargs in tests: with self.subTest(command=command, args=args, kwargs=kwargs): out = StringIO() management.call_command( command, *args, **{**kwargs, "stdout": out}, ) self.assertIn("foo_list=[1, 2]", out.getvalue()) def test_required_const_options(self): args = { "append_const": [42], "const": 31, "count": 1, "flag_false": False, "flag_true": True, } expected_output = "\n".join( "%s=%s" % (arg, value) for arg, value in args.items() ) out = StringIO() management.call_command( "required_constant_option", "--append_const", "--const", "--count", "--flag_false", "--flag_true", stdout=out, ) self.assertIn(expected_output, out.getvalue()) out.truncate(0) management.call_command("required_constant_option", **{**args, "stdout": out}) self.assertIn(expected_output, out.getvalue()) def test_subparser(self): out = StringIO() management.call_command("subparser", "foo", 12, stdout=out) self.assertIn("bar", out.getvalue()) def test_subparser_dest_args(self): out = StringIO() management.call_command("subparser_dest", "foo", bar=12, stdout=out) self.assertIn("bar", out.getvalue()) def test_subparser_dest_required_args(self): out = StringIO() management.call_command( "subparser_required", "foo_1", "foo_2", bar=12, stdout=out ) self.assertIn("bar", out.getvalue()) def test_subparser_invalid_option(self): msg = "invalid choice: 'test' (choose from 'foo')" with self.assertRaisesMessage(CommandError, msg): management.call_command("subparser", "test", 12) msg = "Error: the following arguments are required: subcommand" with self.assertRaisesMessage(CommandError, msg): management.call_command("subparser_dest", subcommand="foo", bar=12) def test_create_parser_kwargs(self): """BaseCommand.create_parser() passes kwargs to CommandParser.""" epilog = "some epilog text" parser = BaseCommand().create_parser( "prog_name", "subcommand", epilog=epilog, formatter_class=ArgumentDefaultsHelpFormatter, ) self.assertEqual(parser.epilog, epilog) self.assertEqual(parser.formatter_class, ArgumentDefaultsHelpFormatter) def test_outputwrapper_flush(self): out = StringIO() with mock.patch.object(out, "flush") as mocked_flush: management.call_command("outputwrapper", stdout=out) self.assertIn("Working...", out.getvalue()) self.assertIs(mocked_flush.called, True) class CommandRunTests(AdminScriptTestCase): """ Tests that need to run by simulating the command line, not by call_command. """ def test_script_prefix_set_in_commands(self): self.write_settings( "settings.py", apps=["user_commands"], sdict={ "ROOT_URLCONF": '"user_commands.urls"', "FORCE_SCRIPT_NAME": '"/PREFIX/"', }, ) out, err = self.run_manage(["reverse_url"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "/PREFIX/some/url/") def test_disallowed_abbreviated_options(self): """ To avoid conflicts with custom options, commands don't allow abbreviated forms of the --setting and --pythonpath options. """ self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["set_option", "--set", "foo"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "Set foo") def test_skip_checks(self): self.write_settings( "settings.py", apps=["django.contrib.staticfiles", "user_commands"], sdict={ # (staticfiles.E001) The STATICFILES_DIRS setting is not a tuple or # list. "STATICFILES_DIRS": '"foo"', }, ) out, err = self.run_manage(["set_option", "--skip-checks", "--set", "foo"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "Set foo") def test_subparser_error_formatting(self): self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["subparser", "foo", "twelve"]) self.maxDiff = None self.assertNoOutput(out) err_lines = err.splitlines() self.assertEqual(len(err_lines), 2) self.assertEqual( err_lines[1], "manage.py subparser foo: error: argument bar: invalid int value: 'twelve'", ) def test_subparser_non_django_error_formatting(self): self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["subparser_vanilla", "foo", "seven"]) self.assertNoOutput(out) err_lines = err.splitlines() self.assertEqual(len(err_lines), 2) self.assertEqual( err_lines[1], "manage.py subparser_vanilla foo: error: argument bar: invalid int value: " "'seven'", ) class UtilsTests(SimpleTestCase): def test_no_existent_external_program(self): msg = "Error executing a_42_command_that_doesnt_exist_42" with self.assertRaisesMessage(CommandError, msg): popen_wrapper(["a_42_command_that_doesnt_exist_42"]) def test_get_random_secret_key(self): key = get_random_secret_key() self.assertEqual(len(key), 50) for char in key: self.assertIn(char, "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") def test_is_ignored_path_true(self): patterns = ( ["foo/bar/baz"], ["baz"], ["foo/bar/baz"], ["*/baz"], ["*"], ["b?z"], ["[abc]az"], ["*/ba[!z]/baz"], ) for ignore_patterns in patterns: with self.subTest(ignore_patterns=ignore_patterns): self.assertIs( is_ignored_path("foo/bar/baz", ignore_patterns=ignore_patterns), True, ) def test_is_ignored_path_false(self): self.assertIs( is_ignored_path( "foo/bar/baz", ignore_patterns=["foo/bar/bat", "bar", "flub/blub"] ), False, ) def test_normalize_path_patterns_truncates_wildcard_base(self): expected = [os.path.normcase(p) for p in ["foo/bar", "bar/*/"]] self.assertEqual(normalize_path_patterns(["foo/bar/*", "bar/*/"]), expected)
3ebe3e5f685d05fdb2cf8c71d4a2e4a4882d7d7f0adac7ead2e5546fd6a9b658
import argparse from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): subparsers = parser.add_subparsers(parser_class=argparse.ArgumentParser) parser_foo = subparsers.add_parser("foo") parser_foo.add_argument("bar", type=int) def handle(self, *args, **options): pass
44b81afd3eb36be3f3ec521d5abd46ed9586d72e5f0f7768bc0d85826268917e
import json import mimetypes import os import sys from copy import copy from functools import partial from http import HTTPStatus from importlib import import_module from io import BytesIO, IOBase from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit from asgiref.sync import sync_to_async from django.conf import settings from django.core.handlers.asgi import ASGIRequest from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.core.serializers.json import DjangoJSONEncoder from django.core.signals import got_request_exception, request_finished, request_started from django.db import close_old_connections from django.http import HttpHeaders, HttpRequest, QueryDict, SimpleCookie from django.test import signals from django.test.utils import ContextList from django.urls import resolve from django.utils.encoding import force_bytes from django.utils.functional import SimpleLazyObject from django.utils.http import urlencode from django.utils.itercompat import is_iterable from django.utils.regex_helper import _lazy_re_compile __all__ = ( "AsyncClient", "AsyncRequestFactory", "Client", "RedirectCycleError", "RequestFactory", "encode_file", "encode_multipart", ) BOUNDARY = "BoUnDaRyStRiNg" MULTIPART_CONTENT = "multipart/form-data; boundary=%s" % BOUNDARY CONTENT_TYPE_RE = _lazy_re_compile(r".*; charset=([\w-]+);?") # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8 JSON_CONTENT_TYPE_RE = _lazy_re_compile(r"^application\/(.+\+)?json") class RedirectCycleError(Exception): """The test client has been asked to follow a redirect loop.""" def __init__(self, message, last_response): super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain class FakePayload(IOBase): """ A wrapper around BytesIO that restricts what can be read since data from the network can't be sought and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life. """ def __init__(self, initial_bytes=None): self.__content = BytesIO() self.__len = 0 self.read_started = False if initial_bytes is not None: self.write(initial_bytes) def __len__(self): return self.__len def read(self, size=-1, /): if not self.read_started: self.__content.seek(0) self.read_started = True if size == -1 or size is None: size = self.__len assert ( self.__len >= size ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(size) self.__len -= len(content) return content def readline(self, size=-1, /): if not self.read_started: self.__content.seek(0) self.read_started = True if size == -1 or size is None: size = self.__len assert ( self.__len >= size ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.readline(size) self.__len -= len(content) return content def write(self, b, /): if self.read_started: raise ValueError("Unable to write a payload after it's been read") content = force_bytes(b) self.__content.write(content) self.__len += len(content) def closing_iterator_wrapper(iterable, close): try: yield from iterable finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) async def aclosing_iterator_wrapper(iterable, close): try: async for chunk in iterable: yield chunk finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) def conditional_content_removal(request, response): """ Simulate the behavior of most web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensure compliance with RFC 9112 Section 6.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): if response.streaming: response.streaming_content = [] else: response.content = b"" if request.method == "HEAD": if response.streaming: response.streaming_content = [] else: response.content = b"" return response class ClientHandler(BaseHandler): """ An HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # Emulate a WSGI server by calling the close method on completion. if response.streaming: if response.is_async: response.streaming_content = aclosing_iterator_wrapper( response.streaming_content, response.close ) else: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response class AsyncClientHandler(BaseHandler): """An async version of ClientHandler.""" def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) async def __call__(self, scope): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware(is_async=True) # Extract body file from the scope, if provided. if "_body_file" in scope: body_file = scope.pop("_body_file") else: body_file = FakePayload("") request_started.disconnect(close_old_connections) await sync_to_async(request_started.send, thread_sensitive=False)( sender=self.__class__, scope=scope ) request_started.connect(close_old_connections) # Wrap FakePayload body_file to allow large read() in test environment. request = ASGIRequest(scope, LimitedStream(body_file, len(body_file))) # Sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably required # for backwards compatibility with external tests against admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = await self.get_response_async(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating ASGI request to the response so that it could # be later retrieved. response.asgi_request = request # Emulate a server by calling the close method on completion. if response.streaming: if response.is_async: response.streaming_content = aclosing_iterator_wrapper( response.streaming_content, response.close ) else: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) # Will fire request_finished. await sync_to_async(response.close, thread_sensitive=False)() request_finished.connect(close_old_connections) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """ store.setdefault("templates", []).append(template) if "context" not in store: store["context"] = ContextList() store["context"].append(copy(context)) def encode_multipart(boundary, data): """ Encode multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. def is_file(thing): return hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for key, value in data.items(): if value is None: raise TypeError( "Cannot encode None for key '%s' as POST data. Did you mean " "to pass an empty string or omit the value?" % key ) elif is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, str) and is_iterable(value): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", item, ] ) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", value, ] ) lines.extend( [ to_bytes("--%s--" % boundary), b"", ] ) return b"\r\n".join(lines) def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # file.name might not be a string. For example, it's an int for # tempfile.TemporaryFile(). file_has_string_name = hasattr(file, "name") and isinstance(file.name, str) filename = os.path.basename(file.name) if file_has_string_name else "" if hasattr(file, "content_type"): content_type = file.content_type elif filename: content_type = mimetypes.guess_type(filename)[0] else: content_type = None if content_type is None: content_type = "application/octet-stream" filename = filename or key return [ to_bytes("--%s" % boundary), to_bytes( 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ), to_bytes("Content-Type: %s" % content_type), b"", to_bytes(file.read()), ] class RequestFactory: """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, *, json_encoder=DjangoJSONEncoder, headers=None, **defaults): self.json_encoder = json_encoder self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() if headers: self.defaults.update(HttpHeaders.to_wsgi_names(headers)) def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See https://www.python.org/dev/peps/pep-3333/#environ-variables return { "HTTP_COOKIE": "; ".join( sorted( "%s=%s" % (morsel.key, morsel.coded_value) for morsel in self.cookies.values() ) ), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, **self.defaults, **request, } def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match[1] else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _encode_json(self, data, content_type): """ Return encoded JSON if data is a dict, list, or tuple and content_type is application/json. """ should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance( data, (dict, list, tuple) ) return json.dumps(data, cls=self.json_encoder) if should_encode else data def _get_path(self, parsed): path = parsed.path # If there are parameters, add them if parsed.params: path += ";" + parsed.params path = unquote_to_bytes(path) # Replace the behavior where non-ASCII values in the WSGI environ are # arbitrarily decoded with ISO-8859-1. # Refs comment in `get_bytes_from_wsgi()`. return path.decode("iso-8859-1") def get(self, path, data=None, secure=False, *, headers=None, **extra): """Construct a GET request.""" data = {} if data is None else data return self.generic( "GET", path, secure=secure, headers=headers, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def post( self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, *, headers=None, **extra, ): """Construct a POST request.""" data = self._encode_json({} if data is None else data, content_type) post_data = self._encode_data(data, content_type) return self.generic( "POST", path, post_data, content_type, secure=secure, headers=headers, **extra, ) def head(self, path, data=None, secure=False, *, headers=None, **extra): """Construct a HEAD request.""" data = {} if data is None else data return self.generic( "HEAD", path, secure=secure, headers=headers, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def trace(self, path, secure=False, *, headers=None, **extra): """Construct a TRACE request.""" return self.generic("TRACE", path, secure=secure, headers=headers, **extra) def options( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): "Construct an OPTIONS request." return self.generic( "OPTIONS", path, data, content_type, secure=secure, headers=headers, **extra ) def put( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct a PUT request.""" data = self._encode_json(data, content_type) return self.generic( "PUT", path, data, content_type, secure=secure, headers=headers, **extra ) def patch( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct a PATCH request.""" data = self._encode_json(data, content_type) return self.generic( "PATCH", path, data, content_type, secure=secure, headers=headers, **extra ) def delete( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct a DELETE request.""" data = self._encode_json(data, content_type) return self.generic( "DELETE", path, data, content_type, secure=secure, headers=headers, **extra ) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { "PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": method, "SERVER_PORT": "443" if secure else "80", "wsgi.url_scheme": "https" if secure else "http", } if data: r.update( { "CONTENT_LENGTH": str(len(data)), "CONTENT_TYPE": content_type, "wsgi.input": FakePayload(data), } ) if headers: extra.update(HttpHeaders.to_wsgi_names(headers)) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get("QUERY_STRING"): # WSGI requires latin-1 encoded strings. See get_path_info(). query_string = parsed[4].encode().decode("iso-8859-1") r["QUERY_STRING"] = query_string return self.request(**r) class AsyncRequestFactory(RequestFactory): """ Class that lets you create mock ASGI-like Request objects for use in testing. Usage: rf = AsyncRequestFactory() get_request = await rf.get('/hello/') post_request = await rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, including synchronous ones. The reason we have a separate class here is: a) this makes ASGIRequest subclasses, and b) AsyncTestClient can subclass it. """ def _base_scope(self, **request): """The base scope for a request.""" # This is a minimal valid ASGI scope, plus: # - headers['cookie'] for cookie support, # - 'client' often useful, see #8551. scope = { "asgi": {"version": "3.0"}, "type": "http", "http_version": "1.1", "client": ["127.0.0.1", 0], "server": ("testserver", "80"), "scheme": "http", "method": "GET", "headers": [], **self.defaults, **request, } scope["headers"].append( ( b"cookie", b"; ".join( sorted( ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii") for morsel in self.cookies.values() ) ), ) ) return scope def request(self, **request): """Construct a generic request object.""" # This is synchronous, which means all methods on this class are. # AsyncClient, however, has an async request function, which makes all # its methods async. if "_body_file" in request: body_file = request.pop("_body_file") else: body_file = FakePayload("") # Wrap FakePayload body_file to allow large read() in test environment. return ASGIRequest( self._base_scope(**request), LimitedStream(body_file, len(body_file)) ) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy. data = force_bytes(data, settings.DEFAULT_CHARSET) s = { "method": method, "path": self._get_path(parsed), "server": ("127.0.0.1", "443" if secure else "80"), "scheme": "https" if secure else "http", "headers": [(b"host", b"testserver")], } if data: s["headers"].extend( [ (b"content-length", str(len(data)).encode("ascii")), (b"content-type", content_type.encode("ascii")), ] ) s["_body_file"] = FakePayload(data) follow = extra.pop("follow", None) if follow is not None: s["follow"] = follow if query_string := extra.pop("QUERY_STRING", None): s["query_string"] = query_string if headers: extra.update(HttpHeaders.to_asgi_names(headers)) s["headers"] += [ (key.lower().encode("ascii"), value.encode("latin1")) for key, value in extra.items() ] # If QUERY_STRING is absent or empty, we want to extract it from the # URL. if not s.get("query_string"): s["query_string"] = parsed[4] return self.request(**s) class ClientMixin: """ Mixin with common methods between Client and AsyncClient. """ def store_exc_info(self, **kwargs): """Store exceptions when they are generated by a view.""" self.exc_info = sys.exc_info() def check_exception(self, response): """ Look for a signaled exception, clear the current context exception data, re-raise the signaled exception, and clear the signaled exception from the local cache. """ response.exc_info = self.exc_info if self.exc_info: _, exc_value, _ = self.exc_info self.exc_info = None if self.raise_request_exception: raise exc_value @property def session(self): """Return the current session variables.""" engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session def login(self, **credentials): """ Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible or False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True return False def force_login(self, user, backend=None): def get_backend(): from django.contrib.auth import load_backend for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) if hasattr(backend, "get_user"): return backend_path if backend is None: backend = get_backend() user.backend = backend self._login(user, backend) def _login(self, user, backend=None): from django.contrib.auth import login # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() login(request, user, backend) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } self.cookies[session_cookie].update(cookie_data) def logout(self): """Log out the user by removing the cookies and session object.""" from django.contrib.auth import get_user, logout request = HttpRequest() if self.session: request.session = self.session request.user = get_user(request) else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie() def _parse_json(self, response, **extra): if not hasattr(response, "_json"): if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")): raise ValueError( 'Content-Type header is "%s", not "application/json"' % response.get("Content-Type") ) response._json = json.loads( response.content.decode(response.charset), **extra ) return response._json class Client(ClientMixin, RequestFactory): """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, **defaults, ): super().__init__(headers=headers, **defaults) self.handler = ClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None self.headers = None def request(self, **request): """ Make a generic request. Compose the environment dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ environ = self._base_environ(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = self.handler(environ) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.wsgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["PATH_INFO"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get( self, path, data=None, follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using GET.""" self.extra = extra self.headers = headers response = super().get(path, data=data, secure=secure, headers=headers, **extra) if follow: response = self._handle_redirects( response, data=data, headers=headers, **extra ) return response def post( self, path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using POST.""" self.extra = extra self.headers = headers response = super().post( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def head( self, path, data=None, follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using HEAD.""" self.extra = extra self.headers = headers response = super().head( path, data=data, secure=secure, headers=headers, **extra ) if follow: response = self._handle_redirects( response, data=data, headers=headers, **extra ) return response def options( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Request a response from the server using OPTIONS.""" self.extra = extra self.headers = headers response = super().options( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def put( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Send a resource to the server using PUT.""" self.extra = extra self.headers = headers response = super().put( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def patch( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Send a resource to the server using PATCH.""" self.extra = extra self.headers = headers response = super().patch( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def delete( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, *, headers=None, **extra, ): """Send a DELETE request to the server.""" self.extra = extra self.headers = headers response = super().delete( path, data=data, content_type=content_type, secure=secure, headers=headers, **extra, ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, headers=headers, **extra ) return response def trace( self, path, data="", follow=False, secure=False, *, headers=None, **extra, ): """Send a TRACE request to the server.""" self.extra = extra self.headers = headers response = super().trace( path, data=data, secure=secure, headers=headers, **extra ) if follow: response = self._handle_redirects( response, data=data, headers=headers, **extra ) return response def _handle_redirects( self, response, data="", content_type="", headers=None, **extra, ): """ Follow any redirects by requesting responses from the server using GET. """ response.redirect_chain = [] redirect_status_codes = ( HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.FOUND, HTTPStatus.SEE_OTHER, HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ) while response.status_code in redirect_status_codes: response_url = response.url redirect_chain = response.redirect_chain redirect_chain.append((response_url, response.status_code)) url = urlsplit(response_url) if url.scheme: extra["wsgi.url_scheme"] = url.scheme if url.hostname: extra["SERVER_NAME"] = url.hostname if url.port: extra["SERVER_PORT"] = str(url.port) path = url.path # RFC 3986 Section 6.2.3: Empty path should be normalized to "/". if not path and url.netloc: path = "/" # Prepend the request path to handle relative path redirects if not path.startswith("/"): path = urljoin(response.request["PATH_INFO"], path) if response.status_code in ( HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ): # Preserve request method and query string (if needed) # post-redirect for 307/308 responses. request_method = response.request["REQUEST_METHOD"].lower() if request_method not in ("get", "head"): extra["QUERY_STRING"] = url.query request_method = getattr(self, request_method) else: request_method = self.get data = QueryDict(url.query) content_type = None response = request_method( path, data=data, content_type=content_type, follow=False, headers=headers, **extra, ) response.redirect_chain = redirect_chain if redirect_chain[-1] in redirect_chain[:-1]: # Check that we're not redirecting to somewhere we've already # been to, to prevent loops. raise RedirectCycleError( "Redirect loop detected.", last_response=response ) if len(redirect_chain) > 20: # Such a lengthy chain likely also means a loop, but one with # a growing path, changing view, or changing query argument; # 20 is the value of "network.http.redirection-limit" from Firefox. raise RedirectCycleError("Too many redirects.", last_response=response) return response class AsyncClient(ClientMixin, AsyncRequestFactory): """ An async version of Client that creates ASGIRequests and calls through an async request path. Does not currently support "follow" on its methods. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, *, headers=None, **defaults, ): super().__init__(headers=headers, **defaults) self.handler = AsyncClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None self.headers = None async def request(self, **request): """ Make a generic request. Compose the scope dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ if "follow" in request: raise NotImplementedError( "AsyncClient request methods do not accept the follow parameter." ) scope = self._base_scope(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = await self.handler(scope) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.asgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["path"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response
112f8b029e1762408f3cf698446be9ed86fb6da39599048fb85240068586f055
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import mimetypes import posixpath from pathlib import Path from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path).lstrip("/") fullpath = Path(safe_join(document_root, path)) if fullpath.is_dir(): if show_indexes: return directory_index(path, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not fullpath.exists(): raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) # Respect the If-Modified-Since header. statobj = fullpath.stat() if not was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime ): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(str(fullpath)) content_type = content_type or "application/octet-stream" response = FileResponse(fullpath.open("rb"), content_type=content_type) response.headers["Last-Modified"] = http_date(statobj.st_mtime) if encoding: response.headers["Content-Encoding"] = encoding return response # Translatable string for static directory index template title. template_translatable = gettext_lazy("Index of %(directory)s") def directory_index(path, fullpath): try: t = loader.select_template( [ "static/directory_index.html", "static/directory_index", ] ) except TemplateDoesNotExist: with builtin_template_path("directory_index.html").open(encoding="utf-8") as fh: t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string( fh.read() ) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith("."): url = str(f.relative_to(fullpath)) if f.is_dir(): url += "/" files.append(url) c.update( { "directory": path + "/", "file_list": files, } ) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. """ try: if header is None: raise ValueError header_mtime = parse_http_date(header) if int(mtime) > header_mtime: raise ValueError except (ValueError, OverflowError): return True return False
1154f08943957adb11ab3c6cdc74b08ae0bb59afdef826010eadba9bf35ec64f
import json import os import re from pathlib import Path from django.apps import apps from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.template import Context, Engine from django.urls import translate_url from django.utils.formats import get_format from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import check_for_language, get_language from django.utils.translation.trans_real import DjangoTranslation from django.views.generic import View LANGUAGE_QUERY_PARAMETER = "language" def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def set_language(request): """ Redirect to a given URL while setting the chosen language in the session (if enabled) and in a cookie. The URL and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next_url = request.POST.get("next", request.GET.get("next")) if ( next_url or request.accepts("text/html") ) and not url_has_allowed_host_and_scheme( url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): next_url = request.META.get("HTTP_REFERER") if not url_has_allowed_host_and_scheme( url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): next_url = "/" response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204) if request.method == "POST": lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): if next_url: next_trans = translate_url(next_url, lang_code) if next_trans != next_url: response = HttpResponseRedirect(next_trans) response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, secure=settings.LANGUAGE_COOKIE_SECURE, httponly=settings.LANGUAGE_COOKIE_HTTPONLY, samesite=settings.LANGUAGE_COOKIE_SAMESITE, ) return response def get_formats(): """Return all formats strings required for i18n to work.""" FORMAT_SETTINGS = ( "DATE_FORMAT", "DATETIME_FORMAT", "TIME_FORMAT", "YEAR_MONTH_FORMAT", "MONTH_DAY_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "FIRST_DAY_OF_WEEK", "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ) return {attr: get_format(attr) for attr in FORMAT_SETTINGS} class JavaScriptCatalog(View): """ Return the selected language catalog as a JavaScript library. Receive the list of packages to check for translations in the `packages` kwarg either from the extra dictionary passed to the path() function or as a plus-sign delimited string from the request. Default is 'django.conf'. You can override the gettext domain for this view, but usually you don't want to do that as JavaScript messages go to the djangojs domain. This might be needed if you deliver your JavaScript source from Django templates. """ domain = "djangojs" packages = None def get(self, request, *args, **kwargs): locale = get_language() domain = kwargs.get("domain", self.domain) # If packages are not provided, default to all installed packages, as # DjangoTranslation without localedirs harvests them all. packages = kwargs.get("packages", "") packages = packages.split("+") if packages else self.packages paths = self.get_paths(packages) if packages else None self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) context = self.get_context_data(**kwargs) return self.render_to_response(context) def get_paths(self, packages): allowable_packages = { app_config.name: app_config for app_config in apps.get_app_configs() } app_configs = [ allowable_packages[p] for p in packages if p in allowable_packages ] if len(app_configs) < len(packages): excluded = [p for p in packages if p not in allowable_packages] raise ValueError( "Invalid package(s) provided to JavaScriptCatalog: %s" % ",".join(excluded) ) # paths of requested packages return [os.path.join(app.path, "locale") for app in app_configs] @property def _num_plurals(self): """ Return the number of plurals for this catalog language, or 2 if no plural string is available. """ match = re.search(r"nplurals=\s*(\d+)", self._plural_string or "") if match: return int(match[1]) return 2 @property def _plural_string(self): """ Return the plural string (including nplurals) for this catalog language, or None if no plural string is available. """ if "" in self.translation._catalog: for line in self.translation._catalog[""].split("\n"): if line.startswith("Plural-Forms:"): return line.split(":", 1)[1].strip() return None def get_plural(self): plural = self._plural_string if plural is not None: # This should be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : # n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [ el.strip() for el in plural.split(";") if el.strip().startswith("plural=") ][0].split("=", 1)[1] return plural def get_catalog(self): pdict = {} catalog = {} translation = self.translation seen_keys = set() while True: for key, value in translation._catalog.items(): if key == "" or key in seen_keys: continue if isinstance(key, str): catalog[key] = value elif isinstance(key, tuple): msgid, cnt = key pdict.setdefault(msgid, {})[cnt] = value else: raise TypeError(key) seen_keys.add(key) if translation._fallback: translation = translation._fallback else: break num_plurals = self._num_plurals for k, v in pdict.items(): catalog[k] = [v.get(i, "") for i in range(num_plurals)] return catalog def get_context_data(self, **kwargs): return { "catalog": self.get_catalog(), "formats": get_formats(), "plural": self.get_plural(), } def render_to_response(self, context, **response_kwargs): def indent(s): return s.replace("\n", "\n ") with builtin_template_path("i18n_catalog.js").open(encoding="utf-8") as fh: template = Engine().from_string(fh.read()) context["catalog_str"] = ( indent(json.dumps(context["catalog"], sort_keys=True, indent=2)) if context["catalog"] else None ) context["formats_str"] = indent( json.dumps(context["formats"], sort_keys=True, indent=2) ) return HttpResponse( template.render(Context(context)), 'text/javascript; charset="utf-8"' ) class JSONCatalog(JavaScriptCatalog): """ Return the selected language catalog as a JSON object. Receive the same parameters as JavaScriptCatalog and return a response with a JSON object of the following format: { "catalog": { # Translations catalog }, "formats": { # Language formats for date, time, etc. }, "plural": '...' # Expression for plural forms, or null. } """ def render_to_response(self, context, **response_kwargs): return JsonResponse(context)
d716a35016041e96c92c769ff6da4a33ef00bbd3b69eaa06daaa8ab369e58278
from pathlib import Path from django.conf import settings from django.http import HttpResponseForbidden from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.translation import gettext as _ from django.utils.version import get_docs_version # We include the template inline since we need to be able to reliably display # this error message, especially for the sake of developers, and there isn't any # other way of making it available independent of what is in the settings file. # Only the text appearing with DEBUG=False is translated. Normal translation # tags cannot be used with this inline templates as makemessages would not be # able to discover the strings. CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER c = { "title": _("Forbidden"), "main": _("CSRF verification failed. Request aborted."), "reason": reason, "no_referer": reason == REASON_NO_REFERER, "no_referer1": _( "You are seeing this message because this HTTPS site requires a " "“Referer header” to be sent by your web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties." ), "no_referer2": _( "If you have configured your browser to disable “Referer” headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for “same-origin” requests." ), "no_referer3": _( 'If you are using the <meta name="referrer" ' 'content="no-referrer"> tag or including the “Referrer-Policy: ' "no-referrer” header, please remove them. The CSRF protection " "requires the “Referer” header to do strict referer checking. If " "you’re concerned about privacy, use alternatives like " '<a rel="noreferrer" …> for links to third-party sites.' ), "no_cookie": reason == REASON_NO_CSRF_COOKIE, "no_cookie1": _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties." ), "no_cookie2": _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for “same-origin” " "requests." ), "DEBUG": settings.DEBUG, "docs_version": get_docs_version(), "more": _("More information is available with DEBUG=True."), } try: t = loader.get_template(template_name) except TemplateDoesNotExist: if template_name == CSRF_FAILURE_TEMPLATE_NAME: # If the default template doesn't exist, use the fallback template. with builtin_template_path("csrf_403.html").open(encoding="utf-8") as fh: t = Engine().from_string(fh.read()) c = Context(c) else: # Raise if a developer-specified template doesn't exist. raise return HttpResponseForbidden(t.render(c))
3b17d5045d4c494821eb3f8d85d90fa656ed858516bcfe6f8edd8d4283568d0a
""" Default Django settings. Override these with settings in the module pointed to by the DJANGO_SETTINGS_MODULE environment variable. """ # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. def gettext_noop(s): return s #################### # CORE # #################### DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing situations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # People who get code error notifications. In the format # [('Full Name', '[email protected]'), ('Full Name', '[email protected]')] ADMINS = [] # List of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = [] # Hosts/domain names that are valid for this site. # "*" matches anything, ".example.com" matches example.com and all subdomains ALLOWED_HOSTS = [] # Local time zone for this installation. All choices can be found here: # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). When USE_TZ is True, this is # interpreted as the default user time zone. TIME_ZONE = "America/Chicago" # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = True # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en-us" # Languages we provide translations for, out of the box. LANGUAGES = [ ("af", gettext_noop("Afrikaans")), ("ar", gettext_noop("Arabic")), ("ar-dz", gettext_noop("Algerian Arabic")), ("ast", gettext_noop("Asturian")), ("az", gettext_noop("Azerbaijani")), ("bg", gettext_noop("Bulgarian")), ("be", gettext_noop("Belarusian")), ("bn", gettext_noop("Bengali")), ("br", gettext_noop("Breton")), ("bs", gettext_noop("Bosnian")), ("ca", gettext_noop("Catalan")), ("ckb", gettext_noop("Central Kurdish (Sorani)")), ("cs", gettext_noop("Czech")), ("cy", gettext_noop("Welsh")), ("da", gettext_noop("Danish")), ("de", gettext_noop("German")), ("dsb", gettext_noop("Lower Sorbian")), ("el", gettext_noop("Greek")), ("en", gettext_noop("English")), ("en-au", gettext_noop("Australian English")), ("en-gb", gettext_noop("British English")), ("eo", gettext_noop("Esperanto")), ("es", gettext_noop("Spanish")), ("es-ar", gettext_noop("Argentinian Spanish")), ("es-co", gettext_noop("Colombian Spanish")), ("es-mx", gettext_noop("Mexican Spanish")), ("es-ni", gettext_noop("Nicaraguan Spanish")), ("es-ve", gettext_noop("Venezuelan Spanish")), ("et", gettext_noop("Estonian")), ("eu", gettext_noop("Basque")), ("fa", gettext_noop("Persian")), ("fi", gettext_noop("Finnish")), ("fr", gettext_noop("French")), ("fy", gettext_noop("Frisian")), ("ga", gettext_noop("Irish")), ("gd", gettext_noop("Scottish Gaelic")), ("gl", gettext_noop("Galician")), ("he", gettext_noop("Hebrew")), ("hi", gettext_noop("Hindi")), ("hr", gettext_noop("Croatian")), ("hsb", gettext_noop("Upper Sorbian")), ("hu", gettext_noop("Hungarian")), ("hy", gettext_noop("Armenian")), ("ia", gettext_noop("Interlingua")), ("id", gettext_noop("Indonesian")), ("ig", gettext_noop("Igbo")), ("io", gettext_noop("Ido")), ("is", gettext_noop("Icelandic")), ("it", gettext_noop("Italian")), ("ja", gettext_noop("Japanese")), ("ka", gettext_noop("Georgian")), ("kab", gettext_noop("Kabyle")), ("kk", gettext_noop("Kazakh")), ("km", gettext_noop("Khmer")), ("kn", gettext_noop("Kannada")), ("ko", gettext_noop("Korean")), ("ky", gettext_noop("Kyrgyz")), ("lb", gettext_noop("Luxembourgish")), ("lt", gettext_noop("Lithuanian")), ("lv", gettext_noop("Latvian")), ("mk", gettext_noop("Macedonian")), ("ml", gettext_noop("Malayalam")), ("mn", gettext_noop("Mongolian")), ("mr", gettext_noop("Marathi")), ("ms", gettext_noop("Malay")), ("my", gettext_noop("Burmese")), ("nb", gettext_noop("Norwegian Bokmål")), ("ne", gettext_noop("Nepali")), ("nl", gettext_noop("Dutch")), ("nn", gettext_noop("Norwegian Nynorsk")), ("os", gettext_noop("Ossetic")), ("pa", gettext_noop("Punjabi")), ("pl", gettext_noop("Polish")), ("pt", gettext_noop("Portuguese")), ("pt-br", gettext_noop("Brazilian Portuguese")), ("ro", gettext_noop("Romanian")), ("ru", gettext_noop("Russian")), ("sk", gettext_noop("Slovak")), ("sl", gettext_noop("Slovenian")), ("sq", gettext_noop("Albanian")), ("sr", gettext_noop("Serbian")), ("sr-latn", gettext_noop("Serbian Latin")), ("sv", gettext_noop("Swedish")), ("sw", gettext_noop("Swahili")), ("ta", gettext_noop("Tamil")), ("te", gettext_noop("Telugu")), ("tg", gettext_noop("Tajik")), ("th", gettext_noop("Thai")), ("tk", gettext_noop("Turkmen")), ("tr", gettext_noop("Turkish")), ("tt", gettext_noop("Tatar")), ("udm", gettext_noop("Udmurt")), ("uk", gettext_noop("Ukrainian")), ("ur", gettext_noop("Urdu")), ("uz", gettext_noop("Uzbek")), ("vi", gettext_noop("Vietnamese")), ("zh-hans", gettext_noop("Simplified Chinese")), ("zh-hant", gettext_noop("Traditional Chinese")), ] # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ["he", "ar", "ar-dz", "ckb", "fa", "ur"] # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = [] # Settings for language cookie LANGUAGE_COOKIE_NAME = "django_language" LANGUAGE_COOKIE_AGE = None LANGUAGE_COOKIE_DOMAIN = None LANGUAGE_COOKIE_PATH = "/" LANGUAGE_COOKIE_SECURE = False LANGUAGE_COOKIE_HTTPONLY = False LANGUAGE_COOKIE_SAMESITE = None # Not-necessarily-technical managers of the site. They get broken link # notifications and other various emails. MANAGERS = ADMINS # Default charset to use for all HttpResponse objects, if a MIME type isn't # manually specified. It's used to construct the Content-Type header. DEFAULT_CHARSET = "utf-8" # Email address that error messages come from. SERVER_EMAIL = "root@localhost" # Database connection info. If left empty, will default to the dummy backend. DATABASES = {} # Classes used to implement DB routing behavior. DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" # Host for sending email. EMAIL_HOST = "localhost" # Port for sending email. EMAIL_PORT = 25 # Whether to send SMTP 'Date' header in the local time zone or in UTC. EMAIL_USE_LOCALTIME = False # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" EMAIL_USE_TLS = False EMAIL_USE_SSL = False EMAIL_SSL_CERTFILE = None EMAIL_SSL_KEYFILE = None EMAIL_TIMEOUT = None # List of strings representing installed apps. INSTALLED_APPS = [] TEMPLATES = [] # Default form rendering class. FORM_RENDERER = "django.forms.renderers.DjangoTemplates" # Default email address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = "webmaster@localhost" # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = "[Django] " # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = [ # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search'), # ] DISALLOWED_USER_AGENTS = [] ABSOLUTE_URL_OVERRIDES = {} # List of compiled regular expression objects representing URLs that need not # be reported by BrokenLinkEmailsMiddleware. Here are a few examples: # import re # IGNORABLE_404_URLS = [ # re.compile(r'^/apple-touch-icon.*\.png$'), # re.compile(r'^/favicon.ico$'), # re.compile(r'^/robots.txt$'), # re.compile(r'^/phpmyadmin/'), # re.compile(r'\.(cgi|php|pl)$'), # ] IGNORABLE_404_URLS = [] # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = "" # List of secret keys used to verify the validity of signatures. This allows # secret key rotation. SECRET_KEY_FALLBACKS = [] # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, } # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = "" # URL that handles the media served from MEDIA_ROOT. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = "" # Absolute path to the directory static files should be collected to. # Example: "/var/www/example.com/static/" STATIC_ROOT = None # URL that handles the static files served from STATIC_ROOT. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = None # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = [ "django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler", ] # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum size in bytes of request data (excluding file uploads) that will be # read before a SuspiciousOperation (RequestDataTooBig) is raised. DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum number of GET/POST parameters that will be read before a # SuspiciousOperation (TooManyFieldsSent) is raised. DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 # Maximum number of files encoded in a multipart upload that will be read # before a SuspiciousOperation (TooManyFilesSent) is raised. DATA_UPLOAD_MAX_NUMBER_FILES = 100 # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see # https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_PERMISSIONS = 0o644 # The numeric mode to assign to newly-created directories, when uploading files. # The value should be a mode as you'd pass to os.chmod; # see https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_DIRECTORY_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = "N j, Y" # Default formatting for datetime objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = "N j, Y, P" # Default formatting for time objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = "P" # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = "F Y" # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = "F j" # Default short formatting for date objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = "m/d/Y" # Default short formatting for datetime objects. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = "m/d/Y P" # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = [ "%Y-%m-%d", # '2006-10-25' "%m/%d/%Y", # '10/25/2006' "%m/%d/%y", # '10/25/06' "%b %d %Y", # 'Oct 25 2006' "%b %d, %Y", # 'Oct 25, 2006' "%d %b %Y", # '25 Oct 2006' "%d %b, %Y", # '25 Oct, 2006' "%B %d %Y", # 'October 25 2006' "%B %d, %Y", # 'October 25, 2006' "%d %B %Y", # '25 October 2006' "%d %B, %Y", # '25 October, 2006' ] # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = [ "%H:%M:%S", # '14:30:59' "%H:%M:%S.%f", # '14:30:59.000200' "%H:%M", # '14:30' ] # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = [ "%Y-%m-%d %H:%M:%S", # '2006-10-25 14:30:59' "%Y-%m-%d %H:%M:%S.%f", # '2006-10-25 14:30:59.000200' "%Y-%m-%d %H:%M", # '2006-10-25 14:30' "%m/%d/%Y %H:%M:%S", # '10/25/2006 14:30:59' "%m/%d/%Y %H:%M:%S.%f", # '10/25/2006 14:30:59.000200' "%m/%d/%Y %H:%M", # '10/25/2006 14:30' "%m/%d/%y %H:%M:%S", # '10/25/06 14:30:59' "%m/%d/%y %H:%M:%S.%f", # '10/25/06 14:30:59.000200' "%m/%d/%y %H:%M", # '10/25/06 14:30' ] # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = "." # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when splitting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = "," # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = "" DEFAULT_INDEX_TABLESPACE = "" # Default primary key field type. DEFAULT_AUTO_FIELD = "django.db.models.AutoField" # Default X-Frame-Options header value X_FRAME_OPTIONS = "DENY" USE_X_FORWARDED_HOST = False USE_X_FORWARDED_PORT = False # The Python dotted path to the WSGI application that Django's internal server # (runserver) will use. If `None`, the return value of # 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same # behavior as previous versions of Django. Otherwise this should point to an # actual WSGI application object. WSGI_APPLICATION = None # If your Django app is behind a proxy that sets a header to specify secure # connections, AND that proxy ensures that user-submitted headers with the # same name are ignored (so that people can't spoof it), set this value to # a tuple of (header_name, header_value). For any requests that come in with # that header/value, request.is_secure() will return True. # WARNING! Only set this if you fully understand what you're doing. Otherwise, # you may be opening yourself up to a security risk. SECURE_PROXY_SSL_HEADER = None ############## # MIDDLEWARE # ############## # List of middleware to use. Order is important; in the request phase, these # middleware will be applied in the order given, and in the response # phase the middleware will be applied in reverse order. MIDDLEWARE = [] ############ # SESSIONS # ############ # Cache to store session data if using the cache session backend. SESSION_CACHE_ALIAS = "default" # Cookie name. This can be whatever you want. SESSION_COOKIE_NAME = "sessionid" # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # A string like "example.com", or None for standard domain cookie. SESSION_COOKIE_DOMAIN = None # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_SECURE = False # The path of the session cookie. SESSION_COOKIE_PATH = "/" # Whether to use the HttpOnly flag. SESSION_COOKIE_HTTPONLY = True # Whether to set the flag restricting cookie leaks on cross-site requests. # This can be 'Lax', 'Strict', 'None', or False to disable the flag. SESSION_COOKIE_SAMESITE = "Lax" # Whether to save the session data on every request. SESSION_SAVE_EVERY_REQUEST = False # Whether a user's session cookie expires when the web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # The module to store session data SESSION_ENGINE = "django.contrib.sessions.backends.db" # Directory to store session files if using the file session module. If None, # the backend will use a sensible default. SESSION_FILE_PATH = None # class to serialize session data SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer" ######### # CACHE # ######### # The cache backends to use. CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", } } CACHE_MIDDLEWARE_KEY_PREFIX = "" CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = "default" ################## # AUTHENTICATION # ################## AUTH_USER_MODEL = "auth.User" AUTHENTICATION_BACKENDS = ["django.contrib.auth.backends.ModelBackend"] LOGIN_URL = "/accounts/login/" LOGIN_REDIRECT_URL = "/accounts/profile/" LOGOUT_REDIRECT_URL = None # The number of seconds a password reset link is valid for (default: 3 days). PASSWORD_RESET_TIMEOUT = 60 * 60 * 24 * 3 # the first hasher in this list is the preferred algorithm. any # password using different algorithms will be converted automatically # upon login PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher", ] AUTH_PASSWORD_VALIDATORS = [] ########### # SIGNING # ########### SIGNING_BACKEND = "django.core.signing.TimestampSigner" ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = "django.views.csrf.csrf_failure" # Settings for CSRF cookie. CSRF_COOKIE_NAME = "csrftoken" CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_PATH = "/" CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE = "Lax" CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" CSRF_TRUSTED_ORIGINS = [] CSRF_USE_SESSIONS = False ############ # MESSAGES # ############ # Class to use as messages backend MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage" # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = "logging.config.dictConfig" # Custom logging configuration. LOGGING = {} # Default exception reporter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER = "django.views.debug.ExceptionReporter" # Default exception reporter filter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER_FILTER = "django.views.debug.SafeExceptionReporterFilter" ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = "django.test.runner.DiscoverRunner" # Apps that don't need to be serialized at test database creation time # (only apps with migrations are to start with) TEST_NON_SERIALIZED_APPS = [] ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = [] ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS = [] # The default file storage backend used during the build process STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ] ############## # MIGRATIONS # ############## # Migration module overrides for apps, by app label. MIGRATION_MODULES = {} ################# # SYSTEM CHECKS # ################# # List of all issues generated by system checks that should be silenced. Light # issues like warnings, infos or debugs will not generate a message. Silencing # serious issues like errors and criticals does not result in hiding the # message, but Django will not stop you from e.g. running server. SILENCED_SYSTEM_CHECKS = [] ####################### # SECURITY MIDDLEWARE # ####################### SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin" SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_HSTS_PRELOAD = False SECURE_HSTS_SECONDS = 0 SECURE_REDIRECT_EXEMPT = [] SECURE_REFERRER_POLICY = "same-origin" SECURE_SSL_HOST = None SECURE_SSL_REDIRECT = False
0f3f77023f407ee20322c75f0ef8f61fe193ea409bedfd87036d63d5269ae75a
""" This is the Django template system. How it works: The Lexer.tokenize() method converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements (TokenType.BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of a ForNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> from django import template >>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>' >>> t = template.Template(s) (t is now a compiled template, and its render() method can be called multiple times with multiple contexts) >>> c = template.Context({'test':True, 'varvalue': 'Hello'}) >>> t.render(c) '<html><h1>Hello</h1></html>' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) '<html></html>' """ import inspect import logging import re from enum import Enum from django.template.context import BaseContext from django.utils.formats import localize from django.utils.html import conditional_escape, escape from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import get_text_list, smart_split, unescape_string_literal from django.utils.timezone import template_localtime from django.utils.translation import gettext_lazy, pgettext_lazy from .exceptions import TemplateSyntaxError # template syntax constants FILTER_SEPARATOR = "|" FILTER_ARGUMENT_SEPARATOR = ":" VARIABLE_ATTRIBUTE_SEPARATOR = "." BLOCK_TAG_START = "{%" BLOCK_TAG_END = "%}" VARIABLE_TAG_START = "{{" VARIABLE_TAG_END = "}}" COMMENT_TAG_START = "{#" COMMENT_TAG_END = "#}" SINGLE_BRACE_START = "{" SINGLE_BRACE_END = "}" # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE = "<unknown source>" # Match BLOCK_TAG_*, VARIABLE_TAG_*, and COMMENT_TAG_* tags and capture the # entire tag, including start/end delimiters. Using re.compile() is faster # than instantiating SimpleLazyObject with _lazy_re_compile(). tag_re = re.compile(r"({%.*?%}|{{.*?}}|{#.*?#})") logger = logging.getLogger("django.template") class TokenType(Enum): TEXT = 0 VAR = 1 BLOCK = 2 COMMENT = 3 class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params class Origin: def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __repr__(self): return "<%s name=%r>" % (self.__class__.__qualname__, self.name) def __eq__(self, other): return ( isinstance(other, Origin) and self.name == other.name and self.loader == other.loader ) @property def loader_name(self): if self.loader: return "%s.%s" % ( self.loader.__module__, self.loader.__class__.__name__, ) class Template: def __init__(self, template_string, origin=None, name=None, engine=None): # If Template is instantiated directly rather than from an Engine and # exactly one Django template engine is configured, use that engine. # This is required to preserve backwards-compatibility for direct use # e.g. Template('...').render(Context({...})) if engine is None: from .engine import Engine engine = Engine.get_default() if origin is None: origin = Origin(UNKNOWN_SOURCE) self.name = name self.origin = origin self.engine = engine self.source = str(template_string) # May be lazy. self.nodelist = self.compile_nodelist() def __repr__(self): return '<%s template_string="%s...">' % ( self.__class__.__qualname__, self.source[:20].replace("\n", ""), ) def _render(self, context): return self.nodelist.render(context) def render(self, context): "Display stage -- can be called many times" with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def compile_nodelist(self): """ Parse and compile the template source into a nodelist. If debug is True and an exception occurs during parsing, the exception is annotated with contextual line information where it occurred in the template source. """ if self.engine.debug: lexer = DebugLexer(self.source) else: lexer = Lexer(self.source) tokens = lexer.tokenize() parser = Parser( tokens, self.engine.template_libraries, self.engine.template_builtins, self.origin, ) try: return parser.parse() except Exception as e: if self.engine.debug: e.template_debug = self.get_exception_info(e, e.token) raise def get_exception_info(self, exception, token): """ Return a dictionary containing contextual line information of where the exception occurred in the template. The following information is provided: message The message of the exception raised. source_lines The lines before, after, and including the line the exception occurred on. line The line number the exception occurred on. before, during, after The line the exception occurred on split into three parts: 1. The content before the token that raised the error. 2. The token that raised the error. 3. The content after the token that raised the error. total The number of lines in source_lines. top The line number where source_lines starts. bottom The line number where source_lines ends. start The start position of the token in the template source. end The end position of the token in the template source. """ start, end = token.position context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(self.source)): if start >= upto and end <= next: line = num before = escape(self.source[upto:start]) during = escape(self.source[start:end]) after = escape(self.source[end:next]) source_lines.append((num, escape(self.source[upto:next]))) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) # In some rare cases exc_value.args can be empty or an invalid # string. try: message = str(exception.args[0]) except (IndexError, UnicodeDecodeError): message = "(Could not get exception message)" return { "message": message, "source_lines": source_lines[top:bottom], "before": before, "during": during, "after": after, "top": top, "bottom": bottom, "total": total, "line": line, "name": self.origin.name, "start": start, "end": end, } def linebreak_iter(template_source): yield 0 p = template_source.find("\n") while p >= 0: yield p + 1 p = template_source.find("\n", p + 1) yield len(template_source) + 1 class Token: def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT. contents The token source string. position An optional tuple containing the start and end index of the token in the template source. This is used for traceback information when debug is on. lineno The line number the token appears on in the template source. This is used for traceback information and gettext files. """ self.token_type, self.contents = token_type, contents self.lineno = lineno self.position = position def __repr__(self): token_name = self.token_type.name.capitalize() return '<%s token: "%s...">' % ( token_name, self.contents[:20].replace("\n", ""), ) def split_contents(self): split = [] bits = smart_split(self.contents) for bit in bits: # Handle translation-marked template pieces if bit.startswith(('_("', "_('")): sentinel = bit[2] + ")" trans_bit = [bit] while not bit.endswith(sentinel): bit = next(bits) trans_bit.append(bit) bit = " ".join(trans_bit) split.append(bit) return split class Lexer: def __init__(self, template_string): self.template_string = template_string self.verbatim = False def __repr__(self): return '<%s template_string="%s...", verbatim=%s>' % ( self.__class__.__qualname__, self.template_string[:20].replace("\n", ""), self.verbatim, ) def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for token_string in tag_re.split(self.template_string): if token_string: result.append(self.create_token(token_string, None, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result def create_token(self, token_string, position, lineno, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag: # The [0:2] and [2:-2] ranges below strip off *_TAG_START and # *_TAG_END. The 2's are hard-coded for performance. Using # len(BLOCK_TAG_START) would permit BLOCK_TAG_START to be # different, but it's not likely that the TAG_START values will # change anytime soon. token_start = token_string[0:2] if token_start == BLOCK_TAG_START: content = token_string[2:-2].strip() if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) # Otherwise, the current verbatim block is ending. self.verbatim = False elif content[:9] in ("verbatim", "verbatim "): # Then a verbatim block is starting. self.verbatim = "end%s" % content return Token(TokenType.BLOCK, content, position, lineno) if not self.verbatim: content = token_string[2:-2].strip() if token_start == VARIABLE_TAG_START: return Token(TokenType.VAR, content, position, lineno) # BLOCK_TAG_START was handled above. assert token_start == COMMENT_TAG_START return Token(TokenType.COMMENT, content, position, lineno) return Token(TokenType.TEXT, token_string, position, lineno) class DebugLexer(Lexer): def _tag_re_split_positions(self): last = 0 for match in tag_re.finditer(self.template_string): start, end = match.span() yield last, start yield start, end last = end yield last, len(self.template_string) # This parallels the use of tag_re.split() in Lexer.tokenize(). def _tag_re_split(self): for position in self._tag_re_split_positions(): yield self.template_string[slice(*position)], position def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True. """ # For maintainability, it is helpful if the implementation below can # continue to closely parallel Lexer.tokenize()'s implementation. in_tag = False lineno = 1 result = [] for token_string, position in self._tag_re_split(): if token_string: result.append(self.create_token(token_string, position, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result class Parser: def __init__(self, tokens, libraries=None, builtins=None, origin=None): # Reverse the tokens so delete_first_token(), prepend_token(), and # next_token() can operate at the end of the list in constant time. self.tokens = list(reversed(tokens)) self.tags = {} self.filters = {} self.command_stack = [] if libraries is None: libraries = {} if builtins is None: builtins = [] self.libraries = libraries for builtin in builtins: self.add_library(builtin) self.origin = origin def __repr__(self): return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens) def parse(self, parse_until=None): """ Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ if parse_until is None: parse_until = [] nodelist = NodeList() while self.tokens: token = self.next_token() # Use the raw values here for TokenType.* for a tiny performance boost. token_type = token.token_type.value if token_type == 0: # TokenType.TEXT self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token_type == 1: # TokenType.VAR if not token.contents: raise self.error( token, "Empty variable tag on line %d" % token.lineno ) try: filter_expression = self.compile_filter(token.contents) except TemplateSyntaxError as e: raise self.error(token, e) var_node = VariableNode(filter_expression) self.extend_nodelist(nodelist, var_node, token) elif token_type == 2: # TokenType.BLOCK try: command = token.contents.split()[0] except IndexError: raise self.error(token, "Empty block tag on line %d" % token.lineno) if command in parse_until: # A matching token has been reached. Return control to # the caller. Put the token back on the token list so the # caller knows where it terminated. self.prepend_token(token) return nodelist # Add the token to the command stack. This is used for error # messages if further parsing fails due to an unclosed block # tag. self.command_stack.append((command, token)) # Get the tag callback function from the ones registered with # the parser. try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) # Compile the callback into a node object and add it to # the node list. try: compiled_result = compile_func(self, token) except Exception as e: raise self.error(token, e) self.extend_nodelist(nodelist, compiled_result, token) # Compile success. Remove the token from the command stack. self.command_stack.pop() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TokenType.BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def extend_nodelist(self, nodelist, node, token): # Check that non-text nodes don't appear before an extends tag. if node.must_be_first and nodelist.contains_nontext: raise self.error( token, "%r must be the first tag in the template." % node, ) if not isinstance(node, TextNode): nodelist.contains_nontext = True # Set origin and token here since we can't modify the node __init__() # method. node.token = token node.origin = self.origin nodelist.append(node) def error(self, token, e): """ Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ if not isinstance(e, Exception): e = TemplateSyntaxError(e) if not hasattr(e, "token"): e.token = token return e def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], "or"), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command), ) def unclosed_block_tag(self, parse_until): command, token = self.command_stack.pop() msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % ( token.lineno, command, ", ".join(parse_until), ) raise self.error(token, msg) def next_token(self): return self.tokens.pop() def prepend_token(self, token): self.tokens.append(token) def delete_first_token(self): del self.tokens[-1] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string "i18n_open": re.escape("_("), "i18n_close": re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+|%(num)s)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+|%(num)s) ) )? )""" % { "constant": constant_string, "num": r"[-+\.]?\d[\d\.e]*", "var_chars": r"\w\.", "filter_sep": re.escape(FILTER_SEPARATOR), "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE) class FilterExpression: """ Parse a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> """ __slots__ = ("token", "filters", "var", "is_var") def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var_obj = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError( "Could not parse some characters: " "%s|%s|%s" % (token[:upto], token[upto:start], token[start:]) ) if var_obj is None: var, constant = match["var"], match["constant"] if constant: try: var_obj = Variable(constant).resolve({}) except VariableDoesNotExist: var_obj = None elif var is None: raise TemplateSyntaxError( "Could not find variable at start of %s." % token ) else: var_obj = Variable(var) else: filter_name = match["filter_name"] args = [] constant_arg, var_arg = match["constant_arg"], match["var_arg"] if constant_arg: args.append((False, Variable(constant_arg).resolve({}))) elif var_arg: args.append((True, Variable(var_arg))) filter_func = parser.find_filter(filter_name) self.args_check(filter_name, filter_func, args) filters.append((filter_func, args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError( "Could not parse the remainder: '%s' " "from '%s'" % (token[upto:], token) ) self.filters = filters self.var = var_obj self.is_var = isinstance(var_obj, Variable) def resolve(self, context, ignore_failures=False): if self.is_var: try: obj = self.var.resolve(context) except VariableDoesNotExist: if ignore_failures: obj = None else: string_if_invalid = context.template.engine.string_if_invalid if string_if_invalid: if "%s" in string_if_invalid: return string_if_invalid % self.var else: return string_if_invalid else: obj = string_if_invalid else: obj = self.var for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(mark_safe(arg)) else: arg_vals.append(arg.resolve(context)) if getattr(func, "expects_localtime", False): obj = template_localtime(obj, context.use_tz) if getattr(func, "needs_autoescape", False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, "is_safe", False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) else: obj = new_obj return obj def args_check(name, func, provided): provided = list(provided) # First argument, filter input, is implied. plen = len(provided) + 1 # Check to see if a decorator is providing the real function. func = inspect.unwrap(func) args, _, _, defaults, _, _, _ = inspect.getfullargspec(func) alen = len(args) dlen = len(defaults or []) # Not enough OR Too many if plen < (alen - dlen) or plen > alen: raise TemplateSyntaxError( "%s requires %d arguments, %d provided" % (name, alen - dlen, plen) ) return True args_check = staticmethod(args_check) def __str__(self): return self.token def __repr__(self): return "<%s %r>" % (self.__class__.__qualname__, self.token) class Variable: """ A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('article').resolve(c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ __slots__ = ("var", "literal", "lookups", "translate", "message_context") def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False self.message_context = None if not isinstance(var, str): raise TypeError("Variable must be a string or number, got %s" % type(var)) try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. # Try to interpret values containing a period or an 'e'/'E' # (possibly scientific notation) as a float; otherwise, try int. if "." in var or "e" in var.lower(): self.literal = float(var) # "2." is invalid if var[-1] == ".": raise ValueError else: self.literal = int(var) except ValueError: # A ValueError means that the variable isn't a number. if var[0:2] == "_(" and var[-1] == ")": # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. try: self.literal = mark_safe(unescape_string_literal(var)) except ValueError: # Otherwise we'll set self.lookups so that resolve() knows we're # dealing with a bonafide variable if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_": raise TemplateSyntaxError( "Variables and attributes may " "not begin with underscores: '%s'" % var ) self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR)) def resolve(self, context): """Resolve this variable against a given context.""" if self.lookups is not None: # We're dealing with a variable that needs to be resolved value = self._resolve_lookup(context) else: # We're dealing with a literal, so it's already been "resolved" value = self.literal if self.translate: is_safe = isinstance(value, SafeData) msgid = value.replace("%", "%%") msgid = mark_safe(msgid) if is_safe else msgid if self.message_context: return pgettext_lazy(self.message_context, msgid) else: return gettext_lazy(msgid) return value def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.var) def __str__(self): return self.var def _resolve_lookup(self, context): """ Perform resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """ current = context try: # catch-all for silent variable failures for bit in self.lookups: try: # dictionary lookup current = current[bit] # ValueError/IndexError are for numpy.array lookup on # numpy < 1.9 and 1.9+ respectively except (TypeError, AttributeError, KeyError, ValueError, IndexError): try: # attribute lookup # Don't return class attributes if the class is the context: if isinstance(current, BaseContext) and getattr( type(current), bit ): raise AttributeError current = getattr(current, bit) except (TypeError, AttributeError): # Reraise if the exception was raised by a @property if not isinstance(current, BaseContext) and bit in dir(current): raise try: # list-index lookup current = current[int(bit)] except ( IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key TypeError, ): # unsubscriptable object raise VariableDoesNotExist( "Failed lookup for key [%s] in %r", (bit, current), ) # missing attribute if callable(current): if getattr(current, "do_not_call_in_templates", False): pass elif getattr(current, "alters_data", False): current = context.template.engine.string_if_invalid else: try: # method call (assuming no args required) current = current() except TypeError: try: signature = inspect.signature(current) except ValueError: # No signature found. current = context.template.engine.string_if_invalid else: try: signature.bind() except TypeError: # Arguments *were* required. # Invalid method call. current = context.template.engine.string_if_invalid else: raise except Exception as e: template_name = getattr(context, "template_name", None) or "unknown" logger.debug( "Exception while resolving variable '%s' in template '%s'.", bit, template_name, exc_info=True, ) if getattr(e, "silent_variable_failure", False): current = context.template.engine.string_if_invalid else: raise return current class Node: # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes. must_be_first = False child_nodelists = ("nodelist",) token = None def render(self, context): """ Return the node rendered as a string. """ pass def render_annotated(self, context): """ Render the node. If debug is True and an exception occurs during rendering, the exception is annotated with contextual line information where it occurred in the template. For internal usage this method is preferred over using the render method directly. """ try: return self.render(context) except Exception as e: if context.template.engine.debug: # Store the actual node that caused the exception. if not hasattr(e, "_culprit_node"): e._culprit_node = self if ( not hasattr(e, "template_debug") and context.render_context.template.origin == e._culprit_node.origin ): e.template_debug = ( context.render_context.template.get_exception_info( e, e._culprit_node.token, ) ) raise def get_nodes_by_type(self, nodetype): """ Return a list of all nodes (within this node and its nodelist) of the given type """ nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): return SafeString("".join([node.render_annotated(context) for node in self])) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes class TextNode(Node): child_nodelists = () def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s def render_annotated(self, context): """ Return the given value. The default implementation of this method handles exceptions raised during rendering, which is not necessary for text nodes. """ return self.s def render_value_in_context(value, context): """ Convert any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a string. If value is a string, it's expected to already be translated. """ value = template_localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=context.use_l10n) if context.autoescape: if not issubclass(type(value), str): value = str(value) return conditional_escape(value) else: return str(value) class VariableNode(Node): child_nodelists = () def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail # quietly. return "" return render_value_in_context(output, context) # Regex for token keyword arguments kwarg_re = _lazy_re_compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ Parse token keyword arguments and return a dictionary of the arguments retrieved from the ``bits`` token list. `bits` is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list. `support_legacy` - if True, the legacy format ``1 as foo`` is accepted. Otherwise, only the standard ``foo=1`` format is allowed. There is no requirement for all remaining token ``bits`` to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached. """ if not bits: return {} match = kwarg_re.match(bits[0]) kwarg_format = match and match[1] if not kwarg_format: if not support_legacy: return {} if len(bits) < 3 or bits[1] != "as": return {} kwargs = {} while bits: if kwarg_format: match = kwarg_re.match(bits[0]) if not match or not match[1]: return kwargs key, value = match.groups() del bits[:1] else: if len(bits) < 3 or bits[1] != "as": return kwargs key, value = bits[2], bits[0] del bits[:3] kwargs[key] = parser.compile_filter(value) if bits and not kwarg_format: if bits[0] != "and": return kwargs del bits[:1] return kwargs
f07786220962c42161baf3c29267c817a21acedcd8ee69f73f05d5a831e14402
"""Default variable filters.""" import random as random_module import re import types import warnings from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation, getcontext from functools import wraps from inspect import unwrap from operator import itemgetter from pprint import pformat from urllib.parse import quote from django.utils import formats from django.utils.dateformat import format, time_format from django.utils.deprecation import RemovedInDjango51Warning from django.utils.encoding import iri_to_uri from django.utils.html import avoid_wrapping, conditional_escape, escape, escapejs from django.utils.html import json_script as _json_script from django.utils.html import linebreaks, strip_tags from django.utils.html import urlize as _urlize from django.utils.safestring import SafeData, mark_safe from django.utils.text import Truncator, normalize_newlines, phone2numeric from django.utils.text import slugify as _slugify from django.utils.text import wrap from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import VARIABLE_ATTRIBUTE_SEPARATOR from .library import Library register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive strings. The object passed as the first positional argument will be converted to a string. """ @wraps(func) def _dec(first, *args, **kwargs): first = str(first) result = func(first, *args, **kwargs) if isinstance(first, SafeData) and getattr(unwrap(func), "is_safe", False): result = mark_safe(result) return result return _dec ################### # STRINGS # ################### @register.filter(is_safe=True) @stringfilter def addslashes(value): """ Add slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace("\\", "\\\\").replace('"', '\\"').replace("'", "\\'") @register.filter(is_safe=True) @stringfilter def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:] @register.filter("escapejs") @stringfilter def escapejs_filter(value): """Hex encode characters for use in JavaScript strings.""" return escapejs(value) @register.filter(is_safe=True) def json_script(value, element_id=None): """ Output value JSON-encoded, wrapped in a <script type="application/json"> tag (with an optional id). """ return _json_script(value, element_id) @register.filter(is_safe=True) def floatformat(text, arg=-1): """ Display a float to a specified number of decimal places. If called without an argument, display the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If arg has the 'g' suffix, force the result to be grouped by the THOUSAND_SEPARATOR for the active locale. When the active locale is en (English): * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67" * {{ 10000|floatformat:"g" }} displays "10,000" If arg has the 'u' suffix, force the result to be unlocalized. When the active locale is pl (Polish): * {{ 66666.6666|floatformat:"2" }} displays "66666,67" * {{ 66666.6666|floatformat:"2u" }} displays "66666.67" If the input float is infinity or NaN, display the string representation of that value. """ force_grouping = False use_l10n = True if isinstance(arg, str): last_char = arg[-1] if arg[-2:] in {"gu", "ug"}: force_grouping = True use_l10n = False arg = arg[:-2] or -1 elif last_char == "g": force_grouping = True arg = arg[:-1] or -1 elif last_char == "u": use_l10n = False arg = arg[:-1] or -1 try: input_val = str(text) d = Decimal(input_val) except InvalidOperation: try: d = Decimal(str(float(text))) except (ValueError, InvalidOperation, TypeError): return "" try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p <= 0: return mark_safe( formats.number_format( "%d" % (int(d)), 0, use_l10n=use_l10n, force_grouping=force_grouping, ) ) exp = Decimal(1).scaleb(-abs(p)) # Set the precision high enough to avoid an exception (#15789). tupl = d.as_tuple() units = len(tupl[1]) units += -tupl[2] if m else tupl[2] prec = abs(p) + units + 1 prec = max(getcontext().prec, prec) # Avoid conversion to scientific notation by accessing `sign`, `digits`, # and `exponent` from Decimal.as_tuple() directly. rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)) sign, digits, exponent = rounded_d.as_tuple() digits = [str(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append("0") digits.insert(-exponent, ".") if sign and rounded_d: digits.append("-") number = "".join(reversed(digits)) return mark_safe( formats.number_format( number, abs(p), use_l10n=use_l10n, force_grouping=force_grouping, ) ) @register.filter(is_safe=True) @stringfilter def iriencode(value): """Escape an IRI value for use in a URL.""" return iri_to_uri(value) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linenumbers(value, autoescape=True): """Display text with line numbers.""" lines = value.split("\n") # Find the maximum width of the line count, for use with zero padding # string format command width = str(len(str(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) return mark_safe("\n".join(lines)) @register.filter(is_safe=True) @stringfilter def lower(value): """Convert a string into all lowercase.""" return value.lower() @register.filter(is_safe=False) @stringfilter def make_list(value): """ Return the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) @register.filter(is_safe=True) @stringfilter def slugify(value): """ Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ return _slugify(value) @register.filter(is_safe=True) def stringformat(value, arg): """ Format the variable according to the arg, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading "%" is dropped. See https://docs.python.org/library/stdtypes.html#printf-style-string-formatting for documentation of Python string formatting. """ if isinstance(value, tuple): value = str(value) try: return ("%" + str(arg)) % value except (ValueError, TypeError): return "" @register.filter(is_safe=True) @stringfilter def title(value): """Convert a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m[0].lower(), value.title()) return re.sub(r"\d([A-Z])", lambda m: m[0].lower(), t) @register.filter(is_safe=True) @stringfilter def truncatechars(value, arg): """Truncate a string after `arg` number of characters.""" try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).chars(length) @register.filter(is_safe=True) @stringfilter def truncatechars_html(value, arg): """ Truncate HTML after `arg` number of chars. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).chars(length, html=True) @register.filter(is_safe=True) @stringfilter def truncatewords(value, arg): """ Truncate a string after `arg` number of words. Remove newlines within the string. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).words(length, truncate=" …") @register.filter(is_safe=True) @stringfilter def truncatewords_html(value, arg): """ Truncate HTML after `arg` number of words. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).words(length, html=True, truncate=" …") @register.filter(is_safe=False) @stringfilter def upper(value): """Convert a string into all uppercase.""" return value.upper() @register.filter(is_safe=False) @stringfilter def urlencode(value, safe=None): """ Escape a value for use in a URL. The ``safe`` parameter determines the characters which should not be escaped by Python's quote() function. If not provided, use the default safe characters (but an empty string can be provided when *all* characters should be escaped). """ kwargs = {} if safe is not None: kwargs["safe"] = safe return quote(value, **kwargs) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlize(value, autoescape=True): """Convert URLs in plain text into clickable links.""" return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlizetrunc(value, limit, autoescape=True): """ Convert URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ return mark_safe( _urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape) ) @register.filter(is_safe=False) @stringfilter def wordcount(value): """Return the number of words.""" return len(value.split()) @register.filter(is_safe=True) @stringfilter def wordwrap(value, arg): """Wrap words at `arg` line length.""" return wrap(value, int(arg)) @register.filter(is_safe=True) @stringfilter def ljust(value, arg): """Left-align the value in a field of a given width.""" return value.ljust(int(arg)) @register.filter(is_safe=True) @stringfilter def rjust(value, arg): """Right-align the value in a field of a given width.""" return value.rjust(int(arg)) @register.filter(is_safe=True) @stringfilter def center(value, arg): """Center the value in a field of a given width.""" return value.center(int(arg)) @register.filter @stringfilter def cut(value, arg): """Remove all values of arg from the given string.""" safe = isinstance(value, SafeData) value = value.replace(arg, "") if safe and arg != ";": return mark_safe(value) return value ################### # HTML STRINGS # ################### @register.filter("escape", is_safe=True) @stringfilter def escape_filter(value): """Mark the value as a string that should be auto-escaped.""" return conditional_escape(value) @register.filter(is_safe=True) @stringfilter def force_escape(value): """ Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ return escape(value) @register.filter("linebreaks", is_safe=True, needs_autoescape=True) @stringfilter def linebreaks_filter(value, autoescape=True): """ Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linebreaksbr(value, autoescape=True): """ Convert all newlines in a piece of plain text to HTML line breaks (``<br>``). """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(value) if autoescape: value = escape(value) return mark_safe(value.replace("\n", "<br>")) @register.filter(is_safe=True) @stringfilter def safe(value): """Mark the value as a string that should not be auto-escaped.""" return mark_safe(value) @register.filter(is_safe=True) def safeseq(value): """ A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results. """ return [mark_safe(obj) for obj in value] @register.filter(is_safe=True) @stringfilter def striptags(value): """Strip all [X]HTML tags.""" return strip_tags(value) ################### # LISTS # ################### def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Foo: ... a = 42 ... b = 3.14 ... c = 'Hey!' >>> _property_resolver('b')(Foo()) 3.14 """ try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in arg or arg[0] == "_": raise AttributeError("Access to private variables is forbidden.") parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): for part in parts: try: value = value[part] except (AttributeError, IndexError, KeyError, TypeError, ValueError): value = getattr(value, part) return value return resolve else: return itemgetter(arg) @register.filter(is_safe=False) def dictsort(value, arg): """ Given a list of dicts, return that list sorted by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def dictsortreversed(value, arg): """ Given a list of dicts, return that list sorted in reverse order by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def first(value): """Return the first item in a list.""" try: return value[0] except IndexError: return "" @register.filter(is_safe=True, needs_autoescape=True) def join(value, arg, autoescape=True): """Join a list with a string, like Python's ``str.join(list)``.""" try: if autoescape: value = [conditional_escape(v) for v in value] data = conditional_escape(arg).join(value) except TypeError: # Fail silently if arg isn't iterable. return value return mark_safe(data) @register.filter(is_safe=True) def last(value): """Return the last item in a list.""" try: return value[-1] except IndexError: return "" @register.filter(is_safe=False) def length(value): """Return the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return 0 @register.filter(is_safe=False) def length_is(value, arg): """Return a boolean of whether the value's length is the argument.""" warnings.warn( "The length_is template filter is deprecated in favor of the length template " "filter and the == operator within an {% if %} tag.", RemovedInDjango51Warning, ) try: return len(value) == int(arg) except (ValueError, TypeError): return "" @register.filter(is_safe=True) def random(value): """Return a random item from the list.""" return random_module.choice(value) @register.filter("slice", is_safe=True) def slice_filter(value, arg): """ Return a slice of the list using the same syntax as Python's list slicing. """ try: bits = [] for x in str(arg).split(":"): if not x: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError): return value # Fail silently. @register.filter(is_safe=True, needs_autoescape=True) def unordered_list(value, autoescape=True): """ Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. Assume the list is in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` returns:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ if autoescape: escaper = conditional_escape else: def escaper(x): return x def walk_items(item_list): item_iterator = iter(item_list) try: item = next(item_iterator) while True: try: next_item = next(item_iterator) except StopIteration: yield item, None break if isinstance(next_item, (list, tuple, types.GeneratorType)): try: iter(next_item) except TypeError: pass else: yield item, next_item item = next(item_iterator) continue yield item, None item = next_item except StopIteration: pass def list_formatter(item_list, tabs=1): indent = "\t" * tabs output = [] for item, children in walk_items(item_list): sublist = "" if children: sublist = "\n%s<ul>\n%s\n%s</ul>\n%s" % ( indent, list_formatter(children, tabs + 1), indent, indent, ) output.append("%s<li>%s%s</li>" % (indent, escaper(item), sublist)) return "\n".join(output) return mark_safe(list_formatter(value)) ################### # INTEGERS # ################### @register.filter(is_safe=False) def add(value, arg): """Add the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except Exception: return "" @register.filter(is_safe=False) def get_digit(value, arg): """ Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 ################### # DATES # ################### @register.filter(expects_localtime=True, is_safe=False) def date(value, arg=None): """Format a date according to the given format.""" if value in (None, ""): return "" try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return "" @register.filter(expects_localtime=True, is_safe=False) def time(value, arg=None): """Format a time according to the given format.""" if value in (None, ""): return "" try: return formats.time_format(value, arg) except (AttributeError, TypeError): try: return time_format(value, arg) except (AttributeError, TypeError): return "" @register.filter("timesince", is_safe=False) def timesince_filter(value, arg=None): """Format a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: return "" try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return "" @register.filter("timeuntil", is_safe=False) def timeuntil_filter(value, arg=None): """Format a date as the time until that date (i.e. "4 days, 6 hours").""" if not value: return "" try: return timeuntil(value, arg) except (ValueError, TypeError): return "" ################### # LOGIC # ################### @register.filter(is_safe=False) def default(value, arg): """If value is unavailable, use given default.""" return value or arg @register.filter(is_safe=False) def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value @register.filter(is_safe=False) def divisibleby(value, arg): """Return True if the value is divisible by the argument.""" return int(value) % int(arg) == 0 @register.filter(is_safe=False) def yesno(value, arg=None): """ Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: # Translators: Please do not add spaces around commas. arg = gettext("yes,no,maybe") bits = arg.split(",") if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no ################### # MISC # ################### @register.filter(is_safe=True) def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = int(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {"size": bytes_} elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value) @register.filter(is_safe=False) def pluralize(value, arg="s"): """ Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: * If value is 0, vote{{ value|pluralize }} display "votes". * If value is 1, vote{{ value|pluralize }} display "vote". * If value is 2, vote{{ value|pluralize }} display "votes". If an argument is provided, use that string instead: * If value is 0, class{{ value|pluralize:"es" }} display "classes". * If value is 1, class{{ value|pluralize:"es" }} display "class". * If value is 2, class{{ value|pluralize:"es" }} display "classes". If the provided argument contains a comma, use the text before the comma for the singular case and the text after the comma for the plural case: * If value is 0, cand{{ value|pluralize:"y,ies" }} display "candies". * If value is 1, cand{{ value|pluralize:"y,ies" }} display "candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} display "candies". """ if "," not in arg: arg = "," + arg bits = arg.split(",") if len(bits) > 2: return "" singular_suffix, plural_suffix = bits[:2] try: return singular_suffix if float(value) == 1 else plural_suffix except ValueError: # Invalid string that's not a number. pass except TypeError: # Value isn't a string or a number; maybe it's a list? try: return singular_suffix if len(value) == 1 else plural_suffix except TypeError: # len() of unsized object. pass return "" @register.filter("phone2numeric", is_safe=True) def phone2numeric_filter(value): """Take a phone number and converts it in to its numerical equivalent.""" return phone2numeric(value) @register.filter(is_safe=True) def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" try: return pformat(value) except Exception as e: return "Error in formatting: %s: %s" % (e.__class__.__name__, e)
20caaa1aaea9efcce6231318af62bb7de48c1f1fd9563f2388a7cb9717064ced
""" Helper functions for creating Form classes from Django models and database field objects. """ from itertools import chain from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.db.models.utils import AltersData from django.forms.fields import ChoiceField, Field from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass from django.forms.formsets import BaseFormSet, formset_factory from django.forms.utils import ErrorList from django.forms.widgets import ( HiddenInput, MultipleHiddenInput, RadioSelect, SelectMultiple, ) from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ __all__ = ( "ModelForm", "BaseModelForm", "model_to_dict", "fields_for_model", "ModelChoiceField", "ModelMultipleChoiceField", "ALL_FIELDS", "BaseModelFormSet", "modelformset_factory", "BaseInlineFormSet", "inlineformset_factory", "modelform_factory", ) ALL_FIELDS = "__all__" def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_data file_field_list = [] for f in opts.fields: if ( not f.editable or isinstance(f, models.AutoField) or f.name not in cleaned_data ): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue # Leave defaults for fields that aren't in POST data, except for # checkbox inputs because they don't appear in POST data if not checked. if ( f.has_default() and form[f.name].field.widget.value_omitted_from_data( form.data, form.files, form.add_prefix(f.name) ) and cleaned_data.get(f.name) in form[f.name].field.empty_values ): continue # Defer saving file-type fields until after the other fields, so a # callable upload_to can use the values from other fields. if isinstance(f, models.FileField): file_field_list.append(f) else: f.save_form_data(instance, cleaned_data[f.name]) for f in file_field_list: f.save_form_data(instance, cleaned_data[f.name]) return instance # ModelForms ################################################################# def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, return only the named. ``exclude`` is an optional list of field names. If provided, exclude the named from the returned dict, even if they are listed in the ``fields`` argument. """ opts = instance._meta data = {} for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if not getattr(f, "editable", False): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue data[f.name] = f.value_from_object(instance) return data def apply_limit_choices_to_to_formfield(formfield): """Apply limit_choices_to to the formfield's queryset if needed.""" from django.db.models import Exists, OuterRef, Q if hasattr(formfield, "queryset") and hasattr(formfield, "get_limit_choices_to"): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to: complex_filter = limit_choices_to if not isinstance(complex_filter, Q): complex_filter = Q(**limit_choices_to) complex_filter &= Q(pk=OuterRef("pk")) # Use Exists() to avoid potential duplicates. formfield.queryset = formfield.queryset.filter( Exists(formfield.queryset.model._base_manager.filter(complex_filter)), ) def fields_for_model( model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, *, apply_limit_choices_to=True, ): """ Return a dictionary containing form fields for the given model. ``fields`` is an optional list of field names. If provided, return only the named fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``localized_fields`` is a list of names of fields which should be localized. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to should be applied to a field's queryset. """ field_dict = {} ignored = [] opts = model._meta # Avoid circular import from django.db.models import Field as ModelField sortable_private_fields = [ f for f in opts.private_fields if isinstance(f, ModelField) ] for f in sorted( chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many) ): if not getattr(f, "editable", False): if ( fields is not None and f.name in fields and (exclude is None or f.name not in exclude) ): raise FieldError( "'%s' cannot be specified for %s model form as it is a " "non-editable field" % (f.name, model.__name__) ) continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue kwargs = {} if widgets and f.name in widgets: kwargs["widget"] = widgets[f.name] if localized_fields == ALL_FIELDS or ( localized_fields and f.name in localized_fields ): kwargs["localize"] = True if labels and f.name in labels: kwargs["label"] = labels[f.name] if help_texts and f.name in help_texts: kwargs["help_text"] = help_texts[f.name] if error_messages and f.name in error_messages: kwargs["error_messages"] = error_messages[f.name] if field_classes and f.name in field_classes: kwargs["form_class"] = field_classes[f.name] if formfield_callback is None: formfield = f.formfield(**kwargs) elif not callable(formfield_callback): raise TypeError("formfield_callback must be a function or callable") else: formfield = formfield_callback(f, **kwargs) if formfield: if apply_limit_choices_to: apply_limit_choices_to_to_formfield(formfield) field_dict[f.name] = formfield else: ignored.append(f.name) if fields: field_dict = { f: field_dict.get(f) for f in fields if (not exclude or f not in exclude) and f not in ignored } return field_dict class ModelFormOptions: def __init__(self, options=None): self.model = getattr(options, "model", None) self.fields = getattr(options, "fields", None) self.exclude = getattr(options, "exclude", None) self.widgets = getattr(options, "widgets", None) self.localized_fields = getattr(options, "localized_fields", None) self.labels = getattr(options, "labels", None) self.help_texts = getattr(options, "help_texts", None) self.error_messages = getattr(options, "error_messages", None) self.field_classes = getattr(options, "field_classes", None) self.formfield_callback = getattr(options, "formfield_callback", None) class ModelFormMetaclass(DeclarativeFieldsMetaclass): def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if bases == (BaseModelForm,): return new_class opts = new_class._meta = ModelFormOptions(getattr(new_class, "Meta", None)) # We check if a string was passed to `fields` or `exclude`, # which is likely to be a mistake where the user typed ('foo') instead # of ('foo',) for opt in ["fields", "exclude", "localized_fields"]: value = getattr(opts, opt) if isinstance(value, str) and value != ALL_FIELDS: msg = ( "%(model)s.Meta.%(opt)s cannot be a string. " "Did you mean to type: ('%(value)s',)?" % { "model": new_class.__name__, "opt": opt, "value": value, } ) raise TypeError(msg) if opts.model: # If a model is defined, extract form fields from it. if opts.fields is None and opts.exclude is None: raise ImproperlyConfigured( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form %s " "needs updating." % name ) if opts.fields == ALL_FIELDS: # Sentinel for fields_for_model to indicate "get the list of # fields from the model" opts.fields = None fields = fields_for_model( opts.model, opts.fields, opts.exclude, opts.widgets, opts.formfield_callback, opts.localized_fields, opts.labels, opts.help_texts, opts.error_messages, opts.field_classes, # limit_choices_to will be applied during ModelForm.__init__(). apply_limit_choices_to=False, ) # make sure opts.fields doesn't specify an invalid field none_model_fields = {k for k, v in fields.items() if not v} missing_fields = none_model_fields.difference(new_class.declared_fields) if missing_fields: message = "Unknown field(s) (%s) specified for %s" message %= (", ".join(missing_fields), opts.model.__name__) raise FieldError(message) # Override default model fields with any custom declared ones # (plus, include all the other declared fields). fields.update(new_class.declared_fields) else: fields = new_class.declared_fields new_class.base_fields = fields return new_class class BaseModelForm(BaseForm, AltersData): def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None, ): opts = self._meta if opts.model is None: raise ValueError("ModelForm has no model class specified.") if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_unique will be set to True by BaseModelForm.clean(). # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False super().__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, renderer=renderer, ) for formfield in self.fields.values(): apply_limit_choices_to_to_formfield(formfield) def _get_validation_exclusions(self): """ For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553. """ exclude = set() # Build up a list of fields that should be excluded from model field # validation and unique checks. for f in self.instance._meta.fields: field = f.name # Exclude fields that aren't on the form. The developer may be # adding these values to the model after form validation. if field not in self.fields: exclude.add(f.name) # Don't perform model validation on fields that were defined # manually on the form and excluded via the ModelForm's Meta # class. See #12901. elif self._meta.fields and field not in self._meta.fields: exclude.add(f.name) elif self._meta.exclude and field in self._meta.exclude: exclude.add(f.name) # Exclude fields that failed form validation. There's no need for # the model fields to validate them as well. elif field in self._errors: exclude.add(f.name) # Exclude empty fields that are not required by the form, if the # underlying model field is required. This keeps the model field # from raising a required error. Note: don't exclude the field from # validation if the model field allows blanks. If it does, the blank # value may be included in a unique check, so cannot be excluded # from validation. else: form_field = self.fields[field] field_value = self.cleaned_data.get(field) if ( not f.blank and not form_field.required and field_value in form_field.empty_values ): exclude.add(f.name) return exclude def clean(self): self._validate_unique = True return self.cleaned_data def _update_errors(self, errors): # Override any validation error messages defined at the model level # with those defined at the form level. opts = self._meta # Allow the model generated by construct_instance() to raise # ValidationError and have them handled in the same way as others. if hasattr(errors, "error_dict"): error_dict = errors.error_dict else: error_dict = {NON_FIELD_ERRORS: errors} for field, messages in error_dict.items(): if ( field == NON_FIELD_ERRORS and opts.error_messages and NON_FIELD_ERRORS in opts.error_messages ): error_messages = opts.error_messages[NON_FIELD_ERRORS] elif field in self.fields: error_messages = self.fields[field].error_messages else: continue for message in messages: if ( isinstance(message, ValidationError) and message.code in error_messages ): message.message = error_messages[message.code] self.add_error(None, errors) def _post_clean(self): opts = self._meta exclude = self._get_validation_exclusions() # Foreign Keys being used to represent inline relationships # are excluded from basic field value validation. This is for two # reasons: firstly, the value may not be supplied (#12507; the # case of providing new values to the admin); secondly the # object being referred to may not yet fully exist (#12749). # However, these fields *must* be included in uniqueness checks, # so this can't be part of _get_validation_exclusions(). for name, field in self.fields.items(): if isinstance(field, InlineForeignKeyField): exclude.add(name) try: self.instance = construct_instance( self, self.instance, opts.fields, opts.exclude ) except ValidationError as e: self._update_errors(e) try: self.instance.full_clean(exclude=exclude, validate_unique=False) except ValidationError as e: self._update_errors(e) # Validate uniqueness if needed. if self._validate_unique: self.validate_unique() def validate_unique(self): """ Call the instance's validate_unique() method and update the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) except ValidationError as e: self._update_errors(e) def _save_m2m(self): """ Save the many-to-many fields and generic relations for this form. """ cleaned_data = self.cleaned_data exclude = self._meta.exclude fields = self._meta.fields opts = self.instance._meta # Note that for historical reasons we want to include also # private_fields here. (GenericRelation was previously a fake # m2m field). for f in chain(opts.many_to_many, opts.private_fields): if not hasattr(f, "save_form_data"): continue if fields and f.name not in fields: continue if exclude and f.name in exclude: continue if f.name in cleaned_data: f.save_form_data(self.instance, cleaned_data[f.name]) def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, "created" if self.instance._state.adding else "changed", ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save() self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance save.alters_data = True class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass): pass def modelform_factory( model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, ): """ Return a ModelForm containing form fields for the given model. You can optionally pass a `form` argument to use as a starting point for constructing the ModelForm. ``fields`` is an optional list of field names. If provided, include only the named fields in the returned fields. If omitted or '__all__', use all fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``localized_fields`` is a list of names of fields which should be localized. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. """ # Create the inner Meta class. FIXME: ideally, we should be able to # construct a ModelForm without creating and passing in a temporary # inner class. # Build up a list of attributes that the Meta object will have. attrs = {"model": model} if fields is not None: attrs["fields"] = fields if exclude is not None: attrs["exclude"] = exclude if widgets is not None: attrs["widgets"] = widgets if localized_fields is not None: attrs["localized_fields"] = localized_fields if labels is not None: attrs["labels"] = labels if help_texts is not None: attrs["help_texts"] = help_texts if error_messages is not None: attrs["error_messages"] = error_messages if field_classes is not None: attrs["field_classes"] = field_classes # If parent form class already has an inner Meta, the Meta we're # creating needs to inherit from the parent's inner meta. bases = (form.Meta,) if hasattr(form, "Meta") else () Meta = type("Meta", bases, attrs) if formfield_callback: Meta.formfield_callback = staticmethod(formfield_callback) # Give this new form class a reasonable name. class_name = model.__name__ + "Form" # Class attributes for the new form class. form_class_attrs = {"Meta": Meta} if getattr(Meta, "fields", None) is None and getattr(Meta, "exclude", None) is None: raise ImproperlyConfigured( "Calling modelform_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) # Instantiate type(form) in order to use the same metaclass as form. return type(form)(class_name, (form,), form_class_attrs) # ModelFormSets ############################################################## class BaseModelFormSet(BaseFormSet, AltersData): """ A ``FormSet`` for editing a queryset and/or adding new objects to it. """ model = None edit_only = False # Set of fields that must be unique among forms of this set. unique_fields = set() def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, queryset=None, *, initial=None, **kwargs, ): self.queryset = queryset self.initial_extra = initial super().__init__( **{ "data": data, "files": files, "auto_id": auto_id, "prefix": prefix, **kwargs, } ) def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count() def _existing_object(self, pk): if not hasattr(self, "_object_dict"): self._object_dict = {o.pk: o for o in self.get_queryset()} return self._object_dict.get(pk) def _get_to_python(self, field): """ If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python. """ while field.remote_field is not None: field = field.remote_field.get_related_field() return field.to_python def _construct_form(self, i, **kwargs): pk_required = i < self.initial_form_count() if pk_required: if self.is_bound: pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name) try: pk = self.data[pk_key] except KeyError: # The primary key is missing. The user may have tampered # with POST data. pass else: to_python = self._get_to_python(self.model._meta.pk) try: pk = to_python(pk) except ValidationError: # The primary key exists but is an invalid value. The # user may have tampered with POST data. pass else: kwargs["instance"] = self._existing_object(pk) else: kwargs["instance"] = self.get_queryset()[i] elif self.initial_extra: # Set initial values for extra forms try: kwargs["initial"] = self.initial_extra[i - self.initial_form_count()] except IndexError: pass form = super()._construct_form(i, **kwargs) if pk_required: form.fields[self.model._meta.pk.name].required = True return form def get_queryset(self): if not hasattr(self, "_queryset"): if self.queryset is not None: qs = self.queryset else: qs = self.model._default_manager.get_queryset() # If the queryset isn't already ordered we need to add an # artificial ordering here to make sure that all formsets # constructed from this queryset have the same form order. if not qs.ordered: qs = qs.order_by(self.model._meta.pk.name) # Removed queryset limiting here. As per discussion re: #13023 # on django-dev, max_num should not prevent existing # related objects/inlines from being displayed. self._queryset = qs return self._queryset def save_new(self, form, commit=True): """Save and return a new model instance for the given form.""" return form.save(commit=commit) def save_existing(self, form, obj, commit=True): """Save and return an existing model instance for the given form.""" return form.save(commit=commit) def delete_existing(self, obj, commit=True): """Deletes an existing model instance.""" if commit: obj.delete() def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: form.save_m2m() self.save_m2m = save_m2m if self.edit_only: return self.save_existing_objects(commit) else: return self.save_existing_objects(commit) + self.save_new_objects(commit) save.alters_data = True def clean(self): self.validate_unique() def validate_unique(self): # Collect unique_checks and date_checks to run from all the forms. all_unique_checks = set() all_date_checks = set() forms_to_delete = self.deleted_forms valid_forms = [ form for form in self.forms if form.is_valid() and form not in forms_to_delete ] for form in valid_forms: exclude = form._get_validation_exclusions() unique_checks, date_checks = form.instance._get_unique_checks( exclude=exclude, include_meta_constraints=True, ) all_unique_checks.update(unique_checks) all_date_checks.update(date_checks) errors = [] # Do each of the unique checks (unique and unique_together) for uclass, unique_check in all_unique_checks: seen_data = set() for form in valid_forms: # Get the data for the set of fields that must be unique among # the forms. row_data = ( field if field in self.unique_fields else form.cleaned_data[field] for field in unique_check if field in form.cleaned_data ) # Reduce Model instances to their primary key values row_data = tuple( d._get_pk_val() if hasattr(d, "_get_pk_val") # Prevent "unhashable type: list" errors later on. else tuple(d) if isinstance(d, list) else d for d in row_data ) if row_data and None not in row_data: # if we've already seen it then we have a uniqueness failure if row_data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_unique_error_message(unique_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. for field in unique_check: if field in form.cleaned_data: del form.cleaned_data[field] # mark the data as seen seen_data.add(row_data) # iterate over each of the date checks now for date_check in all_date_checks: seen_data = set() uclass, lookup, field, unique_for = date_check for form in valid_forms: # see if we have data for both fields if ( form.cleaned_data and form.cleaned_data[field] is not None and form.cleaned_data[unique_for] is not None ): # if it's a date lookup we need to get the data for all the fields if lookup == "date": date = form.cleaned_data[unique_for] date_data = (date.year, date.month, date.day) # otherwise it's just the attribute on the date/datetime # object else: date_data = (getattr(form.cleaned_data[unique_for], lookup),) data = (form.cleaned_data[field],) + date_data # if we've already seen it then we have a uniqueness failure if data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_date_error_message(date_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. del form.cleaned_data[field] # mark the data as seen seen_data.add(data) if errors: raise ValidationError(errors) def get_unique_error_message(self, unique_check): if len(unique_check) == 1: return gettext("Please correct the duplicate data for %(field)s.") % { "field": unique_check[0], } else: return gettext( "Please correct the duplicate data for %(field)s, which must be unique." ) % { "field": get_text_list(unique_check, _("and")), } def get_date_error_message(self, date_check): return gettext( "Please correct the duplicate data for %(field_name)s " "which must be unique for the %(lookup)s in %(date_field)s." ) % { "field_name": date_check[2], "date_field": date_check[3], "lookup": str(date_check[1]), } def get_form_error(self): return gettext("Please correct the duplicate values below.") def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.initial_forms: return [] saved_instances = [] forms_to_delete = self.deleted_forms for form in self.initial_forms: obj = form.instance # If the pk is None, it means either: # 1. The object is an unexpected empty model, created by invalid # POST data such as an object outside the formset's queryset. # 2. The object was already deleted from the database. if obj.pk is None: continue if form in forms_to_delete: self.deleted_objects.append(obj) self.delete_existing(obj, commit=commit) elif form.has_changed(): self.changed_objects.append((obj, form.changed_data)) saved_instances.append(self.save_existing(form, obj, commit=commit)) if not commit: self.saved_forms.append(form) return saved_instances def save_new_objects(self, commit=True): self.new_objects = [] for form in self.extra_forms: if not form.has_changed(): continue # If someone has marked an add form for deletion, don't save the # object. if self.can_delete and self._should_delete_form(form): continue self.new_objects.append(self.save_new(form, commit=commit)) if not commit: self.saved_forms.append(form) return self.new_objects def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, ForeignKey, OneToOneField self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ( (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or ( pk.remote_field and pk.remote_field.parent_link and pk_is_not_editable(pk.remote_field.model._meta.pk) ) ) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key # as it could be an auto-generated default which isn't actually # in the database. pk_value = None if form.instance._state.adding else form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, (ForeignKey, OneToOneField)): qs = pk.remote_field.model._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField( qs, initial=pk_value, required=False, widget=widget ) super().add_fields(form, index) def modelformset_factory( model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False, ): """Return a FormSet class for the given Django model class.""" meta = getattr(form, "Meta", None) if ( getattr(meta, "fields", fields) is None and getattr(meta, "exclude", exclude) is None ): raise ImproperlyConfigured( "Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) form = modelform_factory( model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages, field_classes=field_classes, ) FormSet = formset_factory( form, formset, extra=extra, min_num=min_num, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_min=validate_min, validate_max=validate_max, absolute_max=absolute_max, can_delete_extra=can_delete_extra, renderer=renderer, ) FormSet.model = model FormSet.edit_only = edit_only return FormSet # InlineFormSets ############################################################# class BaseInlineFormSet(BaseModelFormSet): """A formset for child objects related to a parent.""" def __init__( self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None, **kwargs, ): if instance is None: self.instance = self.fk.remote_field.model() else: self.instance = instance self.save_as_new = save_as_new if queryset is None: queryset = self.model._default_manager if self.instance.pk is not None: qs = queryset.filter(**{self.fk.name: self.instance}) else: qs = queryset.none() self.unique_fields = {self.fk.name} super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs) # Add the generated field to form._meta.fields if it's defined to make # sure validation isn't skipped on that field. if self.form._meta.fields and self.fk.name not in self.form._meta.fields: if isinstance(self.form._meta.fields, tuple): self.form._meta.fields = list(self.form._meta.fields) self.form._meta.fields.append(self.fk.name) def initial_form_count(self): if self.save_as_new: return 0 return super().initial_form_count() def _construct_form(self, i, **kwargs): form = super()._construct_form(i, **kwargs) if self.save_as_new: mutable = getattr(form.data, "_mutable", None) # Allow modifying an immutable QueryDict. if mutable is not None: form.data._mutable = True # Remove the primary key from the form's data, we are only # creating new instances form.data[form.add_prefix(self._pk_field.name)] = None # Remove the foreign key from the form's data form.data[form.add_prefix(self.fk.name)] = None if mutable is not None: form.data._mutable = mutable # Set the fk value here so that the form can do its validation. fk_value = self.instance.pk if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: fk_value = getattr(self.instance, self.fk.remote_field.field_name) fk_value = getattr(fk_value, "pk", fk_value) setattr(form.instance, self.fk.get_attname(), fk_value) return form @classmethod def get_default_prefix(cls): return cls.fk.remote_field.get_accessor_name(model=cls.model).replace("+", "") def save_new(self, form, commit=True): # Ensure the latest copy of the related instance is present on each # form (it may have been saved after the formset was originally # instantiated). setattr(form.instance, self.fk.name, self.instance) return super().save_new(form, commit=commit) def add_fields(self, form, index): super().add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {"pk_field": True} else: # The foreign key field might not be on the form, so we poke at the # Model field to get the label, since we need that for error messages. name = self.fk.name kwargs = { "label": getattr( form.fields.get(name), "label", capfirst(self.fk.verbose_name) ) } # The InlineForeignKeyField assumes that the foreign key relation is # based on the parent model's pk. If this isn't the case, set to_field # to correctly resolve the initial form value. if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: kwargs["to_field"] = self.fk.remote_field.field_name # If we're adding a new object, ignore a parent's auto-generated key # as it will be regenerated on the save request. if self.instance._state.adding: if kwargs.get("to_field") is not None: to_field = self.instance._meta.get_field(kwargs["to_field"]) else: to_field = self.instance._meta.pk if to_field.has_default(): setattr(self.instance, to_field.attname, None) form.fields[name] = InlineForeignKeyField(self.instance, **kwargs) def get_unique_error_message(self, unique_check): unique_check = [field for field in unique_check if field != self.fk.name] return super().get_unique_error_message(unique_check) def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): """ Find and return the ForeignKey from model to parent if there is one (return None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, raise an exception if there isn't a ForeignKey from model to parent_model. """ # avoid circular import from django.db.models import ForeignKey opts = model._meta if fk_name: fks_to_parent = [f for f in opts.fields if f.name == fk_name] if len(fks_to_parent) == 1: fk = fks_to_parent[0] parent_list = parent_model._meta.get_parent_list() if ( not isinstance(fk, ForeignKey) or ( # ForeignKey to proxy models. fk.remote_field.model._meta.proxy and fk.remote_field.model._meta.proxy_for_model not in parent_list ) or ( # ForeignKey to concrete models. not fk.remote_field.model._meta.proxy and fk.remote_field.model != parent_model and fk.remote_field.model not in parent_list ) ): raise ValueError( "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label) ) elif not fks_to_parent: raise ValueError( "'%s' has no field named '%s'." % (model._meta.label, fk_name) ) else: # Try to discover what the ForeignKey from model to parent_model is parent_list = parent_model._meta.get_parent_list() fks_to_parent = [ f for f in opts.fields if isinstance(f, ForeignKey) and ( f.remote_field.model == parent_model or f.remote_field.model in parent_list or ( f.remote_field.model._meta.proxy and f.remote_field.model._meta.proxy_for_model in parent_list ) ) ] if len(fks_to_parent) == 1: fk = fks_to_parent[0] elif not fks_to_parent: if can_fail: return raise ValueError( "'%s' has no ForeignKey to '%s'." % ( model._meta.label, parent_model._meta.label, ) ) else: raise ValueError( "'%s' has more than one ForeignKey to '%s'. You must specify " "a 'fk_name' attribute." % ( model._meta.label, parent_model._meta.label, ) ) return fk def inlineformset_factory( parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False, ): """ Return an ``InlineFormSet`` for the given kwargs. ``fk_name`` must be provided if ``model`` has more than one ``ForeignKey`` to ``parent_model``. """ fk = _get_foreign_key(parent_model, model, fk_name=fk_name) # enforce a max_num=1 when the foreign key to the parent model is unique. if fk.unique: max_num = 1 kwargs = { "form": form, "formfield_callback": formfield_callback, "formset": formset, "extra": extra, "can_delete": can_delete, "can_order": can_order, "fields": fields, "exclude": exclude, "min_num": min_num, "max_num": max_num, "widgets": widgets, "validate_min": validate_min, "validate_max": validate_max, "localized_fields": localized_fields, "labels": labels, "help_texts": help_texts, "error_messages": error_messages, "field_classes": field_classes, "absolute_max": absolute_max, "can_delete_extra": can_delete_extra, "renderer": renderer, "edit_only": edit_only, } FormSet = modelformset_factory(model, **kwargs) FormSet.fk = fk return FormSet # Fields ##################################################################### class InlineForeignKeyField(Field): """ A basic integer field that deals with validating the given value to a given parent instance in an inline. """ widget = HiddenInput default_error_messages = { "invalid_choice": _("The inline value did not match the parent instance."), } def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs): self.parent_instance = parent_instance self.pk_field = pk_field self.to_field = to_field if self.parent_instance is not None: if self.to_field: kwargs["initial"] = getattr(self.parent_instance, self.to_field) else: kwargs["initial"] = self.parent_instance.pk kwargs["required"] = False super().__init__(*args, **kwargs) def clean(self, value): if value in self.empty_values: if self.pk_field: return None # if there is no value act as we did before. return self.parent_instance # ensure the we compare the values as equal types. if self.to_field: orig = getattr(self.parent_instance, self.to_field) else: orig = self.parent_instance.pk if str(value) != str(orig): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice" ) return self.parent_instance def has_changed(self, initial, data): return False class ModelChoiceIteratorValue: def __init__(self, value, instance): self.value = value self.instance = instance def __str__(self): return str(self.value) def __hash__(self): return hash(self.value) def __eq__(self, other): if isinstance(other, ModelChoiceIteratorValue): other = other.value return self.value == other class ModelChoiceIterator: def __init__(self, field): self.field = field self.queryset = field.queryset def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) queryset = self.queryset # Can't use iterator() when queryset uses prefetch_related() if not queryset._prefetch_related_lookups: queryset = queryset.iterator() for obj in queryset: yield self.choice(obj) def __len__(self): # count() adds a query but uses less memory since the QuerySet results # won't be cached. In most cases, the choices will only be iterated on, # and __len__() won't be called. return self.queryset.count() + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or self.queryset.exists() def choice(self, obj): return ( ModelChoiceIteratorValue(self.field.prepare_value(obj), obj), self.field.label_from_instance(obj), ) class ModelChoiceField(ChoiceField): """A ChoiceField whose choices are a model QuerySet.""" # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. default_error_messages = { "invalid_choice": _( "Select a valid choice. That choice is not one of the available choices." ), } iterator = ModelChoiceIterator def __init__( self, queryset, *, empty_label="---------", required=True, widget=None, label=None, initial=None, help_text="", to_field_name=None, limit_choices_to=None, blank=False, **kwargs, ): # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__( self, required=required, widget=widget, label=label, initial=initial, help_text=help_text, **kwargs, ) if (required and initial is not None) or ( isinstance(self.widget, RadioSelect) and not blank ): self.empty_label = None else: self.empty_label = empty_label self.queryset = queryset self.limit_choices_to = limit_choices_to # limit the queryset later. self.to_field_name = to_field_name def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this form field. If it is a callable, invoke it and return the result. """ if callable(self.limit_choices_to): return self.limit_choices_to() return self.limit_choices_to def __deepcopy__(self, memo): result = super(ChoiceField, self).__deepcopy__(memo) # Need to force a new ModelChoiceIterator to be created, bug #11183 if self.queryset is not None: result.queryset = self.queryset.all() return result def _get_queryset(self): return self._queryset def _set_queryset(self, queryset): self._queryset = None if queryset is None else queryset.all() self.widget.choices = self.choices queryset = property(_get_queryset, _set_queryset) # this method will be used to create object labels by the QuerySetIterator. # Override it to customize the label. def label_from_instance(self, obj): """ Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ return str(obj) def _get_choices(self): # If self._choices is set, then somebody must have manually set # the property self.choices. In this case, just return self._choices. if hasattr(self, "_choices"): return self._choices # Otherwise, execute the QuerySet in self.queryset to determine the # choices dynamically. Return a fresh ModelChoiceIterator that has not been # consumed. Note that we're instantiating a new ModelChoiceIterator *each* # time _get_choices() is called (and, thus, each time self.choices is # accessed) so that we can ensure the QuerySet has not been consumed. This # construct might look complicated but it allows for lazy evaluation of # the queryset. return self.iterator(self) choices = property(_get_choices, ChoiceField._set_choices) def prepare_value(self, value): if hasattr(value, "_meta"): if self.to_field_name: return value.serializable_value(self.to_field_name) else: return value.pk return super().prepare_value(value) def to_python(self, value): if value in self.empty_values: return None try: key = self.to_field_name or "pk" if isinstance(value, self.queryset.model): value = getattr(value, key) value = self.queryset.get(**{key: value}) except (ValueError, TypeError, self.queryset.model.DoesNotExist): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) return value def validate(self, value): return Field.validate(self, value) def has_changed(self, initial, data): if self.disabled: return False initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return str(self.prepare_value(initial_value)) != str(data_value) class ModelMultipleChoiceField(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { "invalid_list": _("Enter a list of values."), "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_pk_value": _("“%(pk)s” is not a valid value."), } def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label=None, **kwargs) def to_python(self, value): if not value: return [] return list(self._check_values(value)) def clean(self, value): value = self.prepare_value(value) if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") elif not self.required and not value: return self.queryset.none() if not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) qs = self._check_values(value) # Since this overrides the inherited ModelChoiceField.clean # we run custom validators here self.run_validators(value) return qs def _check_values(self, value): """ Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.) """ key = self.to_field_name or "pk" # deduplicate given values to avoid creating many querysets or # requiring the database backend deduplicate efficiently. try: value = frozenset(value) except TypeError: # list of lists isn't hashable, for example raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) for pk in value: try: self.queryset.filter(**{key: pk}) except (ValueError, TypeError): raise ValidationError( self.error_messages["invalid_pk_value"], code="invalid_pk_value", params={"pk": pk}, ) qs = self.queryset.filter(**{"%s__in" % key: value}) pks = {str(getattr(o, key)) for o in qs} for val in value: if str(val) not in pks: raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) return qs def prepare_value(self, value): if ( hasattr(value, "__iter__") and not isinstance(value, str) and not hasattr(value, "_meta") ): prepare_value = super().prepare_value return [prepare_value(v) for v in value] return super().prepare_value(value) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in self.prepare_value(initial)} data_set = {str(value) for value in data} return data_set != initial_set def modelform_defines_fields(form_class): return hasattr(form_class, "_meta") and ( form_class._meta.fields is not None or form_class._meta.exclude is not None )
ccce24b9c5fa0db15b986a6897645220cba5af0a7311d0f8249d222102d64925
from django.core.exceptions import ValidationError from django.forms import Form from django.forms.fields import BooleanField, IntegerField from django.forms.renderers import get_default_renderer from django.forms.utils import ErrorList, RenderableFormMixin from django.forms.widgets import CheckboxInput, HiddenInput, NumberInput from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy __all__ = ("BaseFormSet", "formset_factory", "all_valid") # special field names TOTAL_FORM_COUNT = "TOTAL_FORMS" INITIAL_FORM_COUNT = "INITIAL_FORMS" MIN_NUM_FORM_COUNT = "MIN_NUM_FORMS" MAX_NUM_FORM_COUNT = "MAX_NUM_FORMS" ORDERING_FIELD_NAME = "ORDER" DELETION_FIELD_NAME = "DELETE" # default minimum number of forms in a formset DEFAULT_MIN_NUM = 0 # default maximum number of forms in a formset, to prevent memory exhaustion DEFAULT_MAX_NUM = 1000 class ManagementForm(Form): """ Keep track of how many form instances are displayed on the page. If adding new forms via JavaScript, you should increment the count field of this form as well. """ TOTAL_FORMS = IntegerField(widget=HiddenInput) INITIAL_FORMS = IntegerField(widget=HiddenInput) # MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are output with the rest of the # management form, but only for the convenience of client-side code. The # POST value of them returned from the client is not checked. MIN_NUM_FORMS = IntegerField(required=False, widget=HiddenInput) MAX_NUM_FORMS = IntegerField(required=False, widget=HiddenInput) def clean(self): cleaned_data = super().clean() # When the management form is invalid, we don't know how many forms # were submitted. cleaned_data.setdefault(TOTAL_FORM_COUNT, 0) cleaned_data.setdefault(INITIAL_FORM_COUNT, 0) return cleaned_data class BaseFormSet(RenderableFormMixin): """ A collection of instances of the same Form class. """ deletion_widget = CheckboxInput ordering_widget = NumberInput default_error_messages = { "missing_management_form": _( "ManagementForm data is missing or has been tampered with. Missing fields: " "%(field_names)s. You may need to file a bug report if the issue persists." ), "too_many_forms": ngettext_lazy( "Please submit at most %(num)d form.", "Please submit at most %(num)d forms.", "num", ), "too_few_forms": ngettext_lazy( "Please submit at least %(num)d form.", "Please submit at least %(num)d forms.", "num", ), } template_name_div = "django/forms/formsets/div.html" template_name_p = "django/forms/formsets/p.html" template_name_table = "django/forms/formsets/table.html" template_name_ul = "django/forms/formsets/ul.html" def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, form_kwargs=None, error_messages=None, ): self.is_bound = data is not None or files is not None self.prefix = prefix or self.get_default_prefix() self.auto_id = auto_id self.data = data or {} self.files = files or {} self.initial = initial self.form_kwargs = form_kwargs or {} self.error_class = error_class self._errors = None self._non_form_errors = None messages = {} for cls in reversed(type(self).__mro__): messages.update(getattr(cls, "default_error_messages", {})) if error_messages is not None: messages.update(error_messages) self.error_messages = messages def __iter__(self): """Yield the forms in the order they should be rendered.""" return iter(self.forms) def __getitem__(self, index): """Return the form at the given index, based on the rendering order.""" return self.forms[index] def __len__(self): return len(self.forms) def __bool__(self): """ Return True since all formsets have a management form which is not included in the length. """ return True def __repr__(self): if self._errors is None: is_valid = "Unknown" else: is_valid = ( self.is_bound and not self._non_form_errors and not any(form_errors for form_errors in self._errors) ) return "<%s: bound=%s valid=%s total_forms=%s>" % ( self.__class__.__qualname__, self.is_bound, is_valid, self.total_form_count(), ) @cached_property def management_form(self): """Return the ManagementForm instance for this FormSet.""" if self.is_bound: form = ManagementForm( self.data, auto_id=self.auto_id, prefix=self.prefix, renderer=self.renderer, ) form.full_clean() else: form = ManagementForm( auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num, }, renderer=self.renderer, ) return form def total_form_count(self): """Return the total number of forms in this FormSet.""" if self.is_bound: # return absolute_max if it is lower than the actual total form # count in the data; this is DoS protection to prevent clients # from forcing the server to instantiate arbitrary numbers of # forms return min( self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max ) else: initial_forms = self.initial_form_count() total_forms = max(initial_forms, self.min_num) + self.extra # Allow all existing related objects/inlines to be displayed, # but don't allow extra beyond max_num. if initial_forms > self.max_num >= 0: total_forms = initial_forms elif total_forms > self.max_num >= 0: total_forms = self.max_num return total_forms def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if self.is_bound: return self.management_form.cleaned_data[INITIAL_FORM_COUNT] else: # Use the length of the initial data if it's there, 0 otherwise. initial_forms = len(self.initial) if self.initial else 0 return initial_forms @cached_property def forms(self): """Instantiate forms at first property access.""" # DoS protection is included in total_form_count() return [ self._construct_form(i, **self.get_form_kwargs(i)) for i in range(self.total_form_count()) ] def get_form_kwargs(self, index): """ Return additional keyword arguments for each individual formset form. index will be None if the form being constructed is a new empty form. """ return self.form_kwargs.copy() def _construct_form(self, i, **kwargs): """Instantiate and return the i-th form instance in a formset.""" defaults = { "auto_id": self.auto_id, "prefix": self.add_prefix(i), "error_class": self.error_class, # Don't render the HTML 'required' attribute as it may cause # incorrect validation for extra, optional, and deleted # forms in the formset. "use_required_attribute": False, "renderer": self.renderer, } if self.is_bound: defaults["data"] = self.data defaults["files"] = self.files if self.initial and "initial" not in kwargs: try: defaults["initial"] = self.initial[i] except IndexError: pass # Allow extra forms to be empty, unless they're part of # the minimum forms. if i >= self.initial_form_count() and i >= self.min_num: defaults["empty_permitted"] = True defaults.update(kwargs) form = self.form(**defaults) self.add_fields(form, i) return form @property def initial_forms(self): """Return a list of all the initial forms in this formset.""" return self.forms[: self.initial_form_count()] @property def extra_forms(self): """Return a list of all the extra forms in this formset.""" return self.forms[self.initial_form_count() :] @property def empty_form(self): form_kwargs = { **self.get_form_kwargs(None), "auto_id": self.auto_id, "prefix": self.add_prefix("__prefix__"), "empty_permitted": True, "use_required_attribute": False, "renderer": self.renderer, } form = self.form(**form_kwargs) self.add_fields(form, None) return form @property def cleaned_data(self): """ Return a list of form.cleaned_data dicts for every form in self.forms. """ if not self.is_valid(): raise AttributeError( "'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__ ) return [form.cleaned_data for form in self.forms] @property def deleted_forms(self): """Return a list of forms that have been marked for deletion.""" if not self.is_valid() or not self.can_delete: return [] # construct _deleted_form_indexes which is just a list of form indexes # that have had their deletion widget set to True if not hasattr(self, "_deleted_form_indexes"): self._deleted_form_indexes = [] for i, form in enumerate(self.forms): # if this is an extra form and hasn't changed, don't consider it if i >= self.initial_form_count() and not form.has_changed(): continue if self._should_delete_form(form): self._deleted_form_indexes.append(i) return [self.forms[i] for i in self._deleted_form_indexes] @property def ordered_forms(self): """ Return a list of form in the order specified by the incoming data. Raise an AttributeError if ordering is not allowed. """ if not self.is_valid() or not self.can_order: raise AttributeError( "'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__ ) # Construct _ordering, which is a list of (form_index, order_field_value) # tuples. After constructing this list, we'll sort it by order_field_value # so we have a way to get to the form indexes in the order specified # by the form data. if not hasattr(self, "_ordering"): self._ordering = [] for i, form in enumerate(self.forms): # if this is an extra form and hasn't changed, don't consider it if i >= self.initial_form_count() and not form.has_changed(): continue # don't add data marked for deletion to self.ordered_data if self.can_delete and self._should_delete_form(form): continue self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME])) # After we're done populating self._ordering, sort it. # A sort function to order things numerically ascending, but # None should be sorted below anything else. Allowing None as # a comparison value makes it so we can leave ordering fields # blank. def compare_ordering_key(k): if k[1] is None: return (1, 0) # +infinity, larger than any number return (0, k[1]) self._ordering.sort(key=compare_ordering_key) # Return a list of form.cleaned_data dicts in the order specified by # the form data. return [self.forms[i[0]] for i in self._ordering] @classmethod def get_default_prefix(cls): return "form" @classmethod def get_deletion_widget(cls): return cls.deletion_widget @classmethod def get_ordering_widget(cls): return cls.ordering_widget def non_form_errors(self): """ Return an ErrorList of errors that aren't associated with a particular form -- i.e., from formset.clean(). Return an empty ErrorList if there are none. """ if self._non_form_errors is None: self.full_clean() return self._non_form_errors @property def errors(self): """Return a list of form.errors for every form in self.forms.""" if self._errors is None: self.full_clean() return self._errors def total_error_count(self): """Return the number of errors across all forms in the formset.""" return len(self.non_form_errors()) + sum( len(form_errors) for form_errors in self.errors ) def _should_delete_form(self, form): """Return whether or not the form was marked for deletion.""" return form.cleaned_data.get(DELETION_FIELD_NAME, False) def is_valid(self): """Return True if every form in self.forms is valid.""" if not self.is_bound: return False # Accessing errors triggers a full clean the first time only. self.errors # List comprehension ensures is_valid() is called for all forms. # Forms due to be deleted shouldn't cause the formset to be invalid. forms_valid = all( [ form.is_valid() for form in self.forms if not (self.can_delete and self._should_delete_form(form)) ] ) return forms_valid and not self.non_form_errors() def full_clean(self): """ Clean all of self.data and populate self._errors and self._non_form_errors. """ self._errors = [] self._non_form_errors = self.error_class( error_class="nonform", renderer=self.renderer ) empty_forms_count = 0 if not self.is_bound: # Stop further processing. return if not self.management_form.is_valid(): error = ValidationError( self.error_messages["missing_management_form"], params={ "field_names": ", ".join( self.management_form.add_prefix(field_name) for field_name in self.management_form.errors ), }, code="missing_management_form", ) self._non_form_errors.append(error) for i, form in enumerate(self.forms): # Empty forms are unchanged forms beyond those with initial data. if not form.has_changed() and i >= self.initial_form_count(): empty_forms_count += 1 # Accessing errors calls full_clean() if necessary. # _should_delete_form() requires cleaned_data. form_errors = form.errors if self.can_delete and self._should_delete_form(form): continue self._errors.append(form_errors) try: if ( self.validate_max and self.total_form_count() - len(self.deleted_forms) > self.max_num ) or self.management_form.cleaned_data[ TOTAL_FORM_COUNT ] > self.absolute_max: raise ValidationError( self.error_messages["too_many_forms"] % {"num": self.max_num}, code="too_many_forms", ) if ( self.validate_min and self.total_form_count() - len(self.deleted_forms) - empty_forms_count < self.min_num ): raise ValidationError( self.error_messages["too_few_forms"] % {"num": self.min_num}, code="too_few_forms", ) # Give self.clean() a chance to do cross-form validation. self.clean() except ValidationError as e: self._non_form_errors = self.error_class( e.error_list, error_class="nonform", renderer=self.renderer, ) def clean(self): """ Hook for doing any extra formset-wide cleaning after Form.clean() has been called on every form. Any ValidationError raised by this method will not be associated with a particular form; it will be accessible via formset.non_form_errors() """ pass def has_changed(self): """Return True if data in any form differs from initial.""" return any(form.has_changed() for form in self) def add_fields(self, form, index): """A hook for adding extra fields on to each form instance.""" initial_form_count = self.initial_form_count() if self.can_order: # Only pre-fill the ordering field for initial forms. if index is not None and index < initial_form_count: form.fields[ORDERING_FIELD_NAME] = IntegerField( label=_("Order"), initial=index + 1, required=False, widget=self.get_ordering_widget(), ) else: form.fields[ORDERING_FIELD_NAME] = IntegerField( label=_("Order"), required=False, widget=self.get_ordering_widget(), ) if self.can_delete and ( self.can_delete_extra or (index is not None and index < initial_form_count) ): form.fields[DELETION_FIELD_NAME] = BooleanField( label=_("Delete"), required=False, widget=self.get_deletion_widget(), ) def add_prefix(self, index): return "%s-%s" % (self.prefix, index) def is_multipart(self): """ Return True if the formset needs to be multipart, i.e. it has FileInput, or False otherwise. """ if self.forms: return self.forms[0].is_multipart() else: return self.empty_form.is_multipart() @property def media(self): # All the forms on a FormSet are the same, so you only need to # interrogate the first form for media. if self.forms: return self.forms[0].media else: return self.empty_form.media @property def template_name(self): return self.renderer.formset_template_name def get_context(self): return {"formset": self} def formset_factory( form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True, renderer=None, ): """Return a FormSet for the given form class.""" if min_num is None: min_num = DEFAULT_MIN_NUM if max_num is None: max_num = DEFAULT_MAX_NUM # absolute_max is a hard limit on forms instantiated, to prevent # memory-exhaustion attacks. Default to max_num + DEFAULT_MAX_NUM # (which is 2 * DEFAULT_MAX_NUM if max_num is None in the first place). if absolute_max is None: absolute_max = max_num + DEFAULT_MAX_NUM if max_num > absolute_max: raise ValueError("'absolute_max' must be greater or equal to 'max_num'.") attrs = { "form": form, "extra": extra, "can_order": can_order, "can_delete": can_delete, "can_delete_extra": can_delete_extra, "min_num": min_num, "max_num": max_num, "absolute_max": absolute_max, "validate_min": validate_min, "validate_max": validate_max, "renderer": renderer or get_default_renderer(), } return type(form.__name__ + "FormSet", (formset,), attrs) def all_valid(formsets): """Validate every formset and return True if all are valid.""" # List comprehension ensures is_valid() is called for all formsets. return all([formset.is_valid() for formset in formsets])
0828a141f5d886b596f7eafbcf011235d87b83436c402c4ae2fa6c03af67646c
""" Global Django exception and warning classes. """ import operator from django.utils.hashable import make_hashable class FieldDoesNotExist(Exception): """The requested model field does not exist""" pass class AppRegistryNotReady(Exception): """The django.apps registry is not populated yet""" pass class ObjectDoesNotExist(Exception): """The requested object does not exist""" silent_variable_failure = True class MultipleObjectsReturned(Exception): """The query returned multiple objects when only one was expected.""" pass class SuspiciousOperation(Exception): """The user did something suspicious""" class SuspiciousMultipartForm(SuspiciousOperation): """Suspect MIME request in multipart form data""" pass class SuspiciousFileOperation(SuspiciousOperation): """A Suspicious filesystem operation was attempted""" pass class DisallowedHost(SuspiciousOperation): """HTTP_HOST header contains invalid value""" pass class DisallowedRedirect(SuspiciousOperation): """Redirect to scheme not in allowed list""" pass class TooManyFieldsSent(SuspiciousOperation): """ The number of fields in a GET or POST request exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. """ pass class TooManyFilesSent(SuspiciousOperation): """ The number of fields in a GET or POST request exceeded settings.DATA_UPLOAD_MAX_NUMBER_FILES. """ pass class RequestDataTooBig(SuspiciousOperation): """ The size of the request (excluding any file uploads) exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. """ pass class RequestAborted(Exception): """The request was closed before it was completed, or timed out.""" pass class BadRequest(Exception): """The request is malformed and cannot be processed.""" pass class PermissionDenied(Exception): """The user did not have permission to do that""" pass class ViewDoesNotExist(Exception): """The requested view does not exist""" pass class MiddlewareNotUsed(Exception): """This middleware is not used in this server configuration""" pass class ImproperlyConfigured(Exception): """Django is somehow improperly configured""" pass class FieldError(Exception): """Some kind of problem with a model field.""" pass NON_FIELD_ERRORS = "__all__" class ValidationError(Exception): """An error while validating data.""" def __init__(self, message, code=None, params=None): """ The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its message attribute set, and what we define as list or dictionary can be an actual `list` or `dict` or an instance of ValidationError with its `error_list` or `error_dict` attribute set. """ super().__init__(message, code, params) if isinstance(message, ValidationError): if hasattr(message, "error_dict"): message = message.error_dict elif not hasattr(message, "message"): message = message.error_list else: message, code, params = message.message, message.code, message.params if isinstance(message, dict): self.error_dict = {} for field, messages in message.items(): if not isinstance(messages, ValidationError): messages = ValidationError(messages) self.error_dict[field] = messages.error_list elif isinstance(message, list): self.error_list = [] for message in message: # Normalize plain strings to instances of ValidationError. if not isinstance(message, ValidationError): message = ValidationError(message) if hasattr(message, "error_dict"): self.error_list.extend(sum(message.error_dict.values(), [])) else: self.error_list.extend(message.error_list) else: self.message = message self.code = code self.params = params self.error_list = [self] @property def message_dict(self): # Trigger an AttributeError if this ValidationError # doesn't have an error_dict. getattr(self, "error_dict") return dict(self) @property def messages(self): if hasattr(self, "error_dict"): return sum(dict(self).values(), []) return list(self) def update_error_dict(self, error_dict): if hasattr(self, "error_dict"): for field, error_list in self.error_dict.items(): error_dict.setdefault(field, []).extend(error_list) else: error_dict.setdefault(NON_FIELD_ERRORS, []).extend(self.error_list) return error_dict def __iter__(self): if hasattr(self, "error_dict"): for field, errors in self.error_dict.items(): yield field, list(ValidationError(errors)) else: for error in self.error_list: message = error.message if error.params: message %= error.params yield str(message) def __str__(self): if hasattr(self, "error_dict"): return repr(dict(self)) return repr(list(self)) def __repr__(self): return "ValidationError(%s)" % self def __eq__(self, other): if not isinstance(other, ValidationError): return NotImplemented return hash(self) == hash(other) def __hash__(self): if hasattr(self, "message"): return hash( ( self.message, self.code, make_hashable(self.params), ) ) if hasattr(self, "error_dict"): return hash(make_hashable(self.error_dict)) return hash(tuple(sorted(self.error_list, key=operator.attrgetter("message")))) class EmptyResultSet(Exception): """A database query predicate is impossible.""" pass class FullResultSet(Exception): """A database query predicate is matches everything.""" pass class SynchronousOnlyOperation(Exception): """The user tried to call a sync-only function from an async context.""" pass
55933d3eed8d9cf8e185fb60770230c44d642e545cf9caf57ae9f72625c264e3
""" Multi-part parsing for file uploads. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ import base64 import binascii import collections import html from django.conf import settings from django.core.exceptions import ( RequestDataTooBig, SuspiciousMultipartForm, TooManyFieldsSent, TooManyFilesSent, ) from django.core.files.uploadhandler import SkipFile, StopFutureHandlers, StopUpload from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str from django.utils.http import parse_header_parameters from django.utils.regex_helper import _lazy_re_compile __all__ = ("MultiPartParser", "MultiPartParserError", "InputStreamExhausted") class MultiPartParserError(Exception): pass class InputStreamExhausted(Exception): """ No more reads are allowed from this device. """ pass RAW = "raw" FILE = "file" FIELD = "field" FIELD_TYPES = frozenset([FIELD, RAW]) class MultiPartParser: """ An RFC 7578 multipart/form-data parser. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``. """ boundary_re = _lazy_re_compile(r"[ -~]{0,200}[!-~]") def __init__(self, META, input_data, upload_handlers, encoding=None): """ Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handlers: A list of UploadHandler instances that perform operations on the uploaded data. :encoding: The encoding with which to treat the incoming data. """ # Content-Type should contain multipart and the boundary information. content_type = META.get("CONTENT_TYPE", "") if not content_type.startswith("multipart/"): raise MultiPartParserError("Invalid Content-Type: %s" % content_type) try: content_type.encode("ascii") except UnicodeEncodeError: raise MultiPartParserError( "Invalid non-ASCII Content-Type in multipart: %s" % force_str(content_type) ) # Parse the header to get the boundary to split the parts. _, opts = parse_header_parameters(content_type) boundary = opts.get("boundary") if not boundary or not self.boundary_re.fullmatch(boundary): raise MultiPartParserError( "Invalid boundary in multipart: %s" % force_str(boundary) ) # Content-Length should contain the length of the body we are about # to receive. try: content_length = int(META.get("CONTENT_LENGTH", 0)) except (ValueError, TypeError): content_length = 0 if content_length < 0: # This means we shouldn't continue...raise an error. raise MultiPartParserError("Invalid content length: %r" % content_length) self._boundary = boundary.encode("ascii") self._input_data = input_data # For compatibility with low-level network APIs (with 32-bit integers), # the chunk size should be < 2^31, but still divisible by 4. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] self._chunk_size = min([2**31 - 4] + possible_sizes) self._meta = META self._encoding = encoding or settings.DEFAULT_CHARSET self._content_length = content_length self._upload_handlers = upload_handlers def parse(self): # Call the actual parse routine and close all open files in case of # errors. This is needed because if exceptions are thrown the # MultiPartParser will not be garbage collected immediately and # resources would be kept alive. This is only needed for errors because # the Request object closes all uploaded files at the end of the # request. try: return self._parse() except Exception: if hasattr(self, "_files"): for _, files in self._files.lists(): for fileobj in files: fileobj.close() raise def _parse(self): """ Parse the POST data and break it into a FILES MultiValueDict and a POST MultiValueDict. Return a tuple containing the POST and FILES dictionary, respectively. """ from django.http import QueryDict encoding = self._encoding handlers = self._upload_handlers # HTTP spec says that Content-Length >= 0 is valid # handling content-length == 0 before continuing if self._content_length == 0: return QueryDict(encoding=self._encoding), MultiValueDict() # See if any of the handlers take care of the parsing. # This allows overriding everything if need be. for handler in handlers: result = handler.handle_raw_input( self._input_data, self._meta, self._content_length, self._boundary, encoding, ) # Check to see if it was handled if result is not None: return result[0], result[1] # Create the data structures to be used later. self._post = QueryDict(mutable=True) self._files = MultiValueDict() # Instantiate the parser and stream: stream = LazyStream(ChunkIter(self._input_data, self._chunk_size)) # Whether or not to signal a file-completion at the beginning of the loop. old_field_name = None counters = [0] * len(handlers) # Number of bytes that have been read. num_bytes_read = 0 # To count the number of keys in the request. num_post_keys = 0 # To count the number of files in the request. num_files = 0 # To limit the amount of data read from the request. read_size = None # Whether a file upload is finished. uploaded_file = True try: for item_type, meta_data, field_stream in Parser(stream, self._boundary): if old_field_name: # We run this at the beginning of the next loop # since we cannot be sure a file is complete until # we hit the next boundary/part of the multipart content. self.handle_file_complete(old_field_name, counters) old_field_name = None uploaded_file = True if ( item_type in FIELD_TYPES and settings.DATA_UPLOAD_MAX_NUMBER_FIELDS is not None ): # Avoid storing more than DATA_UPLOAD_MAX_NUMBER_FIELDS. num_post_keys += 1 # 2 accounts for empty raw fields before and after the # last boundary. if settings.DATA_UPLOAD_MAX_NUMBER_FIELDS + 2 < num_post_keys: raise TooManyFieldsSent( "The number of GET/POST parameters exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS." ) try: disposition = meta_data["content-disposition"][1] field_name = disposition["name"].strip() except (KeyError, IndexError, AttributeError): continue transfer_encoding = meta_data.get("content-transfer-encoding") if transfer_encoding is not None: transfer_encoding = transfer_encoding[0].strip() field_name = force_str(field_name, encoding, errors="replace") if item_type == FIELD: # Avoid reading more than DATA_UPLOAD_MAX_MEMORY_SIZE. if settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None: read_size = ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE - num_bytes_read ) # This is a post field, we can just set it in the post if transfer_encoding == "base64": raw_data = field_stream.read(size=read_size) num_bytes_read += len(raw_data) try: data = base64.b64decode(raw_data) except binascii.Error: data = raw_data else: data = field_stream.read(size=read_size) num_bytes_read += len(data) # Add two here to make the check consistent with the # x-www-form-urlencoded check that includes '&='. num_bytes_read += len(field_name) + 2 if ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and num_bytes_read > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( "Request body exceeded " "settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) self._post.appendlist( field_name, force_str(data, encoding, errors="replace") ) elif item_type == FILE: # Avoid storing more than DATA_UPLOAD_MAX_NUMBER_FILES. num_files += 1 if ( settings.DATA_UPLOAD_MAX_NUMBER_FILES is not None and num_files > settings.DATA_UPLOAD_MAX_NUMBER_FILES ): raise TooManyFilesSent( "The number of files exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FILES." ) # This is a file, use the handler... file_name = disposition.get("filename") if file_name: file_name = force_str(file_name, encoding, errors="replace") file_name = self.sanitize_file_name(file_name) if not file_name: continue content_type, content_type_extra = meta_data.get( "content-type", ("", {}) ) content_type = content_type.strip() charset = content_type_extra.get("charset") try: content_length = int(meta_data.get("content-length")[0]) except (IndexError, TypeError, ValueError): content_length = None counters = [0] * len(handlers) uploaded_file = False try: for handler in handlers: try: handler.new_file( field_name, file_name, content_type, content_length, charset, content_type_extra, ) except StopFutureHandlers: break for chunk in field_stream: if transfer_encoding == "base64": # We only special-case base64 transfer encoding # We should always decode base64 chunks by # multiple of 4, ignoring whitespace. stripped_chunk = b"".join(chunk.split()) remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: break stripped_chunk += b"".join(over_chunk.split()) remaining = len(stripped_chunk) % 4 try: chunk = base64.b64decode(stripped_chunk) except Exception as exc: # Since this is only a chunk, any error is # an unfixable error. raise MultiPartParserError( "Could not decode base64 data." ) from exc for i, handler in enumerate(handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[i]) counters[i] += chunk_length if chunk is None: # Don't continue if the chunk received by # the handler is None. break except SkipFile: self._close_files() # Just use up the rest of this file... exhaust(field_stream) else: # Handle file upload completions on next iteration. old_field_name = field_name else: # If this is neither a FIELD nor a FILE, exhaust the field # stream. Note: There could be an error here at some point, # but there will be at least two RAW types (before and # after the other boundaries). This branch is usually not # reached at all, because a missing content-disposition # header will skip the whole boundary. exhaust(field_stream) except StopUpload as e: self._close_files() if not e.connection_reset: exhaust(self._input_data) else: if not uploaded_file: for handler in handlers: handler.upload_interrupted() # Make sure that the request data is all fed exhaust(self._input_data) # Signal that the upload has completed. # any() shortcircuits if a handler's upload_complete() returns a value. any(handler.upload_complete() for handler in handlers) self._post._mutable = False return self._post, self._files def handle_file_complete(self, old_field_name, counters): """ Handle all the signaling that takes place when a file is complete. """ for i, handler in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: # If it returns a file object, then set the files dict. self._files.appendlist( force_str(old_field_name, self._encoding, errors="replace"), file_obj, ) break def sanitize_file_name(self, file_name): """ Sanitize the filename of an upload. Remove all possible path separators, even though that might remove more than actually required by the target system. Filenames that could potentially cause problems (current/parent dir) are also discarded. It should be noted that this function could still return a "filepath" like "C:some_file.txt" which is handled later on by the storage layer. So while this function does sanitize filenames to some extent, the resulting filename should still be considered as untrusted user input. """ file_name = html.unescape(file_name) file_name = file_name.rsplit("/")[-1] file_name = file_name.rsplit("\\")[-1] # Remove non-printable characters. file_name = "".join([char for char in file_name if char.isprintable()]) if file_name in {"", ".", ".."}: return None return file_name IE_sanitize = sanitize_file_name def _close_files(self): # Free up all file handles. # FIXME: this currently assumes that upload handlers store the file as 'file' # We should document that... # (Maybe add handler.free_file to complement new_file) for handler in self._upload_handlers: if hasattr(handler, "file"): handler.file.close() class LazyStream: """ The LazyStream wrapper allows one to get and "unget" bytes from a stream. Given a producer object (an iterator that yields bytestrings), the LazyStream object will support iteration, reading, and keeping a "look-back" variable in case you need to "unget" some bytes. """ def __init__(self, producer, length=None): """ Every LazyStream must have a producer when instantiated. A producer is an iterable that returns a string each time it is called. """ self._producer = producer self._empty = False self._leftover = b"" self.length = length self.position = 0 self._remaining = length self._unget_history = [] def tell(self): return self.position def read(self, size=None): def parts(): remaining = self._remaining if size is None else size # do the whole thing in one shot if no limit was provided. if remaining is None: yield b"".join(self) return # otherwise do some bookkeeping to return exactly enough # of the stream and stashing any extra content we get from # the producer while remaining != 0: assert remaining > 0, "remaining bytes to read should never go negative" try: chunk = next(self) except StopIteration: return else: emitting = chunk[:remaining] self.unget(chunk[remaining:]) remaining -= len(emitting) yield emitting return b"".join(parts()) def __next__(self): """ Used when the exact number of bytes to read is unimportant. Return whatever chunk is conveniently returned from the iterator. Useful to avoid unnecessary bookkeeping if performance is an issue. """ if self._leftover: output = self._leftover self._leftover = b"" else: output = next(self._producer) self._unget_history = [] self.position += len(output) return output def close(self): """ Used to invalidate/disable this lazy stream. Replace the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next(). """ self._producer = [] def __iter__(self): return self def unget(self, bytes): """ Place bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound. """ if not bytes: return self._update_unget_history(len(bytes)) self.position -= len(bytes) self._leftover = bytes + self._leftover def _update_unget_history(self, num_bytes): """ Update the unget history as a sanity check to see if we've pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we're mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request. """ self._unget_history = [num_bytes] + self._unget_history[:49] number_equal = len( [ current_number for current_number in self._unget_history if current_number == num_bytes ] ) if number_equal > 40: raise SuspiciousMultipartForm( "The multipart parser got stuck, which shouldn't happen with" " normal uploaded files. Check for malicious upload activity;" " if there is none, report this to the Django developers." ) class ChunkIter: """ An iterable that will yield chunks of data. Given a file-like object as the constructor, yield chunks of read operations from that object. """ def __init__(self, flo, chunk_size=64 * 1024): self.flo = flo self.chunk_size = chunk_size def __next__(self): try: data = self.flo.read(self.chunk_size) except InputStreamExhausted: raise StopIteration() if data: return data else: raise StopIteration() def __iter__(self): return self class InterBoundaryIter: """ A Producer that will iterate over boundaries. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary def __iter__(self): return self def __next__(self): try: return LazyStream(BoundaryIter(self._stream, self._boundary)) except InputStreamExhausted: raise StopIteration() class BoundaryIter: """ A Producer that is sensitive to boundaries. Will happily yield bytes until a boundary is found. Will yield the bytes before the boundary, throw away the boundary bytes themselves, and push the post-boundary bytes back on the stream. The future calls to next() after locating the boundary will raise a StopIteration exception. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary self._done = False # rollback an additional six bytes because the format is like # this: CRLF<boundary>[--CRLF] self._rollback = len(boundary) + 6 # Try to use mx fast string search if available. Otherwise # use Python find. Wrap the latter for consistency. unused_char = self._stream.read(1) if not unused_char: raise InputStreamExhausted() self._stream.unget(unused_char) def __iter__(self): return self def __next__(self): if self._done: raise StopIteration() stream = self._stream rollback = self._rollback bytes_read = 0 chunks = [] for bytes in stream: bytes_read += len(bytes) chunks.append(bytes) if bytes_read > rollback: break if not bytes: break else: self._done = True if not chunks: raise StopIteration() chunk = b"".join(chunks) boundary = self._find_boundary(chunk) if boundary: end, next = boundary stream.unget(chunk[next:]) self._done = True return chunk[:end] else: # make sure we don't treat a partial boundary (and # its separators) as data if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6): # There's nothing left, we should just return and mark as done. self._done = True return chunk else: stream.unget(chunk[-rollback:]) return chunk[:-rollback] def _find_boundary(self, data): """ Find a multipart boundary in data. Should no boundary exist in the data, return None. Otherwise, return a tuple containing the indices of the following: * the end of current encapsulation * the start of the next encapsulation """ index = data.find(self._boundary) if index < 0: return None else: end = index next = index + len(self._boundary) # backup over CRLF last = max(0, end - 1) if data[last : last + 1] == b"\n": end -= 1 last = max(0, end - 1) if data[last : last + 1] == b"\r": end -= 1 return end, next def exhaust(stream_or_iterable): """Exhaust an iterator or stream.""" try: iterator = iter(stream_or_iterable) except TypeError: iterator = ChunkIter(stream_or_iterable, 16384) collections.deque(iterator, maxlen=0) # consume iterator quickly. def parse_boundary_stream(stream, max_header_size): """ Parse one and exactly one stream that encapsulates a boundary. """ # Stream at beginning of header, look for end of header # and parse it if found. The header must fit within one # chunk. chunk = stream.read(max_header_size) # 'find' returns the top of these four bytes, so we'll # need to munch them later to prevent them from polluting # the payload. header_end = chunk.find(b"\r\n\r\n") if header_end == -1: # we find no header, so we just mark this fact and pass on # the stream verbatim stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] # here we place any excess chunk back onto the stream, as # well as throwing away the CRLFCRLF bytes from above. stream.unget(chunk[header_end + 4 :]) TYPE = RAW outdict = {} # Eliminate blank lines for line in header.split(b"\r\n"): # This terminology ("main value" and "dictionary of # parameters") is from the Python docs. try: main_value_pair, params = parse_header_parameters(line.decode()) name, value = main_value_pair.split(":", 1) params = {k: v.encode() for k, v in params.items()} except ValueError: # Invalid header. continue if name == "content-disposition": TYPE = FIELD if params.get("filename"): TYPE = FILE outdict[name] = value, params if TYPE == RAW: stream.unget(chunk) return (TYPE, outdict, stream) class Parser: def __init__(self, stream, boundary): self._stream = stream self._separator = b"--" + boundary def __iter__(self): boundarystream = InterBoundaryIter(self._stream, self._separator) for sub_stream in boundarystream: # Iterate over each part yield parse_boundary_stream(sub_stream, 1024)
1e43db213dd94795ac801b3b7ad1e99c9bee33e5f8dd3fc80fe2f3e5f009c2af
import codecs import copy from io import BytesIO from itertools import chain from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit from django.conf import settings from django.core import signing from django.core.exceptions import ( DisallowedHost, ImproperlyConfigured, RequestDataTooBig, TooManyFieldsSent, ) from django.core.files import uploadhandler from django.http.multipartparser import ( MultiPartParser, MultiPartParserError, TooManyFilesSent, ) from django.utils.datastructures import ( CaseInsensitiveMapping, ImmutableList, MultiValueDict, ) from django.utils.encoding import escape_uri_path, iri_to_uri from django.utils.functional import cached_property from django.utils.http import is_same_domain, parse_header_parameters from django.utils.regex_helper import _lazy_re_compile RAISE_ERROR = object() host_validation_re = _lazy_re_compile( r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:[0-9]+)?$" ) class UnreadablePostError(OSError): pass class RawPostDataException(Exception): """ You cannot access raw_post_data from a request that has multipart/* POST data if it has been accessed via POST, FILES, etc.. """ pass class HttpRequest: """A basic HTTP request.""" # The encoding used in GET/POST dicts. None means use default setting. _encoding = None _upload_handlers = [] non_picklable_attrs = frozenset(["resolver_match", "_stream"]) def __init__(self): # WARNING: The `WSGIRequest` subclass doesn't call `super`. # Any variable assignment made here should also happen in # `WSGIRequest.__init__()`. self.GET = QueryDict(mutable=True) self.POST = QueryDict(mutable=True) self.COOKIES = {} self.META = {} self.FILES = MultiValueDict() self.path = "" self.path_info = "" self.method = None self.resolver_match = None self.content_type = None self.content_params = None def __repr__(self): if self.method is None or not self.get_full_path(): return "<%s>" % self.__class__.__name__ return "<%s: %s %r>" % ( self.__class__.__name__, self.method, self.get_full_path(), ) def __getstate__(self): obj_dict = self.__dict__.copy() for attr in self.non_picklable_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def __deepcopy__(self, memo): obj = copy.copy(self) for attr in self.non_picklable_attrs: if hasattr(self, attr): setattr(obj, attr, copy.deepcopy(getattr(self, attr), memo)) memo[id(self)] = obj return obj @cached_property def headers(self): return HttpHeaders(self.META) @cached_property def accepted_types(self): """Return a list of MediaType instances.""" return parse_accept_header(self.headers.get("Accept", "*/*")) def accepts(self, media_type): return any( accepted_type.match(media_type) for accepted_type in self.accepted_types ) def _set_content_type_params(self, meta): """Set content_type, content_params, and encoding.""" self.content_type, self.content_params = parse_header_parameters( meta.get("CONTENT_TYPE", "") ) if "charset" in self.content_params: try: codecs.lookup(self.content_params["charset"]) except LookupError: pass else: self.encoding = self.content_params["charset"] def _get_raw_host(self): """ Return the HTTP host using the environment or request headers. Skip allowed hosts protection, so may return an insecure host. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ("HTTP_X_FORWARDED_HOST" in self.META): host = self.META["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in self.META: host = self.META["HTTP_HOST"] else: # Reconstruct the host using the algorithm from PEP 333. host = self.META["SERVER_NAME"] server_port = self.get_port() if server_port != ("443" if self.is_secure() else "80"): host = "%s:%s" % (host, server_port) return host def get_host(self): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: allowed_hosts = [".localhost", "127.0.0.1", "[::1]"] domain, port = split_domain_port(host) if domain and validate_host(domain, allowed_hosts): return host else: msg = "Invalid HTTP_HOST header: %r." % host if domain: msg += " You may need to add %r to ALLOWED_HOSTS." % domain else: msg += ( " The domain name provided is not valid according to RFC 1034/1035." ) raise DisallowedHost(msg) def get_port(self): """Return the port number for the request as a string.""" if settings.USE_X_FORWARDED_PORT and "HTTP_X_FORWARDED_PORT" in self.META: port = self.META["HTTP_X_FORWARDED_PORT"] else: port = self.META["SERVER_PORT"] return str(port) def get_full_path(self, force_append_slash=False): return self._get_full_path(self.path, force_append_slash) def get_full_path_info(self, force_append_slash=False): return self._get_full_path(self.path_info, force_append_slash) def _get_full_path(self, path, force_append_slash): # RFC 3986 requires query string arguments to be in the ASCII range. # Rather than crash if this doesn't happen, we encode defensively. return "%s%s%s" % ( escape_uri_path(path), "/" if force_append_slash and not path.endswith("/") else "", ("?" + iri_to_uri(self.META.get("QUERY_STRING", ""))) if self.META.get("QUERY_STRING", "") else "", ) def get_signed_cookie(self, key, default=RAISE_ERROR, salt="", max_age=None): """ Attempt to return a signed cookie. If the signature fails or the cookie has expired, raise an exception, unless the `default` argument is provided, in which case return that value. """ try: cookie_value = self.COOKIES[key] except KeyError: if default is not RAISE_ERROR: return default else: raise try: value = signing.get_cookie_signer(salt=key + salt).unsign( cookie_value, max_age=max_age ) except signing.BadSignature: if default is not RAISE_ERROR: return default else: raise return value def build_absolute_uri(self, location=None): """ Build an absolute URI from the location and the variables available in this request. If no ``location`` is specified, build the absolute URI using request.get_full_path(). If the location is absolute, convert it to an RFC 3987 compliant URI and return it. If location is relative or is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base URL constructed from the request variables. """ if location is None: # Make it an absolute url (but schemeless and domainless) for the # edge case that the path starts with '//'. location = "//%s" % self.get_full_path() else: # Coerce lazy locations. location = str(location) bits = urlsplit(location) if not (bits.scheme and bits.netloc): # Handle the simple, most common case. If the location is absolute # and a scheme or host (netloc) isn't provided, skip an expensive # urljoin() as long as no path segments are '.' or '..'. if ( bits.path.startswith("/") and not bits.scheme and not bits.netloc and "/./" not in bits.path and "/../" not in bits.path ): # If location starts with '//' but has no netloc, reuse the # schema and netloc from the current request. Strip the double # slashes and continue as if it wasn't specified. location = self._current_scheme_host + location.removeprefix("//") else: # Join the constructed URL with the provided location, which # allows the provided location to apply query strings to the # base path. location = urljoin(self._current_scheme_host + self.path, location) return iri_to_uri(location) @cached_property def _current_scheme_host(self): return "{}://{}".format(self.scheme, self.get_host()) def _get_scheme(self): """ Hook for subclasses like WSGIRequest to implement. Return 'http' by default. """ return "http" @property def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( "The SECURE_PROXY_SSL_HEADER setting must be a tuple containing " "two values." ) header_value = self.META.get(header) if header_value is not None: header_value, *_ = header_value.split(",", 1) return "https" if header_value.strip() == secure_value else "http" return self._get_scheme() def is_secure(self): return self.scheme == "https" @property def encoding(self): return self._encoding @encoding.setter def encoding(self, val): """ Set the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, remove and recreate it on the next access (so that it is decoded correctly). """ self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._post def _initialize_handlers(self): self._upload_handlers = [ uploadhandler.load_handler(handler, self) for handler in settings.FILE_UPLOAD_HANDLERS ] @property def upload_handlers(self): if not self._upload_handlers: # If there are no upload handlers defined, initialize them from settings. self._initialize_handlers() return self._upload_handlers @upload_handlers.setter def upload_handlers(self, upload_handlers): if hasattr(self, "_files"): raise AttributeError( "You cannot set the upload handlers after the upload has been " "processed." ) self._upload_handlers = upload_handlers def parse_file_upload(self, META, post_data): """Return a tuple of (POST QueryDict, FILES MultiValueDict).""" self.upload_handlers = ImmutableList( self.upload_handlers, warning=( "You cannot alter upload handlers after the upload has been " "processed." ), ) parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding) return parser.parse() @property def body(self): if not hasattr(self, "_body"): if self._read_started: raise RawPostDataException( "You cannot access body after reading from request's data stream" ) # Limit the maximum request data size that will be handled in-memory. if ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and int(self.META.get("CONTENT_LENGTH") or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) try: self._body = self.read() except OSError as e: raise UnreadablePostError(*e.args) from e finally: self._stream.close() self._stream = BytesIO(self._body) return self._body def _mark_post_parse_error(self): self._post = QueryDict() self._files = MultiValueDict() def _load_post_and_files(self): """Populate self._post and self._files if the content-type is a form type""" if self.method != "POST": self._post, self._files = ( QueryDict(encoding=self._encoding), MultiValueDict(), ) return if self._read_started and not hasattr(self, "_body"): self._mark_post_parse_error() return if self.content_type == "multipart/form-data": if hasattr(self, "_body"): # Use already read data data = BytesIO(self._body) else: data = self try: self._post, self._files = self.parse_file_upload(self.META, data) except (MultiPartParserError, TooManyFilesSent): # An error occurred while parsing POST data. Since when # formatting the error the request handler might access # self.POST, set self._post and self._file to prevent # attempts to parse POST data again. self._mark_post_parse_error() raise elif self.content_type == "application/x-www-form-urlencoded": self._post, self._files = ( QueryDict(self.body, encoding=self._encoding), MultiValueDict(), ) else: self._post, self._files = ( QueryDict(encoding=self._encoding), MultiValueDict(), ) def close(self): if hasattr(self, "_files"): for f in chain.from_iterable(list_[1] for list_ in self._files.lists()): f.close() # File-like and iterator interface. # # Expects self._stream to be set to an appropriate source of bytes by # a corresponding request subclass (e.g. WSGIRequest). # Also when request data has already been read by request.POST or # request.body, self._stream points to a BytesIO instance # containing that data. def read(self, *args, **kwargs): self._read_started = True try: return self._stream.read(*args, **kwargs) except OSError as e: raise UnreadablePostError(*e.args) from e def readline(self, *args, **kwargs): self._read_started = True try: return self._stream.readline(*args, **kwargs) except OSError as e: raise UnreadablePostError(*e.args) from e def __iter__(self): return iter(self.readline, b"") def readlines(self): return list(self) class HttpHeaders(CaseInsensitiveMapping): HTTP_PREFIX = "HTTP_" # PEP 333 gives two headers which aren't prepended with HTTP_. UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"} def __init__(self, environ): headers = {} for header, value in environ.items(): name = self.parse_header_name(header) if name: headers[name] = value super().__init__(headers) def __getitem__(self, key): """Allow header lookup using underscores in place of hyphens.""" return super().__getitem__(key.replace("_", "-")) @classmethod def parse_header_name(cls, header): if header.startswith(cls.HTTP_PREFIX): header = header.removeprefix(cls.HTTP_PREFIX) elif header not in cls.UNPREFIXED_HEADERS: return None return header.replace("_", "-").title() @classmethod def to_wsgi_name(cls, header): header = header.replace("-", "_").upper() if header in cls.UNPREFIXED_HEADERS: return header return f"{cls.HTTP_PREFIX}{header}" @classmethod def to_asgi_name(cls, header): return header.replace("-", "_").upper() @classmethod def to_wsgi_names(cls, headers): return { cls.to_wsgi_name(header_name): value for header_name, value in headers.items() } @classmethod def to_asgi_names(cls, headers): return { cls.to_asgi_name(header_name): value for header_name, value in headers.items() } class QueryDict(MultiValueDict): """ A specialized MultiValueDict which represents a query string. A QueryDict can be used to represent GET or POST data. It subclasses MultiValueDict since keys in such data can be repeated, for instance in the data from a form with a <select multiple> field. By default QueryDicts are immutable, though the copy() method will always return a mutable copy. Both keys and values set on this class are converted from the given encoding (DEFAULT_CHARSET by default) to str. """ # These are both reset in __init__, but is specified here at the class # level so that unpickling will have valid values _mutable = True _encoding = None def __init__(self, query_string=None, mutable=False, encoding=None): super().__init__() self.encoding = encoding or settings.DEFAULT_CHARSET query_string = query_string or "" parse_qsl_kwargs = { "keep_blank_values": True, "encoding": self.encoding, "max_num_fields": settings.DATA_UPLOAD_MAX_NUMBER_FIELDS, } if isinstance(query_string, bytes): # query_string normally contains URL-encoded data, a subset of ASCII. try: query_string = query_string.decode(self.encoding) except UnicodeDecodeError: # ... but some user agents are misbehaving :-( query_string = query_string.decode("iso-8859-1") try: for key, value in parse_qsl(query_string, **parse_qsl_kwargs): self.appendlist(key, value) except ValueError as e: # ValueError can also be raised if the strict_parsing argument to # parse_qsl() is True. As that is not used by Django, assume that # the exception was raised by exceeding the value of max_num_fields # instead of fragile checks of exception message strings. raise TooManyFieldsSent( "The number of GET/POST parameters exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS." ) from e self._mutable = mutable @classmethod def fromkeys(cls, iterable, value="", mutable=False, encoding=None): """ Return a new QueryDict with keys (may be repeated) from an iterable and values from value. """ q = cls("", mutable=True, encoding=encoding) for key in iterable: q.appendlist(key, value) if not mutable: q._mutable = False return q @property def encoding(self): if self._encoding is None: self._encoding = settings.DEFAULT_CHARSET return self._encoding @encoding.setter def encoding(self, value): self._encoding = value def _assert_mutable(self): if not self._mutable: raise AttributeError("This QueryDict instance is immutable") def __setitem__(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) super().__setitem__(key, value) def __delitem__(self, key): self._assert_mutable() super().__delitem__(key) def __copy__(self): result = self.__class__("", mutable=True, encoding=self.encoding) for key, value in self.lists(): result.setlist(key, value) return result def __deepcopy__(self, memo): result = self.__class__("", mutable=True, encoding=self.encoding) memo[id(self)] = result for key, value in self.lists(): result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def setlist(self, key, list_): self._assert_mutable() key = bytes_to_text(key, self.encoding) list_ = [bytes_to_text(elt, self.encoding) for elt in list_] super().setlist(key, list_) def setlistdefault(self, key, default_list=None): self._assert_mutable() return super().setlistdefault(key, default_list) def appendlist(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) super().appendlist(key, value) def pop(self, key, *args): self._assert_mutable() return super().pop(key, *args) def popitem(self): self._assert_mutable() return super().popitem() def clear(self): self._assert_mutable() super().clear() def setdefault(self, key, default=None): self._assert_mutable() key = bytes_to_text(key, self.encoding) default = bytes_to_text(default, self.encoding) return super().setdefault(key, default) def copy(self): """Return a mutable copy of this object.""" return self.__deepcopy__({}) def urlencode(self, safe=None): """ Return an encoded string of all query string arguments. `safe` specifies characters which don't require quoting, for example:: >>> q = QueryDict(mutable=True) >>> q['next'] = '/a&b/' >>> q.urlencode() 'next=%2Fa%26b%2F' >>> q.urlencode(safe='/') 'next=/a%26b/' """ output = [] if safe: safe = safe.encode(self.encoding) def encode(k, v): return "%s=%s" % ((quote(k, safe), quote(v, safe))) else: def encode(k, v): return urlencode({k: v}) for k, list_ in self.lists(): output.extend( encode(k.encode(self.encoding), str(v).encode(self.encoding)) for v in list_ ) return "&".join(output) class MediaType: def __init__(self, media_type_raw_line): full_type, self.params = parse_header_parameters( media_type_raw_line if media_type_raw_line else "" ) self.main_type, _, self.sub_type = full_type.partition("/") def __str__(self): params_str = "".join("; %s=%s" % (k, v) for k, v in self.params.items()) return "%s%s%s" % ( self.main_type, ("/%s" % self.sub_type) if self.sub_type else "", params_str, ) def __repr__(self): return "<%s: %s>" % (self.__class__.__qualname__, self) @property def is_all_types(self): return self.main_type == "*" and self.sub_type == "*" def match(self, other): if self.is_all_types: return True other = MediaType(other) if self.main_type == other.main_type and self.sub_type in {"*", other.sub_type}: return True return False # It's neither necessary nor appropriate to use # django.utils.encoding.force_str() for parsing URLs and form inputs. Thus, # this slightly more restricted function, used by QueryDict. def bytes_to_text(s, encoding): """ Convert bytes objects to strings, using the given encoding. Illegally encoded input characters are replaced with Unicode "unknown" codepoint (\ufffd). Return any non-bytes objects without change. """ if isinstance(s, bytes): return str(s, encoding, "replace") else: return s def split_domain_port(host): """ Return a (domain, port) tuple from a given host. Returned domain is lowercased. If the host is invalid, the domain will be empty. """ host = host.lower() if not host_validation_re.match(host): return "", "" if host[-1] == "]": # It's an IPv6 address without a port. return host, "" bits = host.rsplit(":", 1) domain, port = bits if len(bits) == 2 else (bits[0], "") # Remove a trailing dot (if present) from the domain. domain = domain.removesuffix(".") return domain, port def validate_host(host, allowed_hosts): """ Validate the given host for this site. Check that the host looks valid and matches a host or host pattern in the given list of ``allowed_hosts``. Any pattern beginning with a period matches a domain and all its subdomains (e.g. ``.example.com`` matches ``example.com`` and any subdomain), ``*`` matches anything, and anything else must match exactly. Note: This function assumes that the given host is lowercased and has already had the port, if any, stripped off. Return ``True`` for a valid host, ``False`` otherwise. """ return any( pattern == "*" or is_same_domain(host, pattern) for pattern in allowed_hosts ) def parse_accept_header(header): return [MediaType(token) for token in header.split(",") if token.strip()]
ed2bac3b574f12b63af21e60e25a71bcf6ec25876b6d372bff4117eee0ca60da
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r"j \d\e F \d\e Y" TIME_FORMAT = "H:i" DATETIME_FORMAT = r"j \d\e F \d\e Y \a \l\a\s H:i" YEAR_MONTH_FORMAT = r"F \d\e Y" MONTH_DAY_FORMAT = r"j \d\e F" SHORT_DATE_FORMAT = "d/m/Y" SHORT_DATETIME_FORMAT = "d/m/Y H:i" FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ "%d/%m/%Y", # '31/12/2009' "%d/%m/%y", # '31/12/09' ] DATETIME_INPUT_FORMATS = [ "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M:%S.%f", "%d/%m/%Y %H:%M", "%d/%m/%y %H:%M:%S", "%d/%m/%y %H:%M:%S.%f", "%d/%m/%y %H:%M", ] DECIMAL_SEPARATOR = "," THOUSAND_SEPARATOR = "\xa0" # non-breaking space NUMBER_GROUPING = 3