hash
stringlengths
64
64
content
stringlengths
0
1.51M
35643fc6c81817d56e131a71719b9d29161d394c9a31875137691323b1d23876
import unittest from datetime import date, datetime, time, timedelta from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.timezone import get_fixed_timezone class DateParseTests(unittest.TestCase): def test_parse_date(self): # Valid inputs self.assertEqual(parse_date('2012-04-23'), date(2012, 4, 23)) self.assertEqual(parse_date('2012-4-9'), date(2012, 4, 9)) # Invalid inputs self.assertIsNone(parse_date('20120423')) with self.assertRaises(ValueError): parse_date('2012-04-56') def test_parse_time(self): # Valid inputs self.assertEqual(parse_time('09:15:00'), time(9, 15)) self.assertEqual(parse_time('10:10'), time(10, 10)) self.assertEqual(parse_time('10:20:30.400'), time(10, 20, 30, 400000)) self.assertEqual(parse_time('4:8:16'), time(4, 8, 16)) # Invalid inputs self.assertIsNone(parse_time('091500')) with self.assertRaises(ValueError): parse_time('09:15:90') def test_parse_datetime(self): valid_inputs = ( ('2012-04-23T09:15:00', datetime(2012, 4, 23, 9, 15)), ('2012-4-9 4:8:16', datetime(2012, 4, 9, 4, 8, 16)), ('2012-04-23T09:15:00Z', datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0))), ('2012-4-9 4:8:16-0320', datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200))), ('2012-04-23T10:20:30.400+02:30', datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150))), ('2012-04-23T10:20:30.400+02', datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120))), ('2012-04-23T10:20:30.400-02', datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120))), ) for source, expected in valid_inputs: with self.subTest(source=source): self.assertEqual(parse_datetime(source), expected) # Invalid inputs self.assertIsNone(parse_datetime('20120423091500')) with self.assertRaises(ValueError): parse_datetime('2012-04-56T09:15:90') class DurationParseTests(unittest.TestCase): def test_parse_python_format(self): timedeltas = [ timedelta(days=4, minutes=15, seconds=30, milliseconds=100), # fractions of seconds timedelta(hours=10, minutes=15, seconds=30), # hours, minutes, seconds timedelta(days=4, minutes=15, seconds=30), # multiple days timedelta(days=1, minutes=00, seconds=00), # single day timedelta(days=-4, minutes=15, seconds=30), # negative durations timedelta(minutes=15, seconds=30), # minute & seconds timedelta(seconds=30), # seconds ] for delta in timedeltas: with self.subTest(delta=delta): self.assertEqual(parse_duration(format(delta)), delta) def test_parse_postgresql_format(self): test_values = ( ('1 day', timedelta(1)), ('1 day 0:00:01', timedelta(days=1, seconds=1)), ('1 day -0:00:01', timedelta(days=1, seconds=-1)), ('-1 day -0:00:01', timedelta(days=-1, seconds=-1)), ('-1 day +0:00:01', timedelta(days=-1, seconds=1)), ('4 days 0:15:30.1', timedelta(days=4, minutes=15, seconds=30, milliseconds=100)), ('4 days 0:15:30.0001', timedelta(days=4, minutes=15, seconds=30, microseconds=100)), ('-4 days -15:00:30', timedelta(days=-4, hours=-15, seconds=-30)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_seconds(self): self.assertEqual(parse_duration('30'), timedelta(seconds=30)) def test_minutes_seconds(self): self.assertEqual(parse_duration('15:30'), timedelta(minutes=15, seconds=30)) self.assertEqual(parse_duration('5:30'), timedelta(minutes=5, seconds=30)) def test_hours_minutes_seconds(self): self.assertEqual(parse_duration('10:15:30'), timedelta(hours=10, minutes=15, seconds=30)) self.assertEqual(parse_duration('1:15:30'), timedelta(hours=1, minutes=15, seconds=30)) self.assertEqual(parse_duration('100:200:300'), timedelta(hours=100, minutes=200, seconds=300)) def test_days(self): self.assertEqual(parse_duration('4 15:30'), timedelta(days=4, minutes=15, seconds=30)) self.assertEqual(parse_duration('4 10:15:30'), timedelta(days=4, hours=10, minutes=15, seconds=30)) def test_fractions_of_seconds(self): test_values = ( ('15:30.1', timedelta(minutes=15, seconds=30, milliseconds=100)), ('15:30.01', timedelta(minutes=15, seconds=30, milliseconds=10)), ('15:30.001', timedelta(minutes=15, seconds=30, milliseconds=1)), ('15:30.0001', timedelta(minutes=15, seconds=30, microseconds=100)), ('15:30.00001', timedelta(minutes=15, seconds=30, microseconds=10)), ('15:30.000001', timedelta(minutes=15, seconds=30, microseconds=1)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_negative(self): test_values = ( ('-4 15:30', timedelta(days=-4, minutes=15, seconds=30)), ('-172800', timedelta(days=-2)), ('-15:30', timedelta(minutes=-15, seconds=30)), ('-1:15:30', timedelta(hours=-1, minutes=15, seconds=30)), ('-30.1', timedelta(seconds=-30, milliseconds=-100)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected) def test_iso_8601(self): test_values = ( ('P4Y', None), ('P4M', None), ('P4W', None), ('P4D', timedelta(days=4)), ('P0.5D', timedelta(hours=12)), ('PT5H', timedelta(hours=5)), ('PT5M', timedelta(minutes=5)), ('PT5S', timedelta(seconds=5)), ('PT0.000005S', timedelta(microseconds=5)), ) for source, expected in test_values: with self.subTest(source=source): self.assertEqual(parse_duration(source), expected)
40dfdd6694373dece89c35680f306e35554a3d27daedd6f4d1fa74a4daaab7cc
import os from datetime import datetime from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, json_script, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe class TestUtilsHtml(SimpleTestCase): def check_output(self, function, value, output=None): """ function(value) equals output. If output is None, function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output) def test_escape(self): items = ( ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ('"', '&quot;'), ("'", '&#39;'), ) # Substitution patterns for testing the above items. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb") for value, output in items: with self.subTest(value=value, output=output): for pattern in patterns: with self.subTest(value=value, output=output, pattern=pattern): self.check_output(escape, pattern % value, pattern % output) self.check_output(escape, lazystr(pattern % value), pattern % output) # Check repeated values. self.check_output(escape, value * 2, output * 2) # Verify it doesn't double replace &. self.check_output(escape, '<&', '&lt;&amp;') def test_format_html(self): self.assertEqual( format_html( "{} {} {third} {fourth}", "< Dangerous >", mark_safe("<b>safe</b>"), third="< dangerous again", fourth=mark_safe("<i>safe again</i>"), ), "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>" ) def test_linebreaks(self): items = ( ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"), ("para1\nsub1\rsub2\n\npara2", "<p>para1<br>sub1<br>sub2</p>\n\n<p>para2</p>"), ("para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br>sub1</p>\n\n<p>para4</p>"), ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(linebreaks, value, output) self.check_output(linebreaks, lazystr(value), output) def test_strip_tags(self): items = ( ('<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>', 'See: &#39;&eacute; is an apostrophe followed by e acute'), ('<adf>a', 'a'), ('</adf>a', 'a'), ('<asdf><asdf>e', 'e'), ('hi, <f x', 'hi, <f x'), ('234<235, right?', '234<235, right?'), ('a4<a5 right?', 'a4<a5 right?'), ('b7>b2!', 'b7>b2!'), ('</fe', '</fe'), ('<x>b<y>', 'b'), ('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'), ('a<p a >b</p>c', 'abc'), ('d<a:b c:d>e</p>f', 'def'), ('<strong>foo</strong><a href="http://example.com">bar</a>', 'foobar'), # caused infinite loop on Pythons not patched with # http://bugs.python.org/issue20288 ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_tags, value, output) self.check_output(strip_tags, lazystr(value), output) def test_strip_tags_files(self): # Test with more lengthy content (also catching performance regressions) for filename in ('strip_tags1.html', 'strip_tags2.txt'): with self.subTest(filename=filename): path = os.path.join(os.path.dirname(__file__), 'files', filename) with open(path, 'r') as fp: content = fp.read() start = datetime.now() stripped = strip_tags(content) elapsed = datetime.now() - start self.assertEqual(elapsed.seconds, 0) self.assertIn("Please try again.", stripped) self.assertNotIn('<', stripped) def test_strip_spaces_between_tags(self): # Strings that should come out untouched. items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>') for value in items: with self.subTest(value=value): self.check_output(strip_spaces_between_tags, value) self.check_output(strip_spaces_between_tags, lazystr(value)) # Strings that have spaces to strip. items = ( ('<d> </d>', '<d></d>'), ('<p>hello </p>\n<p> world</p>', '<p>hello </p><p> world</p>'), ('\n<p>\t</p>\n<p> </p>\n', '\n<p></p><p></p>\n'), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(strip_spaces_between_tags, value, output) self.check_output(strip_spaces_between_tags, lazystr(value), output) def test_escapejs(self): items = ( ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'), (r'\ : backslashes, too', '\\u005C : backslashes, too'), ( 'and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008' ), (r'<script>and this</script>', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'), ( 'paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028' ), ('`', '\\u0060'), ) for value, output in items: with self.subTest(value=value, output=output): self.check_output(escapejs, value, output) self.check_output(escapejs, lazystr(value), output) def test_json_script(self): tests = ( # "<", ">" and "&" are quoted inside JSON strings (('&<>', '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>')), # "<", ">" and "&" are quoted inside JSON objects ( {'a': '<script>test&ing</script>'}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>' ), # Lazy strings are quoted (lazystr('&<>'), '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>'), ( {'a': lazystr('<script>test&ing</script>')}, '<script id="test_id" type="application/json">' '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>' ), ) for arg, expected in tests: with self.subTest(arg=arg): self.assertEqual(json_script(arg, 'test_id'), expected) def test_smart_urlquote(self): items = ( ('http://öäü.com/', 'http://xn--4ca9at.com/'), ('http://öäü.com/öäü/', 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/'), # Everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered # safe as per RFC. ('http://example.com/path/öäü/', 'http://example.com/path/%C3%B6%C3%A4%C3%BC/'), ('http://example.com/%C3%B6/ä/', 'http://example.com/%C3%B6/%C3%A4/'), ('http://example.com/?x=1&y=2+3&z=', 'http://example.com/?x=1&y=2+3&z='), ('http://example.com/?x=<>"\'', 'http://example.com/?x=%3C%3E%22%27'), ('http://example.com/?q=http://example.com/?x=1%26q=django', 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'), ('http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango', 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'), ) # IDNs are properly quoted for value, output in items: with self.subTest(value=value, output=output): self.assertEqual(smart_urlquote(value), output) def test_conditional_escape(self): s = '<h1>interop</h1>' self.assertEqual(conditional_escape(s), '&lt;h1&gt;interop&lt;/h1&gt;') self.assertEqual(conditional_escape(mark_safe(s)), s) self.assertEqual(conditional_escape(lazystr(mark_safe(s))), s) def test_html_safe(self): @html_safe class HtmlClass: def __str__(self): return "<h1>I'm a html class!</h1>" html_obj = HtmlClass() self.assertTrue(hasattr(HtmlClass, '__html__')) self.assertTrue(hasattr(html_obj, '__html__')) self.assertEqual(str(html_obj), html_obj.__html__()) def test_html_safe_subclass(self): class BaseClass: def __html__(self): # defines __html__ on its own return 'some html content' def __str__(self): return 'some non html content' @html_safe class Subclass(BaseClass): def __str__(self): # overrides __str__ and is marked as html_safe return 'some html safe content' subclass_obj = Subclass() self.assertEqual(str(subclass_obj), subclass_obj.__html__()) def test_html_safe_defines_html_error(self): msg = "can't apply @html_safe to HtmlClass because it defines __html__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: def __html__(self): return "<h1>I'm a html class!</h1>" def test_html_safe_doesnt_define_str(self): msg = "can't apply @html_safe to HtmlClass because it doesn't define __str__()." with self.assertRaisesMessage(ValueError, msg): @html_safe class HtmlClass: pass def test_urlize(self): tests = ( ( 'Search for google.com/?q=! and see.', 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and see.' ), ( lazystr('Search for google.com/?q=!'), 'Search for <a href="http://google.com/?q=">google.com/?q=</a>!' ), ('[email protected]', '<a href="mailto:[email protected]">[email protected]</a>'), ) for value, output in tests: with self.subTest(value=value): self.assertEqual(urlize(value), output) def test_urlize_unchanged_inputs(self): tests = ( ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test ('a' + '.' * 1000000) + 'a', # trailing_punctuation catastrophic test 'foo@', '@foo.com', '[email protected]', 'foo@localhost', 'foo@localhost.', ) for value in tests: with self.subTest(value=value): self.assertEqual(urlize(value), value)
e9cb432b28b4e3073c958639ea4ed3aaf8d641e11e9634bc44eb7e00c548e167
import copy import unittest from django.utils.tree import Node class NodeTests(unittest.TestCase): def setUp(self): self.node1_children = [('a', 1), ('b', 2)] self.node1 = Node(self.node1_children) self.node2 = Node() def test_str(self): self.assertEqual(str(self.node1), "(DEFAULT: ('a', 1), ('b', 2))") self.assertEqual(str(self.node2), "(DEFAULT: )") def test_repr(self): self.assertEqual(repr(self.node1), "<Node: (DEFAULT: ('a', 1), ('b', 2))>") self.assertEqual(repr(self.node2), "<Node: (DEFAULT: )>") def test_hash(self): node3 = Node(self.node1_children, negated=True) node4 = Node(self.node1_children, connector='OTHER') node5 = Node(self.node1_children) self.assertNotEqual(hash(self.node1), hash(self.node2)) self.assertNotEqual(hash(self.node1), hash(node3)) self.assertNotEqual(hash(self.node1), hash(node4)) self.assertEqual(hash(self.node1), hash(node5)) self.assertEqual(hash(self.node2), hash(Node())) def test_len(self): self.assertEqual(len(self.node1), 2) self.assertEqual(len(self.node2), 0) def test_bool(self): self.assertTrue(self.node1) self.assertFalse(self.node2) def test_contains(self): self.assertIn(('a', 1), self.node1) self.assertNotIn(('a', 1), self.node2) def test_add(self): # start with the same children of node1 then add an item node3 = Node(self.node1_children) node3_added_child = ('c', 3) # add() returns the added data self.assertEqual(node3.add(node3_added_child, Node.default), node3_added_child) # we added exactly one item, len() should reflect that self.assertEqual(len(self.node1) + 1, len(node3)) self.assertEqual(str(node3), "(DEFAULT: ('a', 1), ('b', 2), ('c', 3))") def test_negate(self): # negated is False by default self.assertFalse(self.node1.negated) self.node1.negate() self.assertTrue(self.node1.negated) self.node1.negate() self.assertFalse(self.node1.negated) def test_deepcopy(self): node4 = copy.copy(self.node1) node5 = copy.deepcopy(self.node1) self.assertIs(self.node1.children, node4.children) self.assertIsNot(self.node1.children, node5.children) def test_eq_children(self): node = Node(self.node1_children) self.assertEqual(node, self.node1) self.assertNotEqual(node, self.node2) def test_eq_connector(self): new_node = Node(connector='NEW') default_node = Node(connector='DEFAULT') self.assertEqual(default_node, self.node2) self.assertNotEqual(default_node, new_node) def test_eq_negated(self): node = Node(negated=False) negated = Node(negated=True) self.assertNotEqual(negated, node)
5a65377b365401438e90c3a21d85c4dd79202d36452f8080a2f1ecc6c9f806d9
# Used to test for modules which don't have submodules.
1b3673246186e13645e90e345aec1b01ade72d8c606ec30617b2f77ede23ceb0
from django.template import Context, Template from django.test import SimpleTestCase from django.utils import html, text from django.utils.functional import lazy, lazystr from django.utils.safestring import SafeData, mark_safe class customescape(str): def __html__(self): # implement specific and obviously wrong escaping # in order to be able to tell for sure when it runs return self.replace('<', '<<').replace('>', '>>') class SafeStringTest(SimpleTestCase): def assertRenderEqual(self, tpl, expected, **context): context = Context(context) tpl = Template(tpl) self.assertEqual(tpl.render(context), expected) def test_mark_safe(self): s = mark_safe('a&b') self.assertRenderEqual('{{ s }}', 'a&b', s=s) self.assertRenderEqual('{{ s|force_escape }}', 'a&amp;b', s=s) def test_mark_safe_str(self): """ Calling str() on a SafeText instance doesn't lose the safe status. """ s = mark_safe('a&b') self.assertIsInstance(str(s), type(s)) def test_mark_safe_object_implementing_dunder_html(self): e = customescape('<a&b>') s = mark_safe(e) self.assertIs(s, e) self.assertRenderEqual('{{ s }}', '<<a&b>>', s=s) self.assertRenderEqual('{{ s|force_escape }}', '&lt;a&amp;b&gt;', s=s) def test_mark_safe_lazy(self): s = lazystr('a&b') self.assertIsInstance(mark_safe(s), SafeData) self.assertRenderEqual('{{ s }}', 'a&b', s=mark_safe(s)) def test_mark_safe_object_implementing_dunder_str(self): class Obj: def __str__(self): return '<obj>' s = mark_safe(Obj()) self.assertRenderEqual('{{ s }}', '<obj>', s=s) def test_mark_safe_result_implements_dunder_html(self): self.assertEqual(mark_safe('a&b').__html__(), 'a&b') def test_mark_safe_lazy_result_implements_dunder_html(self): self.assertEqual(mark_safe(lazystr('a&b')).__html__(), 'a&b') def test_add_lazy_safe_text_and_safe_text(self): s = html.escape(lazystr('a')) s += mark_safe('&b') self.assertRenderEqual('{{ s }}', 'a&b', s=s) s = html.escapejs(lazystr('a')) s += mark_safe('&b') self.assertRenderEqual('{{ s }}', 'a&b', s=s) s = text.slugify(lazystr('a')) s += mark_safe('&b') self.assertRenderEqual('{{ s }}', 'a&b', s=s) def test_mark_safe_as_decorator(self): """ mark_safe used as a decorator leaves the result of a function unchanged. """ def clean_string_provider(): return '<html><body>dummy</body></html>' self.assertEqual(mark_safe(clean_string_provider)(), clean_string_provider()) def test_mark_safe_decorator_does_not_affect_dunder_html(self): """ mark_safe doesn't affect a callable that has an __html__() method. """ class SafeStringContainer: def __html__(self): return '<html></html>' self.assertIs(mark_safe(SafeStringContainer), SafeStringContainer) def test_mark_safe_decorator_does_not_affect_promises(self): """ mark_safe doesn't affect lazy strings (Promise objects). """ def html_str(): return '<html></html>' lazy_str = lazy(html_str, str)() self.assertEqual(mark_safe(lazy_str), html_str())
dc28870f4404cd63554b8658ddbf314f970f9bb014ec368894231136630bd929
from decimal import Decimal from sys import float_info from unittest import TestCase from django.utils.numberformat import format as nformat class TestNumberFormat(TestCase): def test_format_number(self): self.assertEqual(nformat(1234, '.'), '1234') self.assertEqual(nformat(1234.2, '.'), '1234.2') self.assertEqual(nformat(1234, '.', decimal_pos=2), '1234.00') self.assertEqual(nformat(1234, '.', grouping=2, thousand_sep=','), '1234') self.assertEqual(nformat(1234, '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34') self.assertEqual(nformat(-1234.33, '.', decimal_pos=1), '-1234.3') def test_format_string(self): self.assertEqual(nformat('1234', '.'), '1234') self.assertEqual(nformat('1234.2', '.'), '1234.2') self.assertEqual(nformat('1234', '.', decimal_pos=2), '1234.00') self.assertEqual(nformat('1234', '.', grouping=2, thousand_sep=','), '1234') self.assertEqual(nformat('1234', '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34') self.assertEqual(nformat('-1234.33', '.', decimal_pos=1), '-1234.3') self.assertEqual(nformat('10000', '.', grouping=3, thousand_sep='comma', force_grouping=True), '10comma000') def test_large_number(self): most_max = ( '{}179769313486231570814527423731704356798070567525844996' '598917476803157260780028538760589558632766878171540458953' '514382464234321326889464182768467546703537516986049910576' '551282076245490090389328944075868508455133942304583236903' '222948165808559332123348274797826204144723168738177180919' '29988125040402618412485836{}' ) most_max2 = ( '{}35953862697246314162905484746340871359614113505168999' '31978349536063145215600570775211791172655337563430809179' '07028764928468642653778928365536935093407075033972099821' '15310256415249098018077865788815173701691026788460916647' '38064458963316171186642466965495956524082894463374763543' '61838599762500808052368249716736' ) int_max = int(float_info.max) self.assertEqual(nformat(int_max, '.'), most_max.format('', '8')) self.assertEqual(nformat(int_max + 1, '.'), most_max.format('', '9')) self.assertEqual(nformat(int_max * 2, '.'), most_max2.format('')) self.assertEqual(nformat(0 - int_max, '.'), most_max.format('-', '8')) self.assertEqual(nformat(-1 - int_max, '.'), most_max.format('-', '9')) self.assertEqual(nformat(-2 * int_max, '.'), most_max2.format('-')) def test_float_numbers(self): # A float without a fractional part (3.) results in a ".0" when no # deimal_pos is given. Contrast that with the Decimal('3.') case in # test_decimal_numbers which doesn't return a fractional part. self.assertEqual(nformat(3., '.'), '3.0') def test_decimal_numbers(self): self.assertEqual(nformat(Decimal('1234'), '.'), '1234') self.assertEqual(nformat(Decimal('1234.2'), '.'), '1234.2') self.assertEqual(nformat(Decimal('1234'), '.', decimal_pos=2), '1234.00') self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=','), '1234') self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34') self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3') self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.00000001') self.assertEqual(nformat(Decimal('9e-19'), '.', decimal_pos=2), '0.00') self.assertEqual(nformat(Decimal('.00000000000099'), '.', decimal_pos=0), '0') self.assertEqual( nformat(Decimal('1e16'), '.', thousand_sep=',', grouping=3, force_grouping=True), '10,000,000,000,000,000' ) self.assertEqual( nformat(Decimal('1e16'), '.', decimal_pos=2, thousand_sep=',', grouping=3, force_grouping=True), '10,000,000,000,000,000.00' ) self.assertEqual(nformat(Decimal('3.'), '.'), '3') self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0') def test_decimal_subclass(self): class EuroDecimal(Decimal): """ Wrapper for Decimal which prefixes each amount with the € symbol. """ def __format__(self, specifier, **kwargs): amount = super().__format__(specifier, **kwargs) return '€ {}'.format(amount) price = EuroDecimal('1.23') self.assertEqual(nformat(price, ','), '€ 1,23')
2965342d6f9425b841f75269410f433cc5af30b012bb0184979cefaf2b8aadeb
import unittest from django.utils.functional import cached_property, lazy class FunctionalTestCase(unittest.TestCase): def test_lazy(self): t = lazy(lambda: tuple(range(3)), list, tuple) for a, b in zip(t(), range(3)): self.assertEqual(a, b) def test_lazy_base_class(self): """lazy also finds base class methods in the proxy object""" class Base: def base_method(self): pass class Klazz(Base): pass t = lazy(lambda: Klazz(), Klazz)() self.assertIn('base_method', dir(t)) def test_lazy_base_class_override(self): """lazy finds the correct (overridden) method implementation""" class Base: def method(self): return 'Base' class Klazz(Base): def method(self): return 'Klazz' t = lazy(lambda: Klazz(), Base)() self.assertEqual(t.method(), 'Klazz') def test_lazy_object_to_string(self): class Klazz: def __str__(self): return "Î am ā Ǩlâzz." def __bytes__(self): return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz." t = lazy(lambda: Klazz(), Klazz)() self.assertEqual(str(t), "Î am ā Ǩlâzz.") self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.") def test_cached_property(self): """ cached_property caches its value and that it behaves like a property """ class A: @cached_property def value(self): """Here is the docstring...""" return 1, object() def other_value(self): return 1 other = cached_property(other_value, name='other') # docstring should be preserved self.assertEqual(A.value.__doc__, "Here is the docstring...") a = A() # check that it is cached self.assertEqual(a.value, a.value) # check that it returns the right thing self.assertEqual(a.value[0], 1) # check that state isn't shared between instances a2 = A() self.assertNotEqual(a.value, a2.value) # check that it behaves like a property when there's no instance self.assertIsInstance(A.value, cached_property) # check that overriding name works self.assertEqual(a.other, 1) self.assertTrue(callable(a.other_value)) def test_lazy_equality(self): """ == and != work correctly for Promises. """ lazy_a = lazy(lambda: 4, int) lazy_b = lazy(lambda: 4, int) lazy_c = lazy(lambda: 5, int) self.assertEqual(lazy_a(), lazy_b()) self.assertNotEqual(lazy_b(), lazy_c()) def test_lazy_repr_text(self): original_object = 'Lazy translation text' lazy_obj = lazy(lambda: original_object, str) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_int(self): original_object = 15 lazy_obj = lazy(lambda: original_object, int) self.assertEqual(repr(original_object), repr(lazy_obj())) def test_lazy_repr_bytes(self): original_object = b'J\xc3\xbcst a str\xc3\xadng' lazy_obj = lazy(lambda: original_object, bytes) self.assertEqual(repr(original_object), repr(lazy_obj()))
2bb116ecd5cf8efc50a73c00903329874f42938a5f6270e2a3b6a45ce2cce1c1
import hashlib import unittest from django.utils.crypto import constant_time_compare, pbkdf2 class TestUtilsCryptoMisc(unittest.TestCase): def test_constant_time_compare(self): # It's hard to test for constant time, just test the result. self.assertTrue(constant_time_compare(b'spam', b'spam')) self.assertFalse(constant_time_compare(b'spam', b'eggs')) self.assertTrue(constant_time_compare('spam', 'spam')) self.assertFalse(constant_time_compare('spam', 'eggs')) class TestUtilsCryptoPBKDF2(unittest.TestCase): # http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06 rfc_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": "0c60c80f961f0e71f3a9b524af6012062fe037a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 2, "dklen": 20, "digest": hashlib.sha1, }, "result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957", }, { "args": { "password": "password", "salt": "salt", "iterations": 4096, "dklen": 20, "digest": hashlib.sha1, }, "result": "4b007901b765489abead49d926f721d065a429c1", }, # # this takes way too long :( # { # "args": { # "password": "password", # "salt": "salt", # "iterations": 16777216, # "dklen": 20, # "digest": hashlib.sha1, # }, # "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984", # }, { "args": { "password": "passwordPASSWORDpassword", "salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt", "iterations": 4096, "dklen": 25, "digest": hashlib.sha1, }, "result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038", }, { "args": { "password": "pass\0word", "salt": "sa\0lt", "iterations": 4096, "dklen": 16, "digest": hashlib.sha1, }, "result": "56fa6aa75548099dcc37d7f03425e0c3", }, ] regression_vectors = [ { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha256, }, "result": "120fb6cffcf8b32c43e7225256c4f837a86548c9", }, { "args": { "password": "password", "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha512, }, "result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6", }, { "args": { "password": "password", "salt": "salt", "iterations": 1000, "dklen": 0, "digest": hashlib.sha512, }, "result": ("afe6c5530785b6cc6b1c6453384731bd5ee432ee" "549fd42fb6695779ad8a1c5bf59de69c48f774ef" "c4007d5298f9033c0241d5ab69305e7b64eceeb8d" "834cfec"), }, # Check leading zeros are not stripped (#17481) { "args": { "password": b'\xba', "salt": "salt", "iterations": 1, "dklen": 20, "digest": hashlib.sha1, }, "result": '0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b', }, ] def test_public_vectors(self): for vector in self.rfc_vectors: result = pbkdf2(**vector['args']) self.assertEqual(result.hex(), vector['result']) def test_regression_vectors(self): for vector in self.regression_vectors: result = pbkdf2(**vector['args']) self.assertEqual(result.hex(), vector['result']) def test_default_hmac_alg(self): kwargs = {'password': b'password', 'salt': b'salt', 'iterations': 1, 'dklen': 20} self.assertEqual(pbkdf2(**kwargs), hashlib.pbkdf2_hmac(hash_name=hashlib.sha256().name, **kwargs))
29e5712c02b23d78b0c0e1631b5405c8be4cf3a167f574db854d2f546c3cf201
import gettext import os import shutil import tempfile from importlib import import_module from unittest import mock import _thread from django import conf from django.contrib import admin from django.test import SimpleTestCase, override_settings from django.test.utils import extend_sys_path from django.utils import autoreload from django.utils.translation import trans_real LOCALE_PATH = os.path.join(os.path.dirname(__file__), 'locale') class TestFilenameGenerator(SimpleTestCase): def clear_autoreload_caches(self): autoreload._cached_modules = set() autoreload._cached_filenames = [] def assertFileFound(self, filename): self.clear_autoreload_caches() # Test uncached access self.assertIn(filename, autoreload.gen_filenames()) # Test cached access self.assertIn(filename, autoreload.gen_filenames()) def assertFileNotFound(self, filename): self.clear_autoreload_caches() # Test uncached access self.assertNotIn(filename, autoreload.gen_filenames()) # Test cached access self.assertNotIn(filename, autoreload.gen_filenames()) def assertFileFoundOnlyNew(self, filename): self.clear_autoreload_caches() # Test uncached access self.assertIn(filename, autoreload.gen_filenames(only_new=True)) # Test cached access self.assertNotIn(filename, autoreload.gen_filenames(only_new=True)) def test_django_locales(self): """ gen_filenames() yields the built-in Django locale files. """ django_dir = os.path.join(os.path.dirname(conf.__file__), 'locale') django_mo = os.path.join(django_dir, 'nl', 'LC_MESSAGES', 'django.mo') self.assertFileFound(django_mo) @override_settings(LOCALE_PATHS=[LOCALE_PATH]) def test_locale_paths_setting(self): """ gen_filenames also yields from LOCALE_PATHS locales. """ locale_paths_mo = os.path.join(LOCALE_PATH, 'nl', 'LC_MESSAGES', 'django.mo') self.assertFileFound(locale_paths_mo) @override_settings(INSTALLED_APPS=[]) def test_project_root_locale(self): """ gen_filenames() also yields from the current directory (project root). """ old_cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) current_dir = os.path.join(os.path.dirname(__file__), 'locale') current_dir_mo = os.path.join(current_dir, 'nl', 'LC_MESSAGES', 'django.mo') try: self.assertFileFound(current_dir_mo) finally: os.chdir(old_cwd) @override_settings(INSTALLED_APPS=['django.contrib.admin']) def test_app_locales(self): """ gen_filenames() also yields from locale dirs in installed apps. """ admin_dir = os.path.join(os.path.dirname(admin.__file__), 'locale') admin_mo = os.path.join(admin_dir, 'nl', 'LC_MESSAGES', 'django.mo') self.assertFileFound(admin_mo) @override_settings(USE_I18N=False) def test_no_i18n(self): """ If i18n machinery is disabled, there is no need for watching the locale files. """ django_dir = os.path.join(os.path.dirname(conf.__file__), 'locale') django_mo = os.path.join(django_dir, 'nl', 'LC_MESSAGES', 'django.mo') self.assertFileNotFound(django_mo) def test_paths_are_native_strings(self): for filename in autoreload.gen_filenames(): self.assertIsInstance(filename, str) def test_only_new_files(self): """ When calling a second time gen_filenames with only_new = True, only files from newly loaded modules should be given. """ dirname = tempfile.mkdtemp() filename = os.path.join(dirname, 'test_only_new_module.py') self.addCleanup(shutil.rmtree, dirname) with open(filename, 'w'): pass # Test uncached access self.clear_autoreload_caches() filenames = set(autoreload.gen_filenames(only_new=True)) filenames_reference = set(autoreload.gen_filenames()) self.assertEqual(filenames, filenames_reference) # Test cached access: no changes filenames = set(autoreload.gen_filenames(only_new=True)) self.assertEqual(filenames, set()) # Test cached access: add a module with extend_sys_path(dirname): import_module('test_only_new_module') filenames = set(autoreload.gen_filenames(only_new=True)) self.assertEqual(filenames, {filename}) def test_deleted_removed(self): """ When a file is deleted, gen_filenames() no longer returns it. """ dirname = tempfile.mkdtemp() filename = os.path.join(dirname, 'test_deleted_removed_module.py') self.addCleanup(shutil.rmtree, dirname) with open(filename, 'w'): pass with extend_sys_path(dirname): import_module('test_deleted_removed_module') self.assertFileFound(filename) os.unlink(filename) self.assertFileNotFound(filename) def test_check_errors(self): """ When a file containing an error is imported in a function wrapped by check_errors(), gen_filenames() returns it. """ dirname = tempfile.mkdtemp() filename = os.path.join(dirname, 'test_syntax_error.py') self.addCleanup(shutil.rmtree, dirname) with open(filename, 'w') as f: f.write("Ceci n'est pas du Python.") with extend_sys_path(dirname): with self.assertRaises(SyntaxError): autoreload.check_errors(import_module)('test_syntax_error') self.assertFileFound(filename) def test_check_errors_only_new(self): """ When a file containing an error is imported in a function wrapped by check_errors(), gen_filenames(only_new=True) returns it. """ dirname = tempfile.mkdtemp() filename = os.path.join(dirname, 'test_syntax_error.py') self.addCleanup(shutil.rmtree, dirname) with open(filename, 'w') as f: f.write("Ceci n'est pas du Python.") with extend_sys_path(dirname): with self.assertRaises(SyntaxError): autoreload.check_errors(import_module)('test_syntax_error') self.assertFileFoundOnlyNew(filename) def test_check_errors_catches_all_exceptions(self): """ Since Python may raise arbitrary exceptions when importing code, check_errors() must catch Exception, not just some subclasses. """ dirname = tempfile.mkdtemp() filename = os.path.join(dirname, 'test_exception.py') self.addCleanup(shutil.rmtree, dirname) with open(filename, 'w') as f: f.write("raise Exception") with extend_sys_path(dirname): with self.assertRaises(Exception): autoreload.check_errors(import_module)('test_exception') self.assertFileFound(filename) class CleanFilesTests(SimpleTestCase): TEST_MAP = { # description: (input_file_list, expected_returned_file_list) 'falsies': ([None, False], []), 'pycs': (['myfile.pyc'], ['myfile.py']), 'pyos': (['myfile.pyo'], ['myfile.py']), '$py.class': (['myclass$py.class'], ['myclass.py']), 'combined': ( [None, 'file1.pyo', 'file2.pyc', 'myclass$py.class'], ['file1.py', 'file2.py', 'myclass.py'], ) } def _run_tests(self, mock_files_exist=True): with mock.patch('django.utils.autoreload.os.path.exists', return_value=mock_files_exist): for description, values in self.TEST_MAP.items(): filenames, expected_returned_filenames = values self.assertEqual( autoreload.clean_files(filenames), expected_returned_filenames if mock_files_exist else [], msg='{} failed for input file list: {}; returned file list: {}'.format( description, filenames, expected_returned_filenames ), ) def test_files_exist(self): """ If the file exists, any compiled files (pyc, pyo, $py.class) are transformed as their source files. """ self._run_tests() def test_files_do_not_exist(self): """ If the files don't exist, they aren't in the returned file list. """ self._run_tests(mock_files_exist=False) class ResetTranslationsTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext._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_resets_gettext(self): gettext._translations = {'foo': 'bar'} autoreload.reset_translations() self.assertEqual(gettext._translations, {}) def test_resets_trans_real(self): trans_real._translations = {'foo': 'bar'} trans_real._default = 1 trans_real._active = False autoreload.reset_translations() self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, _thread._local) class RestartWithReloaderTests(SimpleTestCase): executable = '/usr/bin/python' def patch_autoreload(self, argv): patch_call = mock.patch('django.utils.autoreload.subprocess.call', return_value=0) patches = [ mock.patch('django.utils.autoreload.sys.argv', argv), mock.patch('django.utils.autoreload.sys.executable', self.executable), mock.patch('django.utils.autoreload.sys.warnoptions', ['all']), ] for p in patches: p.start() self.addCleanup(p.stop) mock_call = patch_call.start() self.addCleanup(patch_call.stop) return mock_call def test_manage_py(self): argv = ['./manage.py', 'runserver'] mock_call = self.patch_autoreload(argv) autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual(mock_call.call_args[0][0], [self.executable, '-Wall'] + argv) def test_python_m_django(self): main = '/usr/lib/pythonX.Y/site-packages/django/__main__.py' argv = [main, 'runserver'] mock_call = self.patch_autoreload(argv) with mock.patch('django.__main__.__file__', main): autoreload.restart_with_reloader() self.assertEqual(mock_call.call_count, 1) self.assertEqual(mock_call.call_args[0][0], [self.executable, '-Wall', '-m', 'django'] + argv[1:])
f5b74cfbd0d4cf126156eeba2c462ec07af9e9b9ea345327d960ce8858a2d374
import unittest from datetime import ( date as original_date, datetime as original_datetime, time as original_time, ) from django.utils.datetime_safe import date, datetime, time class DatetimeTests(unittest.TestCase): def setUp(self): self.just_safe = (1900, 1, 1) self.just_unsafe = (1899, 12, 31, 23, 59, 59) self.just_time = (11, 30, 59) self.really_old = (20, 1, 1) self.more_recent = (2006, 1, 1) def test_compare_datetimes(self): self.assertEqual(original_datetime(*self.more_recent), datetime(*self.more_recent)) self.assertEqual(original_datetime(*self.really_old), datetime(*self.really_old)) self.assertEqual(original_date(*self.more_recent), date(*self.more_recent)) self.assertEqual(original_date(*self.really_old), date(*self.really_old)) self.assertEqual( original_date(*self.just_safe).strftime('%Y-%m-%d'), date(*self.just_safe).strftime('%Y-%m-%d') ) self.assertEqual( original_datetime(*self.just_safe).strftime('%Y-%m-%d'), datetime(*self.just_safe).strftime('%Y-%m-%d') ) self.assertEqual( original_time(*self.just_time).strftime('%H:%M:%S'), time(*self.just_time).strftime('%H:%M:%S') ) def test_safe_strftime(self): self.assertEqual(date(*self.just_unsafe[:3]).strftime('%Y-%m-%d (weekday %w)'), '1899-12-31 (weekday 0)') self.assertEqual(date(*self.just_safe).strftime('%Y-%m-%d (weekday %w)'), '1900-01-01 (weekday 1)') self.assertEqual( datetime(*self.just_unsafe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1899-12-31 23:59:59 (weekday 0)' ) self.assertEqual( datetime(*self.just_safe).strftime('%Y-%m-%d %H:%M:%S (weekday %w)'), '1900-01-01 00:00:00 (weekday 1)' ) self.assertEqual(time(*self.just_time).strftime('%H:%M:%S AM'), '11:30:59 AM') # %y will error before this date self.assertEqual(date(*self.just_safe).strftime('%y'), '00') self.assertEqual(datetime(*self.just_safe).strftime('%y'), '00') self.assertEqual(date(1850, 8, 2).strftime("%Y/%m/%d was a %A"), '1850/08/02 was a Friday') def test_zero_padding(self): """ Regression for #12524 Pre-1000AD dates are padded with zeros if necessary """ self.assertEqual(date(1, 1, 1).strftime("%Y/%m/%d was a %A"), '0001/01/01 was a Monday')
103bc559a647c80afa0801efa656beef5fb38f401c708ffd71eb62c2a8ef29de
import unittest from django.utils.ipv6 import clean_ipv6_address, is_valid_ipv6_address class TestUtilsIPv6(unittest.TestCase): def test_validates_correct_plain_address(self): self.assertTrue(is_valid_ipv6_address('fe80::223:6cff:fe8a:2e8a')) self.assertTrue(is_valid_ipv6_address('2a02::223:6cff:fe8a:2e8a')) self.assertTrue(is_valid_ipv6_address('1::2:3:4:5:6:7')) self.assertTrue(is_valid_ipv6_address('::')) self.assertTrue(is_valid_ipv6_address('::a')) self.assertTrue(is_valid_ipv6_address('2::')) def test_validates_correct_with_v4mapping(self): self.assertTrue(is_valid_ipv6_address('::ffff:254.42.16.14')) self.assertTrue(is_valid_ipv6_address('::ffff:0a0a:0a0a')) def test_validates_incorrect_plain_address(self): self.assertFalse(is_valid_ipv6_address('foo')) self.assertFalse(is_valid_ipv6_address('127.0.0.1')) self.assertFalse(is_valid_ipv6_address('12345::')) self.assertFalse(is_valid_ipv6_address('1::2:3::4')) self.assertFalse(is_valid_ipv6_address('1::zzz')) self.assertFalse(is_valid_ipv6_address('1::2:3:4:5:6:7:8')) self.assertFalse(is_valid_ipv6_address('1:2')) self.assertFalse(is_valid_ipv6_address('1:::2')) self.assertFalse(is_valid_ipv6_address('fe80::223: 6cff:fe8a:2e8a')) self.assertFalse(is_valid_ipv6_address('2a02::223:6cff :fe8a:2e8a')) def test_validates_incorrect_with_v4mapping(self): self.assertFalse(is_valid_ipv6_address('::ffff:999.42.16.14')) self.assertFalse(is_valid_ipv6_address('::ffff:zzzz:0a0a')) # The ::1.2.3.4 format used to be valid but was deprecated # in rfc4291 section 2.5.5.1 self.assertTrue(is_valid_ipv6_address('::254.42.16.14')) self.assertTrue(is_valid_ipv6_address('::0a0a:0a0a')) self.assertFalse(is_valid_ipv6_address('::999.42.16.14')) self.assertFalse(is_valid_ipv6_address('::zzzz:0a0a')) def test_cleans_plain_address(self): self.assertEqual(clean_ipv6_address('DEAD::0:BEEF'), 'dead::beef') self.assertEqual(clean_ipv6_address('2001:000:a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef') self.assertEqual(clean_ipv6_address('2001::a:0000:0:fe:fe:beef'), '2001:0:a::fe:fe:beef') def test_cleans_with_v4_mapping(self): self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a'), '::ffff:10.10.10.10') self.assertEqual(clean_ipv6_address('::ffff:1234:1234'), '::ffff:18.52.18.52') self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52'), '::ffff:18.52.18.52') self.assertEqual(clean_ipv6_address('::ffff:0.52.18.52'), '::ffff:0.52.18.52') self.assertEqual(clean_ipv6_address('::ffff:0.0.0.0'), '::ffff:0.0.0.0') def test_unpacks_ipv4(self): self.assertEqual(clean_ipv6_address('::ffff:0a0a:0a0a', unpack_ipv4=True), '10.10.10.10') self.assertEqual(clean_ipv6_address('::ffff:1234:1234', unpack_ipv4=True), '18.52.18.52') self.assertEqual(clean_ipv6_address('::ffff:18.52.18.52', unpack_ipv4=True), '18.52.18.52')
ddbfb0d074036b1766bf147a3a3c56075ac4cc163c37b37ef6c96ca39bc56ffd
""" Tests for stuff in django.utils.datastructures. """ import copy from django.test import SimpleTestCase from django.utils.datastructures import ( DictWrapper, ImmutableList, MultiValueDict, MultiValueDictKeyError, OrderedSet, ) class OrderedSetTests(SimpleTestCase): def test_bool(self): # Refs #23664 s = OrderedSet() self.assertFalse(s) s.add(1) self.assertTrue(s) def test_len(self): s = OrderedSet() self.assertEqual(len(s), 0) s.add(1) s.add(2) s.add(2) self.assertEqual(len(s), 2) class MultiValueDictTests(SimpleTestCase): def test_multivaluedict(self): d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) self.assertEqual(d['name'], 'Simon') self.assertEqual(d.get('name'), 'Simon') self.assertEqual(d.getlist('name'), ['Adrian', 'Simon']) self.assertEqual( sorted(d.items()), [('name', 'Simon'), ('position', 'Developer')] ) self.assertEqual( sorted(d.lists()), [('name', ['Adrian', 'Simon']), ('position', ['Developer'])] ) with self.assertRaises(MultiValueDictKeyError) as cm: d.__getitem__('lastname') self.assertEqual(str(cm.exception), "'lastname'") self.assertIsNone(d.get('lastname')) self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent') self.assertEqual(d.getlist('lastname'), []) self.assertEqual(d.getlist('doesnotexist', ['Adrian', 'Simon']), ['Adrian', 'Simon']) d.setlist('lastname', ['Holovaty', 'Willison']) self.assertEqual(d.getlist('lastname'), ['Holovaty', 'Willison']) self.assertEqual(sorted(d.values()), ['Developer', 'Simon', 'Willison']) def test_appendlist(self): d = MultiValueDict() d.appendlist('name', 'Adrian') d.appendlist('name', 'Simon') self.assertEqual(d.getlist('name'), ['Adrian', 'Simon']) def test_copy(self): for copy_func in [copy.copy, lambda d: d.copy()]: d1 = MultiValueDict({ "developers": ["Carl", "Fred"] }) self.assertEqual(d1["developers"], "Fred") d2 = copy_func(d1) d2.update({"developers": "Groucho"}) self.assertEqual(d2["developers"], "Groucho") self.assertEqual(d1["developers"], "Fred") d1 = MultiValueDict({ "key": [[]] }) self.assertEqual(d1["key"], []) d2 = copy_func(d1) d2["key"].append("Penguin") self.assertEqual(d1["key"], ["Penguin"]) self.assertEqual(d2["key"], ["Penguin"]) def test_dict_translation(self): mvd = MultiValueDict({ 'devs': ['Bob', 'Joe'], 'pm': ['Rory'], }) d = mvd.dict() self.assertEqual(sorted(d), sorted(mvd)) for key in mvd: self.assertEqual(d[key], mvd[key]) self.assertEqual({}, MultiValueDict().dict()) def test_getlist_doesnt_mutate(self): x = MultiValueDict({'a': ['1', '2'], 'b': ['3']}) values = x.getlist('a') values += x.getlist('b') self.assertEqual(x.getlist('a'), ['1', '2']) def test_internal_getlist_does_mutate(self): x = MultiValueDict({'a': ['1', '2'], 'b': ['3']}) values = x._getlist('a') values += x._getlist('b') self.assertEqual(x._getlist('a'), ['1', '2', '3']) def test_getlist_default(self): x = MultiValueDict({'a': [1]}) MISSING = object() values = x.getlist('b', default=MISSING) self.assertIs(values, MISSING) def test_getlist_none_empty_values(self): x = MultiValueDict({'a': None, 'b': []}) self.assertIsNone(x.getlist('a')) self.assertEqual(x.getlist('b'), []) class ImmutableListTests(SimpleTestCase): def test_sort(self): d = ImmutableList(range(10)) # AttributeError: ImmutableList object is immutable. with self.assertRaisesMessage(AttributeError, 'ImmutableList object is immutable.'): d.sort() self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)') def test_custom_warning(self): d = ImmutableList(range(10), warning="Object is immutable!") self.assertEqual(d[1], 1) # AttributeError: Object is immutable! with self.assertRaisesMessage(AttributeError, 'Object is immutable!'): d.__setitem__(1, 'test') class DictWrapperTests(SimpleTestCase): def test_dictwrapper(self): def f(x): return "*%s" % x d = DictWrapper({'a': 'a'}, f, 'xx_') self.assertEqual( "Normal: %(a)s. Modified: %(xx_a)s" % d, 'Normal: a. Modified: *a' )
0e7b81f10c683efca6bd8e82b08826f104afa58689bd2df1c2b6d6f4451bf49f
import unittest from datetime import datetime from django.test import SimpleTestCase, ignore_warnings from django.utils.datastructures import MultiValueDict from django.utils.deprecation import RemovedInDjango30Warning from django.utils.http import ( base36_to_int, cookie_date, http_date, int_to_base36, is_safe_url, is_same_domain, parse_etags, parse_http_date, quote_etag, urlencode, urlquote, urlquote_plus, urlsafe_base64_decode, urlsafe_base64_encode, urlunquote, urlunquote_plus, ) class URLEncodeTests(unittest.TestCase): def test_tuples(self): self.assertEqual(urlencode((('a', 1), ('b', 2), ('c', 3))), 'a=1&b=2&c=3') def test_dict(self): result = urlencode({'a': 1, 'b': 2, 'c': 3}) # Dictionaries are treated as unordered. self.assertIn(result, [ 'a=1&b=2&c=3', 'a=1&c=3&b=2', 'b=2&a=1&c=3', 'b=2&c=3&a=1', 'c=3&a=1&b=2', 'c=3&b=2&a=1', ]) def test_dict_containing_sequence_not_doseq(self): self.assertEqual(urlencode({'a': [1, 2]}, doseq=False), 'a=%5B%271%27%2C+%272%27%5D') def test_dict_containing_sequence_doseq(self): self.assertEqual(urlencode({'a': [1, 2]}, doseq=True), 'a=1&a=2') def test_dict_containing_empty_sequence_doseq(self): self.assertEqual(urlencode({'a': []}, doseq=True), '') def test_multivaluedict(self): result = urlencode(MultiValueDict({ 'name': ['Adrian', 'Simon'], 'position': ['Developer'], }), doseq=True) # MultiValueDicts are similarly unordered. self.assertIn(result, [ 'name=Adrian&name=Simon&position=Developer', 'position=Developer&name=Adrian&name=Simon', ]) def test_dict_with_bytes_values(self): self.assertEqual(urlencode({'a': b'abc'}, doseq=True), 'a=abc') def test_dict_with_sequence_of_bytes(self): self.assertEqual(urlencode({'a': [b'spam', b'eggs', b'bacon']}, doseq=True), 'a=spam&a=eggs&a=bacon') def test_dict_with_bytearray(self): self.assertEqual(urlencode({'a': bytearray(range(2))}, doseq=True), 'a=0&a=1') self.assertEqual(urlencode({'a': bytearray(range(2))}, doseq=False), 'a=%5B%270%27%2C+%271%27%5D') def test_generator(self): def gen(): yield from range(2) self.assertEqual(urlencode({'a': gen()}, doseq=True), 'a=0&a=1') self.assertEqual(urlencode({'a': gen()}, doseq=False), 'a=%5B%270%27%2C+%271%27%5D') class Base36IntTests(SimpleTestCase): def test_roundtrip(self): for n in [0, 1, 1000, 1000000]: self.assertEqual(n, base36_to_int(int_to_base36(n))) def test_negative_input(self): with self.assertRaisesMessage(ValueError, 'Negative base36 conversion input.'): int_to_base36(-1) def test_to_base36_errors(self): for n in ['1', 'foo', {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): int_to_base36(n) def test_invalid_literal(self): for n in ['#', ' ']: with self.assertRaisesMessage(ValueError, "invalid literal for int() with base 36: '%s'" % n): base36_to_int(n) def test_input_too_large(self): with self.assertRaisesMessage(ValueError, 'Base36 input too large'): base36_to_int('1' * 14) def test_to_int_errors(self): for n in [123, {1: 2}, (1, 2, 3), 3.141]: with self.assertRaises(TypeError): base36_to_int(n) def test_values(self): for n, b36 in [(0, '0'), (1, '1'), (42, '16'), (818469960, 'django')]: self.assertEqual(int_to_base36(n), b36) self.assertEqual(base36_to_int(b36), n) class IsSafeURLTests(unittest.TestCase): def test_bad_urls(self): bad_urls = ( 'http://example.com', 'http:///example.com', 'https://example.com', 'ftp://example.com', r'\\example.com', r'\\\example.com', r'/\\/example.com', r'\\\example.com', r'\\example.com', r'\\//example.com', r'/\/example.com', r'\/example.com', r'/\example.com', 'http:///example.com', r'http:/\//example.com', r'http:\/example.com', r'http:/\example.com', 'javascript:alert("XSS")', '\njavascript:alert(x)', '\x08//example.com', r'http://otherserver\@example.com', r'http:\\testserver\@example.com', r'http://testserver\me:[email protected]', r'http://testserver\@example.com', r'http:\\testserver\confirm\[email protected]', 'http:999999999', 'ftp:9999999999', '\n', 'http://[2001:cdba:0000:0000:0000:0000:3257:9652/', 'http://2001:cdba:0000:0000:0000:0000:3257:9652]/', ) for bad_url in bad_urls: with self.subTest(url=bad_url): self.assertIs(is_safe_url(bad_url, allowed_hosts={'testserver', 'testserver2'}), False) def test_good_urls(self): good_urls = ( '/view/?param=http://example.com', '/view/?param=https://example.com', '/view?param=ftp://example.com', 'view/?param=//example.com', 'https://testserver/', 'HTTPS://testserver/', '//testserver/', 'http://testserver/[email protected]', '/url%20with%20spaces/', 'path/http:2222222222', ) for good_url in good_urls: with self.subTest(url=good_url): self.assertIs(is_safe_url(good_url, allowed_hosts={'otherserver', 'testserver'}), True) def test_basic_auth(self): # Valid basic auth credentials are allowed. self.assertIs(is_safe_url(r'http://user:pass@testserver/', allowed_hosts={'user:pass@testserver'}), True) def test_no_allowed_hosts(self): # A path without host is allowed. self.assertIs(is_safe_url('/confirm/[email protected]', allowed_hosts=None), True) # Basic auth without host is not allowed. self.assertIs(is_safe_url(r'http://testserver\@example.com', allowed_hosts=None), False) def test_secure_param_https_urls(self): secure_urls = ( 'https://example.com/p', 'HTTPS://example.com/p', '/view/?param=http://example.com', ) for url in secure_urls: with self.subTest(url=url): self.assertIs(is_safe_url(url, allowed_hosts={'example.com'}, require_https=True), True) def test_secure_param_non_https_urls(self): insecure_urls = ( 'http://example.com/p', 'ftp://example.com/p', '//example.com/p', ) for url in insecure_urls: with self.subTest(url=url): self.assertIs(is_safe_url(url, allowed_hosts={'example.com'}, require_https=True), False) class URLSafeBase64Tests(unittest.TestCase): def test_roundtrip(self): bytestring = b'foo' encoded = urlsafe_base64_encode(bytestring) decoded = urlsafe_base64_decode(encoded) self.assertEqual(bytestring, decoded) class URLQuoteTests(unittest.TestCase): def test_quote(self): self.assertEqual(urlquote('Paris & Orl\xe9ans'), 'Paris%20%26%20Orl%C3%A9ans') self.assertEqual(urlquote('Paris & Orl\xe9ans', safe="&"), 'Paris%20&%20Orl%C3%A9ans') def test_unquote(self): self.assertEqual(urlunquote('Paris%20%26%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') self.assertEqual(urlunquote('Paris%20&%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') def test_quote_plus(self): self.assertEqual(urlquote_plus('Paris & Orl\xe9ans'), 'Paris+%26+Orl%C3%A9ans') self.assertEqual(urlquote_plus('Paris & Orl\xe9ans', safe="&"), 'Paris+&+Orl%C3%A9ans') def test_unquote_plus(self): self.assertEqual(urlunquote_plus('Paris+%26+Orl%C3%A9ans'), 'Paris & Orl\xe9ans') self.assertEqual(urlunquote_plus('Paris+&+Orl%C3%A9ans'), 'Paris & Orl\xe9ans') class IsSameDomainTests(unittest.TestCase): def test_good(self): for pair in ( ('example.com', 'example.com'), ('example.com', '.example.com'), ('foo.example.com', '.example.com'), ('example.com:8888', 'example.com:8888'), ('example.com:8888', '.example.com:8888'), ('foo.example.com:8888', '.example.com:8888'), ): self.assertIs(is_same_domain(*pair), True) def test_bad(self): for pair in ( ('example2.com', 'example.com'), ('foo.example.com', 'example.com'), ('example.com:9999', 'example.com:8888'), ): self.assertIs(is_same_domain(*pair), False) class ETagProcessingTests(unittest.TestCase): def test_parsing(self): self.assertEqual( parse_etags(r'"" , "etag", "e\\tag", W/"weak"'), ['""', '"etag"', r'"e\\tag"', 'W/"weak"'] ) self.assertEqual(parse_etags('*'), ['*']) # Ignore RFC 2616 ETags that are invalid according to RFC 7232. self.assertEqual(parse_etags(r'"etag", "e\"t\"ag"'), ['"etag"']) def test_quoting(self): self.assertEqual(quote_etag('etag'), '"etag"') # unquoted self.assertEqual(quote_etag('"etag"'), '"etag"') # quoted self.assertEqual(quote_etag('W/"etag"'), 'W/"etag"') # quoted, weak class HttpDateProcessingTests(unittest.TestCase): def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT') @ignore_warnings(category=RemovedInDjango30Warning) def test_cookie_date(self): t = 1167616461.0 self.assertEqual(cookie_date(t), 'Mon, 01-Jan-2007 01:54:21 GMT') def test_parsing_rfc1123(self): parsed = parse_http_date('Sun, 06 Nov 1994 08:49:37 GMT') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) def test_parsing_rfc850(self): parsed = parse_http_date('Sunday, 06-Nov-94 08:49:37 GMT') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) def test_parsing_asctime(self): parsed = parse_http_date('Sun Nov 6 08:49:37 1994') self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37))
b39d97377c37b06bd9226aec6a79599d0391ad7ab9fe0b915edb042d402a0d90
import os import shutil import stat import sys import tempfile import unittest from django.utils.archive import Archive, extract TEST_DIR = os.path.join(os.path.dirname(__file__), 'archives') class ArchiveTester: archive = None def setUp(self): """ Create temporary directory for testing extraction. """ self.old_cwd = os.getcwd() self.tmpdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmpdir) self.archive_path = os.path.join(TEST_DIR, self.archive) self.archive_lead_path = os.path.join(TEST_DIR, "leadpath_%s" % self.archive) # Always start off in TEST_DIR. os.chdir(TEST_DIR) def tearDown(self): os.chdir(self.old_cwd) def test_extract_method(self): with Archive(self.archive) as archive: archive.extract(self.tmpdir) self.check_files(self.tmpdir) def test_extract_method_no_to_path(self): os.chdir(self.tmpdir) with Archive(self.archive_path) as archive: archive.extract() self.check_files(self.tmpdir) def test_extract_function(self): extract(self.archive_path, self.tmpdir) self.check_files(self.tmpdir) @unittest.skipIf(sys.platform == 'win32', 'Python on Windows has a limited os.chmod().') def test_extract_file_permissions(self): """Archive.extract() preserves file permissions.""" extract(self.archive_path, self.tmpdir) filepath = os.path.join(self.tmpdir, 'executable') # The file has executable permission. self.assertTrue(os.stat(filepath).st_mode & stat.S_IXOTH) filepath = os.path.join(self.tmpdir, 'no_permissions') # The file is readable even though it doesn't have permission data in # the archive. self.assertTrue(os.stat(filepath).st_mode & stat.S_IROTH) def test_extract_function_with_leadpath(self): extract(self.archive_lead_path, self.tmpdir) self.check_files(self.tmpdir) def test_extract_function_no_to_path(self): os.chdir(self.tmpdir) extract(self.archive_path) self.check_files(self.tmpdir) def check_files(self, tmpdir): self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, '1'))) self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, '2'))) self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', '1'))) self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', '2'))) self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', 'bar', '1'))) self.assertTrue(os.path.isfile(os.path.join(self.tmpdir, 'foo', 'bar', '2'))) class TestZip(ArchiveTester, unittest.TestCase): archive = 'foobar.zip' class TestTar(ArchiveTester, unittest.TestCase): archive = 'foobar.tar' class TestGzipTar(ArchiveTester, unittest.TestCase): archive = 'foobar.tar.gz' class TestBzip2Tar(ArchiveTester, unittest.TestCase): archive = 'foobar.tar.bz2'
9f0de37f4526b064ff478be5e2fb99e7c5b21e46924d408bcff7ca7cc3a22fcc
import unittest from unittest import mock from django.utils.lorem_ipsum import paragraph, paragraphs, sentence, words class LoremIpsumTests(unittest.TestCase): def test_negative_words(self): """words(n) returns n + 19 words, even if n is negative.""" self.assertEqual( words(-5), 'lorem ipsum dolor sit amet consectetur adipisicing elit sed do ' 'eiusmod tempor incididunt ut' ) def test_same_or_less_common_words(self): """words(n) for n < 19.""" self.assertEqual(words(7), 'lorem ipsum dolor sit amet consectetur adipisicing') def test_common_words_in_string(self): """words(n) starts with the 19 standard lorem ipsum words for n > 19.""" self.assertTrue( words(25).startswith( 'lorem ipsum dolor sit amet consectetur adipisicing elit sed ' 'do eiusmod tempor incididunt ut labore et dolore magna aliqua' ) ) def test_more_words_than_common(self): """words(n) returns n words for n > 19.""" self.assertEqual(len(words(25).split()), 25) def test_common_large_number_of_words(self): """words(n) has n words when n is greater than len(WORDS).""" self.assertEqual(len(words(500).split()), 500) @mock.patch('django.utils.lorem_ipsum.random.sample') def test_not_common_words(self, mock_sample): """words(n, common=False) returns random words.""" mock_sample.return_value = ['exercitationem', 'perferendis'] self.assertEqual(words(2, common=False), 'exercitationem perferendis') def test_sentence_starts_with_capital(self): """A sentence starts with a capital letter.""" self.assertTrue(sentence()[0].isupper()) @mock.patch('django.utils.lorem_ipsum.random.sample') @mock.patch('django.utils.lorem_ipsum.random.choice') @mock.patch('django.utils.lorem_ipsum.random.randint') def test_sentence(self, mock_randint, mock_choice, mock_sample): """ Sentences are built using some number of phrases and a set of words. """ mock_randint.return_value = 2 # Use two phrases. mock_sample.return_value = ['exercitationem', 'perferendis'] mock_choice.return_value = '?' value = sentence() self.assertEqual(mock_randint.call_count, 3) self.assertEqual(mock_sample.call_count, 2) self.assertEqual(mock_choice.call_count, 1) self.assertEqual(value, 'Exercitationem perferendis, exercitationem perferendis?') @mock.patch('django.utils.lorem_ipsum.random.choice') def test_sentence_ending(self, mock_choice): """Sentences end with a question mark or a period.""" mock_choice.return_value = '?' self.assertIn(sentence()[-1], '?') mock_choice.return_value = '.' self.assertIn(sentence()[-1], '.') @mock.patch('django.utils.lorem_ipsum.random.sample') @mock.patch('django.utils.lorem_ipsum.random.choice') @mock.patch('django.utils.lorem_ipsum.random.randint') def test_paragraph(self, mock_paragraph_randint, mock_choice, mock_sample): """paragraph() generates a single paragraph.""" # Make creating 2 sentences use 2 phrases. mock_paragraph_randint.return_value = 2 mock_sample.return_value = ['exercitationem', 'perferendis'] mock_choice.return_value = '.' value = paragraph() self.assertEqual(mock_paragraph_randint.call_count, 7) self.assertEqual(value, ( 'Exercitationem perferendis, exercitationem perferendis. ' 'Exercitationem perferendis, exercitationem perferendis.' )) @mock.patch('django.utils.lorem_ipsum.random.sample') @mock.patch('django.utils.lorem_ipsum.random.choice') @mock.patch('django.utils.lorem_ipsum.random.randint') def test_paragraphs_not_common(self, mock_randint, mock_choice, mock_sample): """ paragraphs(1, common=False) generating one paragraph that's not the COMMON_P paragraph. """ # Make creating 2 sentences use 2 phrases. mock_randint.return_value = 2 mock_sample.return_value = ['exercitationem', 'perferendis'] mock_choice.return_value = '.' self.assertEqual( paragraphs(1, common=False), [ 'Exercitationem perferendis, exercitationem perferendis. ' 'Exercitationem perferendis, exercitationem perferendis.' ] ) self.assertEqual(mock_randint.call_count, 7) def test_paragraphs(self): """paragraphs(1) uses the COMMON_P paragraph.""" self.assertEqual( paragraphs(1), [ 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' 'sed do eiusmod tempor incididunt ut labore et dolore magna ' 'aliqua. Ut enim ad minim veniam, quis nostrud exercitation ' 'ullamco laboris nisi ut aliquip ex ea commodo consequat. ' 'Duis aute irure dolor in reprehenderit in voluptate velit ' 'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ' 'occaecat cupidatat non proident, sunt in culpa qui officia ' 'deserunt mollit anim id est laborum.' ] )
1158ae4a89b8c57b820f8e7ab4c6e787fb3a18c46b9eace3ed0569b3e5ace1a2
import copy import pickle import sys import warnings from unittest import TestCase from django.utils.functional import LazyObject, SimpleLazyObject, empty from .models import Category, CategoryInfo class Foo: """ A simple class with just one attribute. """ foo = 'bar' def __eq__(self, other): return self.foo == other.foo class LazyObjectTestCase(TestCase): def lazy_wrap(self, wrapped_object): """ Wrap the given object into a LazyObject """ class AdHocLazyObject(LazyObject): def _setup(self): self._wrapped = wrapped_object return AdHocLazyObject() def test_getattr(self): obj = self.lazy_wrap(Foo()) self.assertEqual(obj.foo, 'bar') def test_setattr(self): obj = self.lazy_wrap(Foo()) obj.foo = 'BAR' obj.bar = 'baz' self.assertEqual(obj.foo, 'BAR') self.assertEqual(obj.bar, 'baz') def test_setattr2(self): # Same as test_setattr but in reversed order obj = self.lazy_wrap(Foo()) obj.bar = 'baz' obj.foo = 'BAR' self.assertEqual(obj.foo, 'BAR') self.assertEqual(obj.bar, 'baz') def test_delattr(self): obj = self.lazy_wrap(Foo()) obj.bar = 'baz' self.assertEqual(obj.bar, 'baz') del obj.bar with self.assertRaises(AttributeError): obj.bar def test_cmp(self): obj1 = self.lazy_wrap('foo') obj2 = self.lazy_wrap('bar') obj3 = self.lazy_wrap('foo') self.assertEqual(obj1, 'foo') self.assertEqual(obj1, obj3) self.assertNotEqual(obj1, obj2) self.assertNotEqual(obj1, 'bar') def test_bytes(self): obj = self.lazy_wrap(b'foo') self.assertEqual(bytes(obj), b'foo') def test_text(self): obj = self.lazy_wrap('foo') self.assertEqual(str(obj), 'foo') def test_bool(self): # Refs #21840 for f in [False, 0, (), {}, [], None, set()]: self.assertFalse(self.lazy_wrap(f)) for t in [True, 1, (1,), {1: 2}, [1], object(), {1}]: self.assertTrue(t) def test_dir(self): obj = self.lazy_wrap('foo') self.assertEqual(dir(obj), dir('foo')) def test_len(self): for seq in ['asd', [1, 2, 3], {'a': 1, 'b': 2, 'c': 3}]: obj = self.lazy_wrap(seq) self.assertEqual(len(obj), 3) def test_class(self): self.assertIsInstance(self.lazy_wrap(42), int) class Bar(Foo): pass self.assertIsInstance(self.lazy_wrap(Bar()), Foo) def test_hash(self): obj = self.lazy_wrap('foo') d = {obj: 'bar'} self.assertIn('foo', d) self.assertEqual(d['foo'], 'bar') def test_contains(self): test_data = [ ('c', 'abcde'), (2, [1, 2, 3]), ('a', {'a': 1, 'b': 2, 'c': 3}), (2, {1, 2, 3}), ] for needle, haystack in test_data: self.assertIn(needle, self.lazy_wrap(haystack)) # __contains__ doesn't work when the haystack is a string and the needle a LazyObject for needle_haystack in test_data[1:]: self.assertIn(self.lazy_wrap(needle), haystack) self.assertIn(self.lazy_wrap(needle), self.lazy_wrap(haystack)) def test_getitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({'a': 1, 'b': 2, 'c': 3}) self.assertEqual(obj_list[0], 1) self.assertEqual(obj_list[-1], 3) self.assertEqual(obj_list[1:2], [2]) self.assertEqual(obj_dict['b'], 2) with self.assertRaises(IndexError): obj_list[3] with self.assertRaises(KeyError): obj_dict['f'] def test_setitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({'a': 1, 'b': 2, 'c': 3}) obj_list[0] = 100 self.assertEqual(obj_list, [100, 2, 3]) obj_list[1:2] = [200, 300, 400] self.assertEqual(obj_list, [100, 200, 300, 400, 3]) obj_dict['a'] = 100 obj_dict['d'] = 400 self.assertEqual(obj_dict, {'a': 100, 'b': 2, 'c': 3, 'd': 400}) def test_delitem(self): obj_list = self.lazy_wrap([1, 2, 3]) obj_dict = self.lazy_wrap({'a': 1, 'b': 2, 'c': 3}) del obj_list[-1] del obj_dict['c'] self.assertEqual(obj_list, [1, 2]) self.assertEqual(obj_dict, {'a': 1, 'b': 2}) with self.assertRaises(IndexError): del obj_list[3] with self.assertRaises(KeyError): del obj_dict['f'] def test_iter(self): # Tests whether an object's custom `__iter__` method is being # used when iterating over it. class IterObject: def __init__(self, values): self.values = values def __iter__(self): return iter(self.values) original_list = ['test', '123'] self.assertEqual( list(self.lazy_wrap(IterObject(original_list))), original_list ) def test_pickle(self): # See ticket #16563 obj = self.lazy_wrap(Foo()) obj.bar = 'baz' pickled = pickle.dumps(obj) unpickled = pickle.loads(pickled) self.assertIsInstance(unpickled, Foo) self.assertEqual(unpickled, obj) self.assertEqual(unpickled.foo, obj.foo) self.assertEqual(unpickled.bar, obj.bar) # Test copying lazy objects wrapping both builtin types and user-defined # classes since a lot of the relevant code does __dict__ manipulation and # builtin types don't have __dict__. def test_copy_list(self): # Copying a list works and returns the correct objects. lst = [1, 2, 3] obj = self.lazy_wrap(lst) len(lst) # forces evaluation obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, list) self.assertEqual(obj2, [1, 2, 3]) def test_copy_list_no_evaluation(self): # Copying a list doesn't force evaluation. lst = [1, 2, 3] obj = self.lazy_wrap(lst) obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_copy_class(self): # Copying a class works and returns the correct objects. foo = Foo() obj = self.lazy_wrap(foo) str(foo) # forces evaluation obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, Foo) self.assertEqual(obj2, Foo()) def test_copy_class_no_evaluation(self): # Copying a class doesn't force evaluation. foo = Foo() obj = self.lazy_wrap(foo) obj2 = copy.copy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_deepcopy_list(self): # Deep copying a list works and returns the correct objects. lst = [1, 2, 3] obj = self.lazy_wrap(lst) len(lst) # forces evaluation obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, list) self.assertEqual(obj2, [1, 2, 3]) def test_deepcopy_list_no_evaluation(self): # Deep copying doesn't force evaluation. lst = [1, 2, 3] obj = self.lazy_wrap(lst) obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) def test_deepcopy_class(self): # Deep copying a class works and returns the correct objects. foo = Foo() obj = self.lazy_wrap(foo) str(foo) # forces evaluation obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIsInstance(obj2, Foo) self.assertEqual(obj2, Foo()) def test_deepcopy_class_no_evaluation(self): # Deep copying doesn't force evaluation. foo = Foo() obj = self.lazy_wrap(foo) obj2 = copy.deepcopy(obj) self.assertIsNot(obj, obj2) self.assertIs(obj._wrapped, empty) self.assertIs(obj2._wrapped, empty) class SimpleLazyObjectTestCase(LazyObjectTestCase): # By inheriting from LazyObjectTestCase and redefining the lazy_wrap() # method which all testcases use, we get to make sure all behaviors # tested in the parent testcase also apply to SimpleLazyObject. def lazy_wrap(self, wrapped_object): return SimpleLazyObject(lambda: wrapped_object) def test_repr(self): # First, for an unevaluated SimpleLazyObject obj = self.lazy_wrap(42) # __repr__ contains __repr__ of setup function and does not evaluate # the SimpleLazyObject self.assertRegex(repr(obj), '^<SimpleLazyObject:') self.assertIs(obj._wrapped, empty) # make sure evaluation hasn't been triggered self.assertEqual(obj, 42) # evaluate the lazy object self.assertIsInstance(obj._wrapped, int) self.assertEqual(repr(obj), '<SimpleLazyObject: 42>') def test_trace(self): # See ticket #19456 old_trace_func = sys.gettrace() try: def trace_func(frame, event, arg): frame.f_locals['self'].__class__ if old_trace_func is not None: old_trace_func(frame, event, arg) sys.settrace(trace_func) self.lazy_wrap(None) finally: sys.settrace(old_trace_func) def test_none(self): i = [0] def f(): i[0] += 1 return None x = SimpleLazyObject(f) self.assertEqual(str(x), "None") self.assertEqual(i, [1]) self.assertEqual(str(x), "None") self.assertEqual(i, [1]) def test_dict(self): # See ticket #18447 lazydict = SimpleLazyObject(lambda: {'one': 1}) self.assertEqual(lazydict['one'], 1) lazydict['one'] = -1 self.assertEqual(lazydict['one'], -1) self.assertIn('one', lazydict) self.assertNotIn('two', lazydict) self.assertEqual(len(lazydict), 1) del lazydict['one'] with self.assertRaises(KeyError): lazydict['one'] def test_list_set(self): lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5]) lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4}) self.assertIn(1, lazy_list) self.assertIn(1, lazy_set) self.assertNotIn(6, lazy_list) self.assertNotIn(6, lazy_set) self.assertEqual(len(lazy_list), 5) self.assertEqual(len(lazy_set), 4) class BaseBaz: """ A base class with a funky __reduce__ method, meant to simulate the __reduce__ method of Model, which sets self._django_version. """ def __init__(self): self.baz = 'wrong' def __reduce__(self): self.baz = 'right' return super().__reduce__() def __eq__(self, other): if self.__class__ != other.__class__: return False for attr in ['bar', 'baz', 'quux']: if hasattr(self, attr) != hasattr(other, attr): return False elif getattr(self, attr, None) != getattr(other, attr, None): return False return True class Baz(BaseBaz): """ A class that inherits from BaseBaz and has its own __reduce_ex__ method. """ def __init__(self, bar): self.bar = bar super().__init__() def __reduce_ex__(self, proto): self.quux = 'quux' return super().__reduce_ex__(proto) class BazProxy(Baz): """ A class that acts as a proxy for Baz. It does some scary mucking about with dicts, which simulates some crazy things that people might do with e.g. proxy models. """ def __init__(self, baz): self.__dict__ = baz.__dict__ self._baz = baz # Grandparent super super(BaseBaz, self).__init__() class SimpleLazyObjectPickleTestCase(TestCase): """ Regression test for pickling a SimpleLazyObject wrapping a model (#25389). Also covers other classes with a custom __reduce__ method. """ def test_pickle_with_reduce(self): """ Test in a fairly synthetic setting. """ # Test every pickle protocol available for protocol in range(pickle.HIGHEST_PROTOCOL + 1): lazy_objs = [ SimpleLazyObject(lambda: BaseBaz()), SimpleLazyObject(lambda: Baz(1)), SimpleLazyObject(lambda: BazProxy(Baz(2))), ] for obj in lazy_objs: pickled = pickle.dumps(obj, protocol) unpickled = pickle.loads(pickled) self.assertEqual(unpickled, obj) self.assertEqual(unpickled.baz, 'right') def test_pickle_model(self): """ Test on an actual model, based on the report in #25426. """ category = Category.objects.create(name="thing1") CategoryInfo.objects.create(category=category) # Test every pickle protocol available for protocol in range(pickle.HIGHEST_PROTOCOL + 1): lazy_category = SimpleLazyObject(lambda: category) # Test both if we accessed a field on the model and if we didn't. lazy_category.categoryinfo lazy_category_2 = SimpleLazyObject(lambda: category) with warnings.catch_warnings(record=True) as recorded: self.assertEqual(pickle.loads(pickle.dumps(lazy_category, protocol)), category) self.assertEqual(pickle.loads(pickle.dumps(lazy_category_2, protocol)), category) # Assert that there were no warnings. self.assertEqual(len(recorded), 0)
28d9d1b51928a65831b6fa6e53cafcd25ebd8b9541d566029a1c5204f1469501
"""Tests for jslex.""" # originally from https://bitbucket.org/ned/jslex from django.test import SimpleTestCase from django.utils.jslex import JsLexer, prepare_js_for_gettext class JsTokensTest(SimpleTestCase): LEX_CASES = [ # ids ("a ABC $ _ a123", ["id a", "id ABC", "id $", "id _", "id a123"]), ("\\u1234 abc\\u0020 \\u0065_\\u0067", ["id \\u1234", "id abc\\u0020", "id \\u0065_\\u0067"]), # numbers ("123 1.234 0.123e-3 0 1E+40 1e1 .123", [ "dnum 123", "dnum 1.234", "dnum 0.123e-3", "dnum 0", "dnum 1E+40", "dnum 1e1", "dnum .123", ]), ("0x1 0xabCD 0XABcd", ["hnum 0x1", "hnum 0xabCD", "hnum 0XABcd"]), ("010 0377 090", ["onum 010", "onum 0377", "dnum 0", "dnum 90"]), ("0xa123ghi", ["hnum 0xa123", "id ghi"]), # keywords ("function Function FUNCTION", ["keyword function", "id Function", "id FUNCTION"]), ("const constructor in inherits", ["keyword const", "id constructor", "keyword in", "id inherits"]), ("true true_enough", ["reserved true", "id true_enough"]), # strings (''' 'hello' "hello" ''', ["string 'hello'", 'string "hello"']), (r""" 'don\'t' "don\"t" '"' "'" '\'' "\"" """, [ r"""string 'don\'t'""", r'''string "don\"t"''', r"""string '"'""", r'''string "'"''', r"""string '\''""", r'''string "\""''' ]), (r'"ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""', [r'string "ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""']), # comments ("a//b", ["id a", "linecomment //b"]), ("/****/a/=2//hello", ["comment /****/", "id a", "punct /=", "dnum 2", "linecomment //hello"]), ("/*\n * Header\n */\na=1;", ["comment /*\n * Header\n */", "id a", "punct =", "dnum 1", "punct ;"]), # punctuation ("a+++b", ["id a", "punct ++", "punct +", "id b"]), # regex (r"a=/a*/,1", ["id a", "punct =", "regex /a*/", "punct ,", "dnum 1"]), (r"a=/a*[^/]+/,1", ["id a", "punct =", "regex /a*[^/]+/", "punct ,", "dnum 1"]), (r"a=/a*\[^/,1", ["id a", "punct =", r"regex /a*\[^/", "punct ,", "dnum 1"]), (r"a=/\//,1", ["id a", "punct =", r"regex /\//", "punct ,", "dnum 1"]), # next two are from http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions ("""for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}""", ["keyword for", "punct (", "keyword var", "id x", "punct =", "id a", "keyword in", "id foo", "punct &&", 'string "</x>"', "punct ||", "id mot", "punct ?", "id z", "punct :", "regex /x:3;x<5;y</g", "punct /", "id i", "punct )", "punct {", "id xyz", "punct (", "id x", "punct ++", "punct )", "punct ;", "punct }"]), ("""for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}""", ["keyword for", "punct (", "keyword var", "id x", "punct =", "id a", "keyword in", "id foo", "punct &&", 'string "</x>"', "punct ||", "id mot", "punct ?", "id z", "punct /", "id x", "punct :", "dnum 3", "punct ;", "id x", "punct <", "dnum 5", "punct ;", "id y", "punct <", "regex /g/i", "punct )", "punct {", "id xyz", "punct (", "id x", "punct ++", "punct )", "punct ;", "punct }"]), # Various "illegal" regexes that are valid according to the std. (r"""/????/, /++++/, /[----]/ """, ["regex /????/", "punct ,", "regex /++++/", "punct ,", "regex /[----]/"]), # Stress cases from http://stackoverflow.com/questions/5533925/what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409 # NOQA (r"""/\[/""", [r"""regex /\[/"""]), (r"""/[i]/""", [r"""regex /[i]/"""]), (r"""/[\]]/""", [r"""regex /[\]]/"""]), (r"""/a[\]]/""", [r"""regex /a[\]]/"""]), (r"""/a[\]]b/""", [r"""regex /a[\]]b/"""]), (r"""/[\]/]/gi""", [r"""regex /[\]/]/gi"""]), (r"""/\[[^\]]+\]/gi""", [r"""regex /\[[^\]]+\]/gi"""]), (r""" rexl.re = { NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_LITERAL: /^'(?:[^']|'')*'/, NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; """, # NOQA ["id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", # NOQA "punct }", "punct ;" ]), (r""" rexl.re = { NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_LITERAL: /^'(?:[^']|'')*'/, NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; str = '"'; """, # NOQA ["id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", # NOQA "punct }", "punct ;", "id str", "punct =", """string '"'""", "punct ;", ]), (r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """, ["keyword this", "punct .", "id _js", "punct =", r'''string "e.str(\""''', "punct +", "keyword this", "punct .", "id value", "punct .", "id replace", "punct (", r"regex /\\/g", "punct ,", r'string "\\\\"', "punct )", "punct .", "id replace", "punct (", r'regex /"/g', "punct ,", r'string "\\\""', "punct )", "punct +", r'string "\")"', "punct ;"]), ] def make_function(input, toks): def test_func(self): lexer = JsLexer() result = ["%s %s" % (name, tok) for name, tok in lexer.lex(input) if name != 'ws'] self.assertEqual(result, toks) return test_func for i, (input, toks) in enumerate(JsTokensTest.LEX_CASES): setattr(JsTokensTest, "test_case_%d" % i, make_function(input, toks)) GETTEXT_CASES = ( ( r""" a = 1; /* /[0-9]+/ */ b = 0x2a0b / 1; // /[0-9]+/ c = 3; """, r""" a = 1; /* /[0-9]+/ */ b = 0x2a0b / 1; // /[0-9]+/ c = 3; """ ), ( r""" a = 1.234e-5; /* * /[0-9+/ */ b = .0123; """, r""" a = 1.234e-5; /* * /[0-9+/ */ b = .0123; """ ), ( r""" x = y / z; alert(gettext("hello")); x /= 3; """, r""" x = y / z; alert(gettext("hello")); x /= 3; """ ), ( r""" s = "Hello \"th/foo/ere\""; s = 'He\x23llo \'th/foo/ere\''; s = 'slash quote \", just quote "'; """, r""" s = "Hello \"th/foo/ere\""; s = "He\x23llo \'th/foo/ere\'"; s = "slash quote \", just quote \""; """ ), ( r""" s = "Line continuation\ continued /hello/ still the string";/hello/; """, r""" s = "Line continuation\ continued /hello/ still the string";"REGEX"; """ ), ( r""" var regex = /pattern/; var regex2 = /matter/gm; var regex3 = /[*/]+/gm.foo("hey"); """, r""" var regex = "REGEX"; var regex2 = "REGEX"; var regex3 = "REGEX".foo("hey"); """ ), ( r""" for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);} for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);} """, r""" for (var x = a in foo && "</x>" || mot ? z:"REGEX"/i) {xyz(x++);} for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y<"REGEX") {xyz(x++);} """ ), ( """ \\u1234xyz = gettext('Hello there'); """, r""" Uu1234xyz = gettext("Hello there"); """ ) ) class JsToCForGettextTest(SimpleTestCase): pass def make_function(js, c): def test_func(self): self.assertEqual(prepare_js_for_gettext(js), c) return test_func for i, pair in enumerate(GETTEXT_CASES): setattr(JsToCForGettextTest, "test_case_%d" % i, make_function(*pair))
2ad3c60ffbc2e8273bfa3ef17e4e022248d1a5addf5f2e3da5ed4181a0d1fd6b
from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.test import RequestFactory, SimpleTestCase from django.utils.decorators import classproperty, decorator_from_middleware class ProcessViewMiddleware: def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() class ClassProcessView: def __call__(self, request): return HttpResponse() class_process_view = process_view_dec(ClassProcessView()) class FullMiddleware: def process_request(self, request): request.process_request_reached = True def process_view(self, request, view_func, view_args, view_kwargs): request.process_view_reached = True def process_template_response(self, request, response): request.process_template_response_reached = True return response def process_response(self, request, response): # This should never receive unrendered content. request.process_response_content = response.content request.process_response_reached = True return response full_dec = decorator_from_middleware(FullMiddleware) class DecoratorFromMiddlewareTests(SimpleTestCase): """ Tests for view decorators created using ``django.utils.decorators.decorator_from_middleware``. """ rf = RequestFactory() def test_process_view_middleware(self): """ Test a middleware that implements process_view. """ process_view(self.rf.get('/')) def test_callable_process_view_middleware(self): """ Test a middleware that implements process_view, operating on a callable class. """ class_process_view(self.rf.get('/')) def test_full_dec_normal(self): """ All methods of middleware are called for normal HttpResponses """ @full_dec def normal_view(request): template = engines['django'].from_string("Hello world") return HttpResponse(template.render()) request = self.rf.get('/') normal_view(request) self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(request, 'process_view_reached', False)) # process_template_response must not be called for HttpResponse self.assertFalse(getattr(request, 'process_template_response_reached', False)) self.assertTrue(getattr(request, 'process_response_reached', False)) def test_full_dec_templateresponse(self): """ All methods of middleware are called for TemplateResponses in the right sequence. """ @full_dec def template_response_view(request): template = engines['django'].from_string("Hello world") return TemplateResponse(request, template) request = self.rf.get('/') response = template_response_view(request) self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(request, 'process_view_reached', False)) self.assertTrue(getattr(request, 'process_template_response_reached', False)) # response must not be rendered yet. self.assertFalse(response._is_rendered) # process_response must not be called until after response is rendered, # otherwise some decorators like csrf_protect and gzip_page will not # work correctly. See #16004 self.assertFalse(getattr(request, 'process_response_reached', False)) response.render() self.assertTrue(getattr(request, 'process_response_reached', False)) # process_response saw the rendered content self.assertEqual(request.process_response_content, b"Hello world") class ClassPropertyTest(SimpleTestCase): def test_getter(self): class Foo: foo_attr = 123 def __init__(self): self.foo_attr = 456 @classproperty def foo(cls): return cls.foo_attr class Bar: bar = classproperty() @bar.getter def bar(cls): return 123 self.assertEqual(Foo.foo, 123) self.assertEqual(Foo().foo, 123) self.assertEqual(Bar.bar, 123) self.assertEqual(Bar().bar, 123) def test_override_getter(self): class Foo: @classproperty def foo(cls): return 123 @foo.getter def foo(cls): return 456 self.assertEqual(Foo.foo, 456) self.assertEqual(Foo().foo, 456)
9792398388c4d45f980914c449ab019007b89fc5bca603f77344bd361437dc70
import datetime import unittest from django.test import TestCase from django.utils import feedgenerator from django.utils.timezone import get_fixed_timezone, utc class FeedgeneratorTest(unittest.TestCase): """ Tests for the low-level syndication feed framework. """ def test_get_tag_uri(self): """ get_tag_uri() correctly generates TagURIs. """ self.assertEqual( feedgenerator.get_tag_uri('http://example.org/foo/bar#headline', datetime.date(2004, 10, 25)), 'tag:example.org,2004-10-25:/foo/bar/headline') def test_get_tag_uri_with_port(self): """ get_tag_uri() correctly generates TagURIs from URLs with port numbers. """ self.assertEqual( feedgenerator.get_tag_uri( 'http://www.example.org:8000/2008/11/14/django#headline', datetime.datetime(2008, 11, 14, 13, 37, 0), ), 'tag:www.example.org,2008-11-14:/2008/11/14/django/headline') def test_rfc2822_date(self): """ rfc2822_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "Fri, 14 Nov 2008 13:37:00 -0000" ) def test_rfc2822_date_with_timezone(self): """ rfc2822_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(60))), "Fri, 14 Nov 2008 13:37:00 +0100" ) def test_rfc2822_date_without_time(self): """ rfc2822_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc2822_date(datetime.date(2008, 11, 14)), "Fri, 14 Nov 2008 00:00:00 -0000" ) def test_rfc3339_date(self): """ rfc3339_date() correctly formats datetime objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), "2008-11-14T13:37:00Z" ) def test_rfc3339_date_with_timezone(self): """ rfc3339_date() correctly formats datetime objects with tzinfo. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=get_fixed_timezone(120))), "2008-11-14T13:37:00+02:00" ) def test_rfc3339_date_without_time(self): """ rfc3339_date() correctly formats date objects. """ self.assertEqual( feedgenerator.rfc3339_date(datetime.date(2008, 11, 14)), "2008-11-14T00:00:00Z" ) def test_atom1_mime_type(self): """ Atom MIME type has UTF8 Charset parameter set """ atom_feed = feedgenerator.Atom1Feed("title", "link", "description") self.assertEqual( atom_feed.content_type, "application/atom+xml; charset=utf-8" ) def test_rss_mime_type(self): """ RSS MIME type has UTF8 Charset parameter set """ rss_feed = feedgenerator.Rss201rev2Feed("title", "link", "description") self.assertEqual( rss_feed.content_type, "application/rss+xml; charset=utf-8" ) # Two regression tests for #14202 def test_feed_without_feed_url_gets_rendered_without_atom_link(self): feed = feedgenerator.Rss201rev2Feed('title', '/link/', 'descr') self.assertIsNone(feed.feed['feed_url']) feed_content = feed.writeString('utf-8') self.assertNotIn('<atom:link', feed_content) self.assertNotIn('href="/feed/"', feed_content) self.assertNotIn('rel="self"', feed_content) def test_feed_with_feed_url_gets_rendered_with_atom_link(self): feed = feedgenerator.Rss201rev2Feed('title', '/link/', 'descr', feed_url='/feed/') self.assertEqual(feed.feed['feed_url'], '/feed/') feed_content = feed.writeString('utf-8') self.assertIn('<atom:link', feed_content) self.assertIn('href="/feed/"', feed_content) self.assertIn('rel="self"', feed_content) def test_atom_add_item(self): # Not providing any optional arguments to Atom1Feed.add_item() feed = feedgenerator.Atom1Feed('title', '/link/', 'descr') feed.add_item('item_title', 'item_link', 'item_description') feed.writeString('utf-8') def test_deterministic_attribute_order(self): feed = feedgenerator.Atom1Feed('title', '/link/', 'desc') feed_content = feed.writeString('utf-8') self.assertIn('href="/link/" rel="alternate"', feed_content) class FeedgeneratorDBTest(TestCase): # setting the timezone requires a database query on PostgreSQL. def test_latest_post_date_returns_utc_time(self): for use_tz in (True, False): with self.settings(USE_TZ=use_tz): rss_feed = feedgenerator.Rss201rev2Feed('title', 'link', 'description') self.assertEqual(rss_feed.latest_post_date().tzinfo, utc)
36d2a2958599d4eff728b4d82f69abf37930c3e534ed5e0fd375c501a5df2877
from unittest import TestCase from django.utils.baseconv import ( BaseConverter, base2, base16, base36, base56, base62, base64, ) class TestBaseConv(TestCase): def test_baseconv(self): nums = [-10 ** 10, 10 ** 10] + list(range(-100, 100)) for converter in [base2, base16, base36, base56, base62, base64]: for i in nums: self.assertEqual(i, converter.decode(converter.encode(i))) def test_base11(self): base11 = BaseConverter('0123456789-', sign='$') self.assertEqual(base11.encode(1234), '-22') self.assertEqual(base11.decode('-22'), 1234) self.assertEqual(base11.encode(-1234), '$-22') self.assertEqual(base11.decode('$-22'), -1234) def test_base20(self): base20 = BaseConverter('0123456789abcdefghij') self.assertEqual(base20.encode(1234), '31e') self.assertEqual(base20.decode('31e'), 1234) self.assertEqual(base20.encode(-1234), '-31e') self.assertEqual(base20.decode('-31e'), -1234) def test_base64(self): self.assertEqual(base64.encode(1234), 'JI') self.assertEqual(base64.decode('JI'), 1234) self.assertEqual(base64.encode(-1234), '$JI') self.assertEqual(base64.decode('$JI'), -1234) def test_base7(self): base7 = BaseConverter('cjdhel3', sign='g') self.assertEqual(base7.encode(1234), 'hejd') self.assertEqual(base7.decode('hejd'), 1234) self.assertEqual(base7.encode(-1234), 'ghejd') self.assertEqual(base7.decode('ghejd'), -1234) def test_exception(self): with self.assertRaises(ValueError): BaseConverter('abc', sign='a') self.assertIsInstance(BaseConverter('abc', sign='d'), BaseConverter) def test_repr(self): base7 = BaseConverter('cjdhel3', sign='g') self.assertEqual(repr(base7), '<BaseConverter: base7 (cjdhel3)>')
7811eef5d1b539035b4384c6bb24f0f56e747920042757d121617901f48c19af
import json from django.test import SimpleTestCase from django.utils import text from django.utils.functional import lazystr from django.utils.text import format_lazy from django.utils.translation import gettext_lazy, override IS_WIDE_BUILD = (len('\U0001F4A9') == 1) class TestUtilsText(SimpleTestCase): def test_get_text_list(self): self.assertEqual(text.get_text_list(['a', 'b', 'c', 'd']), 'a, b, c or d') self.assertEqual(text.get_text_list(['a', 'b', 'c'], 'and'), 'a, b and c') self.assertEqual(text.get_text_list(['a', 'b'], 'and'), 'a and b') self.assertEqual(text.get_text_list(['a']), 'a') self.assertEqual(text.get_text_list([]), '') with override('ar'): self.assertEqual(text.get_text_list(['a', 'b', 'c']), "a، b أو c") def test_smart_split(self): testdata = [ ('This is "a person" test.', ['This', 'is', '"a person"', 'test.']), ('This is "a person\'s" test.', ['This', 'is', '"a person\'s"', 'test.']), ('This is "a person\\"s" test.', ['This', 'is', '"a person\\"s"', 'test.']), ('"a \'one', ['"a', "'one"]), ('all friends\' tests', ['all', 'friends\'', 'tests']), ('url search_page words="something else"', ['url', 'search_page', 'words="something else"']), ("url search_page words='something else'", ['url', 'search_page', "words='something else'"]), ('url search_page words "something else"', ['url', 'search_page', 'words', '"something else"']), ('url search_page words-"something else"', ['url', 'search_page', 'words-"something else"']), ('url search_page words=hello', ['url', 'search_page', 'words=hello']), ('url search_page words="something else', ['url', 'search_page', 'words="something', 'else']), ("cut:','|cut:' '", ["cut:','|cut:' '"]), (lazystr("a b c d"), # Test for #20231 ['a', 'b', 'c', 'd']), ] for test, expected in testdata: self.assertEqual(list(text.smart_split(test)), expected) def test_truncate_chars(self): truncator = text.Truncator('The quick brown fox jumped over the lazy dog.') self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.chars(100)), self.assertEqual('The quick brown fox ...', truncator.chars(23)), self.assertEqual('The quick brown fo.....', truncator.chars(23, '.....')), nfc = text.Truncator('o\xfco\xfco\xfco\xfc') nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308') self.assertEqual('oüoüoüoü', nfc.chars(8)) self.assertEqual('oüoüoüoü', nfd.chars(8)) self.assertEqual('oü...', nfc.chars(5)) self.assertEqual('oü...', nfd.chars(5)) # Ensure the final length is calculated correctly when there are # combining characters with no precomposed form, and that combining # characters are not split up. truncator = text.Truncator('-B\u030AB\u030A----8') self.assertEqual('-B\u030A...', truncator.chars(5)) self.assertEqual('-B\u030AB\u030A-...', truncator.chars(7)) self.assertEqual('-B\u030AB\u030A----8', truncator.chars(8)) # Ensure the length of the end text is correctly calculated when it # contains combining characters with no precomposed form. truncator = text.Truncator('-----') self.assertEqual('---B\u030A', truncator.chars(4, 'B\u030A')) self.assertEqual('-----', truncator.chars(5, 'B\u030A')) # Make a best effort to shorten to the desired length, but requesting # a length shorter than the ellipsis shouldn't break self.assertEqual('...', text.Truncator('asdf').chars(1)) # lazy strings are handled correctly self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...') def test_truncate_words(self): truncator = text.Truncator('The quick brown fox jumped over the lazy dog.') self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.words(10)) self.assertEqual('The quick brown fox...', truncator.words(4)) self.assertEqual('The quick brown fox[snip]', truncator.words(4, '[snip]')) # lazy strings are handled correctly truncator = text.Truncator(lazystr('The quick brown fox jumped over the lazy dog.')) self.assertEqual('The quick brown fox...', truncator.words(4)) def test_truncate_html_words(self): truncator = text.Truncator( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>' ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>', truncator.words(10, html=True) ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox...</em></strong></p>', truncator.words(4, html=True) ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox....</em></strong></p>', truncator.words(4, '....', html=True) ) self.assertEqual( '<p id="par"><strong><em>The quick brown fox</em></strong></p>', truncator.words(4, '', html=True) ) # Test with new line inside tag truncator = text.Truncator( '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over the lazy dog.</p>' ) self.assertEqual( '<p>The quick <a href="xyz.html"\n id="mylink">brown...</a></p>', truncator.words(3, '...', html=True) ) # Test self-closing tags truncator = text.Truncator('<br/>The <hr />quick brown fox jumped over the lazy dog.') self.assertEqual('<br/>The <hr />quick brown...', truncator.words(3, '...', html=True)) truncator = text.Truncator('<br>The <hr/>quick <em>brown fox</em> jumped over the lazy dog.') self.assertEqual('<br>The <hr/>quick <em>brown...</em>', truncator.words(3, '...', html=True)) # Test html entities truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo...</i>', truncator.words(3, '...', html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>' truncator = text.Truncator(re_tag_catastrophic_test) self.assertEqual(re_tag_catastrophic_test, truncator.words(500, html=True)) def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9') self.assertEqual(text.wrap(digits, 9), '1234 67 9') self.assertEqual(text.wrap(digits, 8), '1234 67\n9') self.assertEqual(text.wrap('short\na long line', 7), 'short\na long\nline') self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8), 'do-not-break-long-words\nplease?\nok') long_word = 'l%sng' % ('o' * 20) self.assertEqual(text.wrap(long_word, 20), long_word) self.assertEqual(text.wrap('a %s word' % long_word, 10), 'a\n%s\nword' % long_word) self.assertEqual(text.wrap(lazystr(digits), 100), '1234 67 9') def test_normalize_newlines(self): self.assertEqual(text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n") self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n") self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi") self.assertEqual(text.normalize_newlines(""), "") self.assertEqual(text.normalize_newlines(lazystr("abc\ndef\rghi\r\n")), "abc\ndef\nghi\n") def test_phone2numeric(self): numeric = text.phone2numeric('0800 flowers') self.assertEqual(numeric, '0800 3569377') lazy_numeric = lazystr(text.phone2numeric('0800 flowers')) self.assertEqual(lazy_numeric, '0800 3569377') def test_slugify(self): items = ( # given - expected - unicode? ('Hello, World!', 'hello-world', False), ('spam & eggs', 'spam-eggs', False), ('spam & ıçüş', 'spam-ıçüş', True), ('foo ıç bar', 'foo-ıç-bar', True), (' foo ıç bar', 'foo-ıç-bar', True), ('你好', '你好', True), ) for value, output, is_unicode in items: self.assertEqual(text.slugify(value, allow_unicode=is_unicode), output) def test_unescape_entities(self): items = [ ('', ''), ('foo', 'foo'), ('&amp;', '&'), ('&#x26;', '&'), ('&#38;', '&'), ('foo &amp; bar', 'foo & bar'), ('foo & bar', 'foo & bar'), ] for value, output in items: self.assertEqual(text.unescape_entities(value), output) self.assertEqual(text.unescape_entities(lazystr(value)), output) def test_unescape_string_literal(self): items = [ ('"abc"', 'abc'), ("'abc'", 'abc'), ('"a \"bc\""', 'a "bc"'), ("'\'ab\' c'", "'ab' c"), ] for value, output in items: self.assertEqual(text.unescape_string_literal(value), output) self.assertEqual(text.unescape_string_literal(lazystr(value)), output) def test_get_valid_filename(self): filename = "^&'@{}[],$=!-#()%+~_123.txt" self.assertEqual(text.get_valid_filename(filename), "-_123.txt") self.assertEqual(text.get_valid_filename(lazystr(filename)), "-_123.txt") def test_compress_sequence(self): data = [{'key': i} for i in range(10)] seq = list(json.JSONEncoder().iterencode(data)) seq = [s.encode() for s in seq] actual_length = len(b''.join(seq)) out = text.compress_sequence(seq) compressed_length = len(b''.join(out)) self.assertTrue(compressed_length < actual_length) def test_format_lazy(self): self.assertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test'))) self.assertEqual('django/test', format_lazy('{0}/{1}', *('django', 'test'))) self.assertEqual('django/test', format_lazy('{a}/{b}', **{'a': 'django', 'b': 'test'})) self.assertEqual('django/test', format_lazy('{a[0]}/{a[1]}', a=('django', 'test'))) t = {} s = format_lazy('{0[a]}-{p[a]}', t, p=t) t['a'] = lazystr('django') self.assertEqual('django-django', s) t['a'] = 'update' self.assertEqual('update-update', s) # The format string can be lazy. (string comes from contrib.admin) s = format_lazy( gettext_lazy("Added {name} \"{object}\"."), name='article', object='My first try', ) with override('fr'): self.assertEqual('Ajout de article «\xa0My first try\xa0».', s)
96f083034d0513c7d83581dd2e985ee873873990093f921d3d8ef5077c40f55c
from django.conf import settings from django.db import connection, models from django.test import SimpleTestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from .models import Book, ChildModel1, ChildModel2 class IndexesTests(SimpleTestCase): def test_suffix(self): self.assertEqual(models.Index.suffix, 'idx') def test_repr(self): index = models.Index(fields=['title']) multi_col_index = models.Index(fields=['title', 'author']) self.assertEqual(repr(index), "<Index: fields='title'>") self.assertEqual(repr(multi_col_index), "<Index: fields='title, author'>") def test_eq(self): index = models.Index(fields=['title']) same_index = models.Index(fields=['title']) another_index = models.Index(fields=['title', 'author']) index.model = Book same_index.model = Book another_index.model = Book self.assertEqual(index, same_index) self.assertNotEqual(index, another_index) def test_index_fields_type(self): with self.assertRaisesMessage(ValueError, 'Index.fields must be a list or tuple.'): models.Index(fields='title') def test_fields_tuple(self): self.assertEqual(models.Index(fields=('title',)).fields, ['title']) def test_raises_error_without_field(self): msg = 'At least one field is required to define an index.' with self.assertRaisesMessage(ValueError, msg): models.Index() def test_max_name_length(self): msg = 'Index names cannot be longer than 30 characters.' with self.assertRaisesMessage(ValueError, msg): models.Index(fields=['title'], name='looooooooooooong_index_name_idx') def test_name_constraints(self): msg = 'Index names cannot start with an underscore (_).' with self.assertRaisesMessage(ValueError, msg): models.Index(fields=['title'], name='_name_starting_with_underscore') msg = 'Index names cannot start with a number (0-9).' with self.assertRaisesMessage(ValueError, msg): models.Index(fields=['title'], name='5name_starting_with_number') def test_name_auto_generation(self): index = models.Index(fields=['author']) index.set_name_with_model(Book) self.assertEqual(index.name, 'model_index_author_0f5565_idx') # '-' for DESC columns should be accounted for in the index name. index = models.Index(fields=['-author']) index.set_name_with_model(Book) self.assertEqual(index.name, 'model_index_author_708765_idx') # fields may be truncated in the name. db_column is used for naming. long_field_index = models.Index(fields=['pages']) long_field_index.set_name_with_model(Book) self.assertEqual(long_field_index.name, 'model_index_page_co_69235a_idx') # suffix can't be longer than 3 characters. long_field_index.suffix = 'suff' msg = 'Index too long for multiple database support. Is self.suffix longer than 3 characters?' with self.assertRaisesMessage(AssertionError, msg): long_field_index.set_name_with_model(Book) @isolate_apps('model_indexes') def test_name_auto_generation_with_quoted_db_table(self): class QuotedDbTable(models.Model): name = models.CharField(max_length=50) class Meta: db_table = '"t_quoted"' index = models.Index(fields=['name']) index.set_name_with_model(QuotedDbTable) self.assertEqual(index.name, 't_quoted_name_e4ed1b_idx') def test_deconstruction(self): index = models.Index(fields=['title'], db_tablespace='idx_tbls') index.set_name_with_model(Book) path, args, kwargs = index.deconstruct() self.assertEqual(path, 'django.db.models.Index') self.assertEqual(args, ()) self.assertEqual( kwargs, {'fields': ['title'], 'name': 'model_index_title_196f42_idx', 'db_tablespace': 'idx_tbls'} ) def test_clone(self): index = models.Index(fields=['title']) new_index = index.clone() self.assertIsNot(index, new_index) self.assertEqual(index.fields, new_index.fields) def test_name_set(self): index_names = [index.name for index in Book._meta.indexes] self.assertCountEqual(index_names, ['model_index_title_196f42_idx', 'model_index_isbn_34f975_idx']) def test_abstract_children(self): index_names = [index.name for index in ChildModel1._meta.indexes] self.assertEqual(index_names, ['model_index_name_440998_idx']) index_names = [index.name for index in ChildModel2._meta.indexes] self.assertEqual(index_names, ['model_index_name_b6c374_idx']) @skipUnlessDBFeature('supports_tablespaces') def test_db_tablespace(self): with connection.schema_editor() as editor: # Index with db_tablespace attribute. for fields in [ # Field with db_tablespace specified on model. ['shortcut'], # Field without db_tablespace specified on model. ['author'], # Multi-column with db_tablespaces specified on model. ['shortcut', 'isbn'], # Multi-column without db_tablespace specified on model. ['title', 'author'], ]: with self.subTest(fields=fields): index = models.Index(fields=fields, db_tablespace='idx_tbls2') self.assertIn('"idx_tbls2"', str(index.create_sql(Book, editor)).lower()) # Indexes without db_tablespace attribute. for fields in [['author'], ['shortcut', 'isbn'], ['title', 'author']]: with self.subTest(fields=fields): index = models.Index(fields=fields) # The DEFAULT_INDEX_TABLESPACE setting can't be tested # because it's evaluated when the model class is defined. # As a consequence, @override_settings doesn't work. if settings.DEFAULT_INDEX_TABLESPACE: self.assertIn( '"%s"' % settings.DEFAULT_INDEX_TABLESPACE, str(index.create_sql(Book, editor)).lower() ) else: self.assertNotIn('TABLESPACE', str(index.create_sql(Book, editor))) # Field with db_tablespace specified on the model and an index # without db_tablespace. index = models.Index(fields=['shortcut']) self.assertIn('"idx_tbls"', str(index.create_sql(Book, editor)).lower())
1736fa96e7eefcf11dd7221e7d44af8416f9aaa53ee05a161da9c27c1240996c
from django.db import models class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) pages = models.IntegerField(db_column='page_count') shortcut = models.CharField(max_length=50, db_tablespace='idx_tbls') isbn = models.CharField(max_length=50, db_tablespace='idx_tbls') class Meta: indexes = [ models.indexes.Index(fields=['title']), models.indexes.Index(fields=['isbn', 'id']), ] class AbstractModel(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True indexes = [models.indexes.Index(fields=['name'])] class ChildModel1(AbstractModel): pass class ChildModel2(AbstractModel): pass
884a73b8565733cca19788ac28e85c00915ea2b4c481e27f935c91d3e8e327fb
import threading from datetime import datetime, timedelta from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections from django.db.models.manager import BaseManager from django.db.models.query import EmptyQuerySet, QuerySet from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature, ) from django.utils.translation import gettext_lazy from .models import Article, ArticleSelectOnSave, FeaturedArticle, SelfRef class ModelInstanceCreationTests(TestCase): def test_object_is_not_written_to_database_until_save_was_called(self): a = Article( id=None, headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) self.assertIsNone(a.id) self.assertEqual(Article.objects.all().count(), 0) # Save it into the database. You have to call save() explicitly. a.save() self.assertIsNotNone(a.id) self.assertEqual(Article.objects.all().count(), 1) def test_can_initialize_model_instance_using_positional_arguments(self): """ You can initialize a model instance using positional arguments, which should match the field order as defined in the model. """ a = Article(None, 'Second article', datetime(2005, 7, 29)) a.save() self.assertEqual(a.headline, 'Second article') self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0)) def test_can_create_instance_using_kwargs(self): a = Article( id=None, headline='Third article', pub_date=datetime(2005, 7, 30), ) a.save() self.assertEqual(a.headline, 'Third article') self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0)) def test_autofields_generate_different_values_for_each_instance(self): a1 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0)) a2 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0)) a3 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0)) self.assertNotEqual(a3.id, a1.id) self.assertNotEqual(a3.id, a2.id) def test_can_mix_and_match_position_and_kwargs(self): # You can also mix and match position and keyword arguments, but # be sure not to duplicate field information. a = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, 'Fourth article') def test_cannot_create_instance_with_invalid_kwargs(self): with self.assertRaisesMessage(TypeError, "Article() got an unexpected keyword argument 'foo'"): Article( id=None, headline='Some headline', pub_date=datetime(2005, 7, 31), foo='bar', ) def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self): """ You can leave off the value for an AutoField when creating an object, because it'll get filled in automatically when you save(). """ a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, 'Article 5') self.assertIsNotNone(a.id) def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self): a = Article(pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, 'Default headline') def test_for_datetimefields_saves_as_much_precision_as_was_given(self): """as much precision in *seconds*""" a1 = Article( headline='Article 7', pub_date=datetime(2005, 7, 31, 12, 30), ) a1.save() self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30)) a2 = Article( headline='Article 8', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a2.save() self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45)) def test_saving_an_object_again_does_not_create_a_new_object(self): a = Article(headline='original', pub_date=datetime(2014, 5, 16)) a.save() current_id = a.id a.save() self.assertEqual(a.id, current_id) a.headline = 'Updated headline' a.save() self.assertEqual(a.id, current_id) def test_querysets_checking_for_membership(self): headlines = [ 'Parrot programs in Python', 'Second article', 'Third article'] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() a = Article(headline='Some headline', pub_date=some_pub_date) a.save() # You can use 'in' to test for membership... self.assertIn(a, Article.objects.all()) # ... but there will often be more efficient ways if that is all you need: self.assertTrue(Article.objects.filter(id=a.id).exists()) class ModelTest(TestCase): def test_objects_attribute_is_only_available_on_the_class_itself(self): with self.assertRaisesMessage(AttributeError, "Manager isn't accessible via Article instances"): getattr(Article(), "objects",) self.assertFalse(hasattr(Article(), 'objects')) self.assertTrue(hasattr(Article, 'objects')) def test_queryset_delete_removes_all_items_in_that_queryset(self): headlines = [ 'An article', 'Article One', 'Amazing article', 'Boring article'] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() self.assertQuerysetEqual( Article.objects.all().order_by('headline'), ["<Article: Amazing article>", "<Article: An article>", "<Article: Article One>", "<Article: Boring article>"] ) Article.objects.filter(headline__startswith='A').delete() self.assertQuerysetEqual(Article.objects.all().order_by('headline'), ["<Article: Boring article>"]) def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self): some_pub_date = datetime(2014, 5, 16, 12, 1) a1 = Article.objects.create(headline='First', pub_date=some_pub_date) a2 = Article.objects.create(headline='Second', pub_date=some_pub_date) self.assertNotEqual(a1, a2) self.assertEqual(a1, Article.objects.get(id__exact=a1.id)) self.assertNotEqual(Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id)) def test_microsecond_precision(self): a9 = Article( headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180)) def test_manually_specify_primary_key(self): # You can manually specify the primary key when creating a new object. a101 = Article( id=101, headline='Article 101', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a101.save() a101 = Article.objects.get(pk=101) self.assertEqual(a101.headline, 'Article 101') def test_create_method(self): # You can create saved objects in a single step a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) self.assertEqual(Article.objects.get(headline="Article 10"), a10) def test_year_lookup_edge_case(self): # Edge-case test: A year lookup should retrieve all objects in # the given year, including Jan. 1 and Dec. 31. Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2008), ["<Article: Article 11>", "<Article: Article 12>"] ) def test_unicode_data(self): # Unicode data works, too. a = Article( headline='\u6797\u539f \u3081\u3050\u307f', pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual(Article.objects.get(pk=a.id).headline, '\u6797\u539f \u3081\u3050\u307f') def test_hash_function(self): # Model instances have a hash function, so they can be used in sets # or as dictionary keys. Two models compare as equal if their primary # keys are equal. a10 = Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a11 = Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) a12 = Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) s = {a10, a11, a12} self.assertIn(Article.objects.get(headline='Article 11'), s) def test_extra_method_select_argument_with_dashes_and_values(self): # The 'select' argument to extra() supports names with dashes in # them, as long as you use values(). Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) dicts = Article.objects.filter( pub_date__year=2008).extra( select={'dashed-value': '1'}).values('headline', 'dashed-value') self.assertEqual( [sorted(d.items()) for d in dicts], [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]] ) def test_extra_method_select_argument_with_dashes(self): # If you use 'select' with extra() and names containing dashes on a # query that's *not* a values() query, those extra 'select' values # will silently be ignored. Article.objects.create( headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) Article.objects.create( headline='Article 11', pub_date=datetime(2008, 1, 1), ) Article.objects.create( headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) articles = Article.objects.filter( pub_date__year=2008).extra(select={'dashed-value': '1', 'undashedvalue': '2'}) self.assertEqual(articles[0].undashedvalue, 2) def test_create_relation_with_gettext_lazy(self): """ gettext_lazy objects work when saving model instances through various methods. Refs #10498. """ notlazy = 'test' lazy = gettext_lazy(notlazy) Article.objects.create(headline=lazy, pub_date=datetime.now()) article = Article.objects.get() self.assertEqual(article.headline, notlazy) # test that assign + save works with Promise objects article.headline = lazy article.save() self.assertEqual(article.headline, notlazy) # test .update() Article.objects.update(headline=lazy) article = Article.objects.get() self.assertEqual(article.headline, notlazy) # still test bulk_create() Article.objects.all().delete() Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())]) article = Article.objects.get() self.assertEqual(article.headline, notlazy) def test_emptyqs(self): msg = "EmptyQuerySet can't be instantiated" with self.assertRaisesMessage(TypeError, msg): EmptyQuerySet() self.assertIsInstance(Article.objects.none(), EmptyQuerySet) self.assertNotIsInstance('', EmptyQuerySet) def test_emptyqs_values(self): # test for #15959 Article.objects.create(headline='foo', pub_date=datetime.now()) with self.assertNumQueries(0): qs = Article.objects.none().values_list('pk') self.assertIsInstance(qs, EmptyQuerySet) self.assertEqual(len(qs), 0) def test_emptyqs_customqs(self): # A hacky test for custom QuerySet subclass - refs #17271 Article.objects.create(headline='foo', pub_date=datetime.now()) class CustomQuerySet(QuerySet): def do_something(self): return 'did something' qs = Article.objects.all() qs.__class__ = CustomQuerySet qs = qs.none() with self.assertNumQueries(0): self.assertEqual(len(qs), 0) self.assertIsInstance(qs, EmptyQuerySet) self.assertEqual(qs.do_something(), 'did something') def test_emptyqs_values_order(self): # Tests for ticket #17712 Article.objects.create(headline='foo', pub_date=datetime.now()) with self.assertNumQueries(0): self.assertEqual(len(Article.objects.none().values_list('id').order_by('id')), 0) with self.assertNumQueries(0): self.assertEqual(len(Article.objects.none().filter( id__in=Article.objects.values_list('id', flat=True))), 0) @skipUnlessDBFeature('can_distinct_on_fields') def test_emptyqs_distinct(self): # Tests for #19426 Article.objects.create(headline='foo', pub_date=datetime.now()) with self.assertNumQueries(0): self.assertEqual(len(Article.objects.none().distinct('headline', 'pub_date')), 0) def test_ticket_20278(self): sr = SelfRef.objects.create() with self.assertRaises(ObjectDoesNotExist): SelfRef.objects.get(selfref=sr) def test_eq(self): self.assertEqual(Article(id=1), Article(id=1)) self.assertNotEqual(Article(id=1), object()) self.assertNotEqual(object(), Article(id=1)) a = Article() self.assertEqual(a, a) self.assertNotEqual(Article(), a) def test_hash(self): # Value based on PK self.assertEqual(hash(Article(id=1)), hash(1)) msg = 'Model instances without primary key value are unhashable' with self.assertRaisesMessage(TypeError, msg): # No PK value -> unhashable (because save() would then change # hash) hash(Article()) def test_delete_and_access_field(self): # Accessing a field after it's deleted from a model reloads its value. pub_date = datetime.now() article = Article.objects.create(headline='foo', pub_date=pub_date) new_pub_date = article.pub_date + timedelta(days=10) article.headline = 'bar' article.pub_date = new_pub_date del article.headline with self.assertNumQueries(1): self.assertEqual(article.headline, 'foo') # Fields that weren't deleted aren't reloaded. self.assertEqual(article.pub_date, new_pub_date) class ModelLookupTest(TestCase): def setUp(self): # Create an Article. self.a = Article( id=None, headline='Swallow programs in Python', pub_date=datetime(2005, 7, 28), ) # Save it into the database. You have to call save() explicitly. self.a.save() def test_all_lookup(self): # Change values by changing the attributes, then calling save(). self.a.headline = 'Parrot programs in Python' self.a.save() # Article.objects.all() returns all the articles in the database. self.assertQuerysetEqual(Article.objects.all(), ['<Article: Parrot programs in Python>']) def test_rich_lookup(self): # Django provides a rich database lookup API. self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a) self.assertEqual(Article.objects.get(headline__startswith='Swallow'), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a) self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), self.a) self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a) def test_equal_lookup(self): # The "__exact" lookup type can be omitted, as a shortcut. self.assertEqual(Article.objects.get(id=self.a.id), self.a) self.assertEqual(Article.objects.get(headline='Swallow programs in Python'), self.a) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2005), ['<Article: Swallow programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2004), [], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__year=2005, pub_date__month=7), ['<Article: Swallow programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__week_day=5), ['<Article: Swallow programs in Python>'], ) self.assertQuerysetEqual( Article.objects.filter(pub_date__week_day=6), [], ) def test_does_not_exist(self): # Django raises an Article.DoesNotExist exception for get() if the # parameters don't match any object. with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."): Article.objects.get(id__exact=2000,) # To avoid dict-ordering related errors check only one lookup # in single assert. with self.assertRaises(ObjectDoesNotExist): Article.objects.get(pub_date__year=2005, pub_date__month=8) with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."): Article.objects.get(pub_date__week_day=6,) def test_lookup_by_primary_key(self): # Lookup by a primary key is the most common case, so Django # provides a shortcut for primary-key exact lookups. # The following is identical to articles.get(id=a.id). self.assertEqual(Article.objects.get(pk=self.a.id), self.a) # pk can be used as a shortcut for the primary key name in any query. self.assertQuerysetEqual(Article.objects.filter(pk__in=[self.a.id]), ["<Article: Swallow programs in Python>"]) # Model instances of the same type and same ID are considered equal. a = Article.objects.get(pk=self.a.id) b = Article.objects.get(pk=self.a.id) self.assertEqual(a, b) def test_too_many(self): # Create a very similar object a = Article( id=None, headline='Swallow bites Python', pub_date=datetime(2005, 7, 28), ) a.save() self.assertEqual(Article.objects.count(), 2) # Django raises an Article.MultipleObjectsReturned exception if the # lookup matches more than one object msg = "get() returned more than one Article -- it returned 2!" with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(headline__startswith='Swallow',) with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(pub_date__year=2005,) with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(pub_date__year=2005, pub_date__month=7) class ConcurrentSaveTests(TransactionTestCase): available_apps = ['basic'] @skipUnlessDBFeature('test_db_allows_multiple_connections') def test_concurrent_delete_with_save(self): """ Test fetching, deleting and finally saving an object - we should get an insert in this case. """ a = Article.objects.create(headline='foo', pub_date=datetime.now()) exceptions = [] def deleter(): try: # Do not delete a directly - doing so alters its state. Article.objects.filter(pk=a.pk).delete() except Exception as e: exceptions.append(e) finally: connections[DEFAULT_DB_ALIAS].close() self.assertEqual(len(exceptions), 0) t = threading.Thread(target=deleter) t.start() t.join() a.save() self.assertEqual(Article.objects.get(pk=a.pk).headline, 'foo') class ManagerTest(SimpleTestCase): QUERYSET_PROXY_METHODS = [ 'none', 'count', 'dates', 'datetimes', 'distinct', 'extra', 'get', 'get_or_create', 'update_or_create', 'create', 'bulk_create', 'filter', 'aggregate', 'annotate', 'complex_filter', 'exclude', 'in_bulk', 'iterator', 'earliest', 'latest', 'first', 'last', 'order_by', 'select_for_update', 'select_related', 'prefetch_related', 'values', 'values_list', 'update', 'reverse', 'defer', 'only', 'using', 'exists', 'explain', '_insert', '_update', 'raw', 'union', 'intersection', 'difference', ] def test_manager_methods(self): """ This test ensures that the correct set of methods from `QuerySet` are copied onto `Manager`. It's particularly useful to prevent accidentally leaking new methods into `Manager`. New `QuerySet` methods that should also be copied onto `Manager` will need to be added to `ManagerTest.QUERYSET_PROXY_METHODS`. """ self.assertEqual( sorted(BaseManager._get_queryset_methods(QuerySet)), sorted(self.QUERYSET_PROXY_METHODS), ) class SelectOnSaveTests(TestCase): def test_select_on_save(self): a1 = Article.objects.create(pub_date=datetime.now()) with self.assertNumQueries(1): a1.save() asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now()) with self.assertNumQueries(2): asos.save() with self.assertNumQueries(1): asos.save(force_update=True) Article.objects.all().delete() with self.assertRaisesMessage(DatabaseError, 'Forced update did not affect any rows.'): with self.assertNumQueries(1): asos.save(force_update=True) def test_select_on_save_lying_update(self): """ select_on_save works correctly if the database doesn't return correct information about matched rows from UPDATE. """ # Change the manager to not return "row matched" for update(). # We are going to change the Article's _base_manager class # dynamically. This is a bit of a hack, but it seems hard to # test this properly otherwise. Article's manager, because # proxy models use their parent model's _base_manager. orig_class = Article._base_manager._queryset_class class FakeQuerySet(QuerySet): # Make sure the _update method below is in fact called. called = False def _update(self, *args, **kwargs): FakeQuerySet.called = True super()._update(*args, **kwargs) return 0 try: Article._base_manager._queryset_class = FakeQuerySet asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now()) with self.assertNumQueries(3): asos.save() self.assertTrue(FakeQuerySet.called) # This is not wanted behavior, but this is how Django has always # behaved for databases that do not return correct information # about matched rows for UPDATE. with self.assertRaisesMessage(DatabaseError, 'Forced update did not affect any rows.'): asos.save(force_update=True) msg = ( "An error occurred in the current transaction. You can't " "execute queries until the end of the 'atomic' block." ) with self.assertRaisesMessage(DatabaseError, msg): asos.save(update_fields=['pub_date']) finally: Article._base_manager._queryset_class = orig_class class ModelRefreshTests(TestCase): def test_refresh(self): a = Article.objects.create(pub_date=datetime.now()) Article.objects.create(pub_date=datetime.now()) Article.objects.filter(pk=a.pk).update(headline='new headline') with self.assertNumQueries(1): a.refresh_from_db() self.assertEqual(a.headline, 'new headline') orig_pub_date = a.pub_date new_pub_date = a.pub_date + timedelta(10) Article.objects.update(headline='new headline 2', pub_date=new_pub_date) with self.assertNumQueries(1): a.refresh_from_db(fields=['headline']) self.assertEqual(a.headline, 'new headline 2') self.assertEqual(a.pub_date, orig_pub_date) with self.assertNumQueries(1): a.refresh_from_db() self.assertEqual(a.pub_date, new_pub_date) def test_unknown_kwarg(self): s = SelfRef.objects.create() msg = "refresh_from_db() got an unexpected keyword argument 'unknown_kwarg'" with self.assertRaisesMessage(TypeError, msg): s.refresh_from_db(unknown_kwarg=10) def test_refresh_fk(self): s1 = SelfRef.objects.create() s2 = SelfRef.objects.create() s3 = SelfRef.objects.create(selfref=s1) s3_copy = SelfRef.objects.get(pk=s3.pk) s3_copy.selfref.touched = True s3.selfref = s2 s3.save() with self.assertNumQueries(1): s3_copy.refresh_from_db() with self.assertNumQueries(1): # The old related instance was thrown away (the selfref_id has # changed). It needs to be reloaded on access, so one query # executed. self.assertFalse(hasattr(s3_copy.selfref, 'touched')) self.assertEqual(s3_copy.selfref, s2) def test_refresh_null_fk(self): s1 = SelfRef.objects.create() s2 = SelfRef.objects.create(selfref=s1) s2.selfref = None s2.refresh_from_db() self.assertEqual(s2.selfref, s1) def test_refresh_unsaved(self): pub_date = datetime.now() a = Article.objects.create(pub_date=pub_date) a2 = Article(id=a.pk) with self.assertNumQueries(1): a2.refresh_from_db() self.assertEqual(a2.pub_date, pub_date) self.assertEqual(a2._state.db, "default") def test_refresh_fk_on_delete_set_null(self): a = Article.objects.create( headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) s1 = SelfRef.objects.create(article=a) a.delete() s1.refresh_from_db() self.assertIsNone(s1.article_id) self.assertIsNone(s1.article) def test_refresh_no_fields(self): a = Article.objects.create(pub_date=datetime.now()) with self.assertNumQueries(0): a.refresh_from_db(fields=[]) def test_refresh_clears_reverse_related(self): """refresh_from_db() clear cached reverse relations.""" article = Article.objects.create( headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) self.assertFalse(hasattr(article, 'featured')) FeaturedArticle.objects.create(article_id=article.pk) article.refresh_from_db() self.assertTrue(hasattr(article, 'featured')) def test_refresh_clears_one_to_one_field(self): article = Article.objects.create( headline='Parrot programs in Python', pub_date=datetime(2005, 7, 28), ) featured = FeaturedArticle.objects.create(article_id=article.pk) self.assertEqual(featured.article.headline, 'Parrot programs in Python') article.headline = 'Parrot programs in Python 2.0' article.save() featured.refresh_from_db() self.assertEqual(featured.article.headline, 'Parrot programs in Python 2.0')
6214e57a15cf6d7973a9ed3bdc2d4843dd0d38ebbb9d173b602c26d1c65f1a2b
""" Bare-bones model This is a basic model with only two non-primary-key fields. """ from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') pub_date = models.DateTimeField() class Meta: ordering = ('pub_date', 'headline') def __str__(self): return self.headline class FeaturedArticle(models.Model): article = models.OneToOneField(Article, models.CASCADE, related_name='featured') class ArticleSelectOnSave(Article): class Meta: proxy = True select_on_save = True class SelfRef(models.Model): selfref = models.ForeignKey( 'self', models.SET_NULL, null=True, blank=True, related_name='+', ) article = models.ForeignKey(Article, models.SET_NULL, null=True, blank=True) def __str__(self): # This method intentionally doesn't work for all cases - part # of the test for ticket #20278 return SelfRef.objects.get(selfref=self).pk
df0ac71fde4247e8d4e8f60d9c6363fdb184af84328314b7a54c6e581b0953d0
from xml.dom import minidom from django.core import serializers from django.core.serializers.xml_serializer import DTDForbidden from django.test import TestCase, TransactionTestCase from .tests import SerializersTestBase, SerializersTransactionTestBase class XmlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "xml" pkless_str = """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object model="serializers.category"> <field type="CharField" name="name">Reference</field> </object> <object model="serializers.category"> <field type="CharField" name="name">Non-fiction</field> </object> </django-objects>""" mapping_ordering_str = """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object model="serializers.article" pk="%(article_pk)s"> <field name="author" rel="ManyToOneRel" to="serializers.author">%(author_pk)s</field> <field name="headline" type="CharField">Poker has no place on ESPN</field> <field name="pub_date" type="DateTimeField">2006-06-16T11:00:00</field> <field name="categories" rel="ManyToManyRel" to="serializers.category"><object pk="%(first_category_pk)s"></object><object pk="%(second_category_pk)s"></object></field> <field name="meta_data" rel="ManyToManyRel" to="serializers.categorymetadata"></field> </object> </django-objects>""" # NOQA @staticmethod def _validate_output(serial_str): try: minidom.parseString(serial_str) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] dom = minidom.parseString(serial_str) fields = dom.getElementsByTagName("object") for field in fields: ret_list.append(field.getAttribute("pk")) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] dom = minidom.parseString(serial_str) fields = dom.getElementsByTagName("field") for field in fields: if field.getAttribute("name") == field_name: temp = [] for child in field.childNodes: temp.append(child.nodeValue) ret_list.append("".join(temp)) return ret_list def test_control_char_failure(self): """ Serializing control characters with XML should fail as those characters are not supported in the XML 1.0 standard (except HT, LF, CR). """ self.a1.headline = "This contains \u0001 control \u0011 chars" msg = "Article.headline (pk:%s) contains unserializable characters" % self.a1.pk with self.assertRaisesMessage(ValueError, msg): serializers.serialize(self.serializer_name, [self.a1]) self.a1.headline = "HT \u0009, LF \u000A, and CR \u000D are allowed" self.assertIn( "HT \t, LF \n, and CR \r are allowed", serializers.serialize(self.serializer_name, [self.a1]) ) def test_no_dtd(self): """ The XML deserializer shouldn't allow a DTD. This is the most straightforward way to prevent all entity definitions and avoid both external entities and entity-expansion attacks. """ xml = '<?xml version="1.0" standalone="no"?><!DOCTYPE example SYSTEM "http://example.com/example.dtd">' with self.assertRaises(DTDForbidden): next(serializers.deserialize('xml', xml)) class XmlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "xml" fwd_ref_str = """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"> <object pk="1" model="serializers.article"> <field to="serializers.author" name="author" rel="ManyToOneRel">1</field> <field type="CharField" name="headline">Forward references pose no problem</field> <field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field> <field to="serializers.category" name="categories" rel="ManyToManyRel"> <object pk="1"></object> </field> <field to="serializers.categorymetadata" name="meta_data" rel="ManyToManyRel"></field> </object> <object pk="1" model="serializers.author"> <field type="CharField" name="name">Agnes</field> </object> <object pk="1" model="serializers.category"> <field type="CharField" name="name">Reference</field></object> </django-objects>"""
460469a6bb450c2b05a50f1a2c05f1fded0794180eefcd74de3e3a5c4392db83
import importlib import unittest from io import StringIO from django.core import management, serializers from django.core.serializers.base import DeserializationError from django.test import SimpleTestCase, TestCase, TransactionTestCase from .models import Author from .tests import SerializersTestBase, SerializersTransactionTestBase try: import yaml HAS_YAML = True except ImportError: HAS_YAML = False YAML_IMPORT_ERROR_MESSAGE = r'No module named yaml' class YamlImportModuleMock: """Provides a wrapped import_module function to simulate yaml ImportError In order to run tests that verify the behavior of the YAML serializer when run on a system that has yaml installed (like the django CI server), mock import_module, so that it raises an ImportError when the yaml serializer is being imported. The importlib.import_module() call is being made in the serializers.register_serializer(). Refs: #12756 """ def __init__(self): self._import_module = importlib.import_module def import_module(self, module_path): if module_path == serializers.BUILTIN_SERIALIZERS['yaml']: raise ImportError(YAML_IMPORT_ERROR_MESSAGE) return self._import_module(module_path) class NoYamlSerializerTestCase(SimpleTestCase): """Not having pyyaml installed provides a misleading error Refs: #12756 """ @classmethod def setUpClass(cls): """Removes imported yaml and stubs importlib.import_module""" super().setUpClass() cls._import_module_mock = YamlImportModuleMock() importlib.import_module = cls._import_module_mock.import_module # clear out cached serializers to emulate yaml missing serializers._serializers = {} @classmethod def tearDownClass(cls): """Puts yaml back if necessary""" super().tearDownClass() importlib.import_module = cls._import_module_mock._import_module # clear out cached serializers to clean out BadSerializer instances serializers._serializers = {} def test_serializer_pyyaml_error_message(self): """Using yaml serializer without pyyaml raises ImportError""" jane = Author(name="Jane") with self.assertRaises(ImportError): serializers.serialize("yaml", [jane]) def test_deserializer_pyyaml_error_message(self): """Using yaml deserializer without pyyaml raises ImportError""" with self.assertRaises(ImportError): serializers.deserialize("yaml", "") def test_dumpdata_pyyaml_error_message(self): """Calling dumpdata produces an error when yaml package missing""" with self.assertRaisesMessage(management.CommandError, YAML_IMPORT_ERROR_MESSAGE): management.call_command('dumpdata', format='yaml') @unittest.skipUnless(HAS_YAML, "No yaml library detected") class YamlSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "yaml" fwd_ref_str = """- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 pk: 1 model: serializers.article - fields: name: Reference pk: 1 model: serializers.category - fields: name: Agnes pk: 1 model: serializers.author""" pkless_str = """- fields: name: Reference pk: null model: serializers.category - fields: name: Non-fiction model: serializers.category""" mapping_ordering_str = """- model: serializers.article pk: %(article_pk)s fields: author: %(author_pk)s headline: Poker has no place on ESPN pub_date: 2006-06-16 11:00:00 categories: [%(first_category_pk)s, %(second_category_pk)s] meta_data: [] """ @staticmethod def _validate_output(serial_str): try: yaml.safe_load(StringIO(serial_str)) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.safe_load(stream): ret_list.append(obj_dict["pk"]) return ret_list @staticmethod def _get_field_values(serial_str, field_name): ret_list = [] stream = StringIO(serial_str) for obj_dict in yaml.safe_load(stream): if "fields" in obj_dict and field_name in obj_dict["fields"]: field_value = obj_dict["fields"][field_name] # yaml.safe_load will return non-string objects for some # of the fields we are interested in, this ensures that # everything comes back as a string if isinstance(field_value, str): ret_list.append(field_value) else: ret_list.append(str(field_value)) return ret_list def test_yaml_deserializer_exception(self): with self.assertRaises(DeserializationError): for obj in serializers.deserialize("yaml", "{"): pass @unittest.skipUnless(HAS_YAML, "No yaml library detected") class YamlSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "yaml" fwd_ref_str = """- fields: headline: Forward references pose no problem pub_date: 2006-06-16 15:00:00 categories: [1] author: 1 pk: 1 model: serializers.article - fields: name: Reference pk: 1 model: serializers.category - fields: name: Agnes pk: 1 model: serializers.author"""
5ff540b0efce8e4c740bd08064c57b7e681e50d5bacb776f84fb4965926384d2
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, 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. Refs #14823" 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 popuates 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.assertRaises(SerializerDoesNotExist) as cm: serializers.get_serializer("nonsense") self.assertEqual(cm.exception.args, ("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 def setUp(self): sports = Category.objects.create(name="Sports") music = Category.objects.create(name="Music") op_ed = Category.objects.create(name="Op-Ed") self.joe = Author.objects.create(name="Joe") self.jane = Author.objects.create(name="Jane") self.a1 = Article( author=self.jane, headline="Poker has no place on ESPN", pub_date=datetime(2006, 6, 16, 11, 00) ) self.a1.save() self.a1.categories.set([sports, op_ed]) self.a2 = Article( author=self.joe, headline="Time to reform copyright", pub_date=datetime(2006, 6, 16, 13, 00, 11, 345) ) self.a2.save() self.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(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_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_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.all().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', '')) 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.all().count(), 1) art_obj = Article.objects.all()[0] self.assertEqual(art_obj.categories.all().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_))
2ddfb829a0ac5959c2ea4f4f492052db5593746eada61806195ed90b0f89dccb
from django.core import serializers from django.db import connection from django.test import TestCase from .models import Child, FKDataNaturalKey, NaturalKeyAnchor from .tests import register_tests class NaturalKeySerializerTests(TestCase): pass def natural_key_serializer_test(self, format): # Create all the objects defined in the test data with connection.constraint_checks_disabled(): objects = [ NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"), FKDataNaturalKey.objects.create(id=1101, data_id=1100), FKDataNaturalKey.objects.create(id=1102, data_id=None), ] # Serialize the test database serialized_data = serializers.serialize(format, objects, indent=2, use_natural_foreign_keys=True) for obj in serializers.deserialize(format, serialized_data): obj.save() # Assert that the deserialized data is the same # as the original source for obj in objects: instance = obj.__class__.objects.get(id=obj.pk) self.assertEqual( obj.data, instance.data, "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( obj.pk, obj.data, type(obj.data), instance, type(instance.data), ) ) def natural_key_test(self, format): book1 = { 'data': '978-1590597255', 'title': 'The Definitive Guide to Django: Web Development Done Right', } book2 = {'data': '978-1590599969', 'title': 'Practical Django Projects'} # Create the books. adrian = NaturalKeyAnchor.objects.create(**book1) james = NaturalKeyAnchor.objects.create(**book2) # Serialize the books. string_data = serializers.serialize( format, NaturalKeyAnchor.objects.all(), indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True, ) # Delete one book (to prove that the natural key generation will only # restore the primary keys of books found in the database via the # get_natural_key manager method). james.delete() # Deserialize and test. books = list(serializers.deserialize(format, string_data)) self.assertEqual(len(books), 2) self.assertEqual(books[0].object.title, book1['title']) self.assertEqual(books[0].object.pk, adrian.pk) self.assertEqual(books[1].object.title, book2['title']) self.assertIsNone(books[1].object.pk) def natural_pk_mti_test(self, format): """ If serializing objects in a multi-table inheritance relationship using natural primary keys, the natural foreign key for the parent is output in the fields of the child so it's possible to relate the child to the parent when deserializing. """ child_1 = Child.objects.create(parent_data='1', child_data='1') child_2 = Child.objects.create(parent_data='2', child_data='2') string_data = serializers.serialize( format, [child_1.parent_ptr, child_2.parent_ptr, child_2, child_1], use_natural_foreign_keys=True, use_natural_primary_keys=True, ) child_1.delete() child_2.delete() for obj in serializers.deserialize(format, string_data): obj.save() children = Child.objects.all() self.assertEqual(len(children), 2) for child in children: # If it's possible to find the superclass from the subclass and it's # the correct superclass, it's working. self.assertEqual(child.child_data, child.parent_data) # Dynamically register tests for each serializer register_tests(NaturalKeySerializerTests, 'test_%s_natural_key_serializer', natural_key_serializer_test) register_tests(NaturalKeySerializerTests, 'test_%s_serializer_natural_keys', natural_key_test) register_tests(NaturalKeySerializerTests, 'test_%s_serializer_natural_pks_mti', natural_pk_mti_test)
c7b2f8dcbd4b752e764cc2ed971a88d683494f7ece2ce1ab76dfa19f832f8d60
""" A test spanning all the capabilities of all the serializers. This class defines sample data and a dynamically generated test case that is capable of testing the capabilities of the serializers. This includes all valid data values, plus forward, backwards and self references. """ import datetime import decimal import uuid from django.core import serializers from django.db import connection, models from django.test import TestCase from .models import ( Anchor, AutoNowDateTimeData, BigIntegerData, BinaryData, BooleanData, BooleanPKData, CharData, CharPKData, DateData, DatePKData, DateTimeData, DateTimePKData, DecimalData, DecimalPKData, EmailData, EmailPKData, ExplicitInheritBaseModel, FileData, FilePathData, FilePathPKData, FKData, FKDataToField, FKDataToO2O, FKSelfData, FKToUUID, FloatData, FloatPKData, GenericData, GenericIPAddressData, GenericIPAddressPKData, InheritAbstractModel, InheritBaseModel, IntegerData, IntegerPKData, Intermediate, LengthModel, M2MData, M2MIntermediateData, M2MSelfData, ModifyingSaveData, NullBooleanData, O2OData, PositiveIntegerData, PositiveIntegerPKData, PositiveSmallIntegerData, PositiveSmallIntegerPKData, SlugData, SlugPKData, SmallData, SmallPKData, Tag, TextData, TimeData, UniqueAnchor, UUIDData, ) from .tests import register_tests # A set of functions that can be used to recreate # test data objects of various kinds. # The save method is a raw base model save, to make # sure that the data in the database matches the # exact test case. def data_create(pk, klass, data): instance = klass(id=pk) instance.data = data models.Model.save_base(instance, raw=True) return [instance] def generic_create(pk, klass, data): instance = klass(id=pk) instance.data = data[0] models.Model.save_base(instance, raw=True) for tag in data[1:]: instance.tags.create(data=tag) return [instance] def fk_create(pk, klass, data): instance = klass(id=pk) setattr(instance, 'data_id', data) models.Model.save_base(instance, raw=True) return [instance] def m2m_create(pk, klass, data): instance = klass(id=pk) models.Model.save_base(instance, raw=True) instance.data.set(data) return [instance] def im2m_create(pk, klass, data): instance = klass(id=pk) models.Model.save_base(instance, raw=True) return [instance] def im_create(pk, klass, data): instance = klass(id=pk) instance.right_id = data['right'] instance.left_id = data['left'] if 'extra' in data: instance.extra = data['extra'] models.Model.save_base(instance, raw=True) return [instance] def o2o_create(pk, klass, data): instance = klass() instance.data_id = data models.Model.save_base(instance, raw=True) return [instance] def pk_create(pk, klass, data): instance = klass() instance.data = data models.Model.save_base(instance, raw=True) return [instance] def inherited_create(pk, klass, data): instance = klass(id=pk, **data) # This isn't a raw save because: # 1) we're testing inheritance, not field behavior, so none # of the field values need to be protected. # 2) saving the child class and having the parent created # automatically is easier than manually creating both. models.Model.save(instance) created = [instance] for klass in instance._meta.parents: created.append(klass.objects.get(id=pk)) return created # A set of functions that can be used to compare # test data objects of various kinds def data_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) if klass == BinaryData and data is not None: testcase.assertEqual( bytes(data), bytes(instance.data), "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( pk, repr(bytes(data)), type(data), repr(bytes(instance.data)), type(instance.data), ) ) else: testcase.assertEqual( data, instance.data, "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( pk, data, type(data), instance, type(instance.data), ) ) def generic_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data[0], instance.data) testcase.assertEqual(data[1:], [t.data for t in instance.tags.order_by('id')]) def fk_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data, instance.data_id) def m2m_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')]) def im2m_compare(testcase, pk, klass, data): klass.objects.get(id=pk) # actually nothing else to check, the instance just should exist def im_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) testcase.assertEqual(data['left'], instance.left_id) testcase.assertEqual(data['right'], instance.right_id) if 'extra' in data: testcase.assertEqual(data['extra'], instance.extra) else: testcase.assertEqual("doesn't matter", instance.extra) def o2o_compare(testcase, pk, klass, data): instance = klass.objects.get(data=data) testcase.assertEqual(data, instance.data_id) def pk_compare(testcase, pk, klass, data): instance = klass.objects.get(data=data) testcase.assertEqual(data, instance.data) def inherited_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) for key, value in data.items(): testcase.assertEqual(value, getattr(instance, key)) # Define some data types. Each data type is # actually a pair of functions; one to create # and one to compare objects of that type data_obj = (data_create, data_compare) generic_obj = (generic_create, generic_compare) fk_obj = (fk_create, fk_compare) m2m_obj = (m2m_create, m2m_compare) im2m_obj = (im2m_create, im2m_compare) im_obj = (im_create, im_compare) o2o_obj = (o2o_create, o2o_compare) pk_obj = (pk_create, pk_compare) inherited_obj = (inherited_create, inherited_compare) uuid_obj = uuid.uuid4() test_data = [ # Format: (data type, PK value, Model Class, data) (data_obj, 1, BinaryData, memoryview(b"\x05\xFD\x00")), (data_obj, 2, BinaryData, None), (data_obj, 5, BooleanData, True), (data_obj, 6, BooleanData, False), (data_obj, 7, BooleanData, None), (data_obj, 10, CharData, "Test Char Data"), (data_obj, 11, CharData, ""), (data_obj, 12, CharData, "None"), (data_obj, 13, CharData, "null"), (data_obj, 14, CharData, "NULL"), (data_obj, 15, CharData, None), # (We use something that will fit into a latin1 database encoding here, # because that is still the default used on many system setups.) (data_obj, 16, CharData, '\xa5'), (data_obj, 20, DateData, datetime.date(2006, 6, 16)), (data_obj, 21, DateData, None), (data_obj, 30, DateTimeData, datetime.datetime(2006, 6, 16, 10, 42, 37)), (data_obj, 31, DateTimeData, None), (data_obj, 40, EmailData, "[email protected]"), (data_obj, 41, EmailData, None), (data_obj, 42, EmailData, ""), (data_obj, 50, FileData, 'file:///foo/bar/whiz.txt'), # (data_obj, 51, FileData, None), (data_obj, 52, FileData, ""), (data_obj, 60, FilePathData, "/foo/bar/whiz.txt"), (data_obj, 61, FilePathData, None), (data_obj, 62, FilePathData, ""), (data_obj, 70, DecimalData, decimal.Decimal('12.345')), (data_obj, 71, DecimalData, decimal.Decimal('-12.345')), (data_obj, 72, DecimalData, decimal.Decimal('0.0')), (data_obj, 73, DecimalData, None), (data_obj, 74, FloatData, 12.345), (data_obj, 75, FloatData, -12.345), (data_obj, 76, FloatData, 0.0), (data_obj, 77, FloatData, None), (data_obj, 80, IntegerData, 123456789), (data_obj, 81, IntegerData, -123456789), (data_obj, 82, IntegerData, 0), (data_obj, 83, IntegerData, None), # (XX, ImageData (data_obj, 95, GenericIPAddressData, "fe80:1424:2223:6cff:fe8a:2e8a:2151:abcd"), (data_obj, 96, GenericIPAddressData, None), (data_obj, 100, NullBooleanData, True), (data_obj, 101, NullBooleanData, False), (data_obj, 102, NullBooleanData, None), (data_obj, 120, PositiveIntegerData, 123456789), (data_obj, 121, PositiveIntegerData, None), (data_obj, 130, PositiveSmallIntegerData, 12), (data_obj, 131, PositiveSmallIntegerData, None), (data_obj, 140, SlugData, "this-is-a-slug"), (data_obj, 141, SlugData, None), (data_obj, 142, SlugData, ""), (data_obj, 150, SmallData, 12), (data_obj, 151, SmallData, -12), (data_obj, 152, SmallData, 0), (data_obj, 153, SmallData, None), (data_obj, 160, TextData, """This is a long piece of text. It contains line breaks. Several of them. The end."""), (data_obj, 161, TextData, ""), (data_obj, 162, TextData, None), (data_obj, 170, TimeData, datetime.time(10, 42, 37)), (data_obj, 171, TimeData, None), (generic_obj, 200, GenericData, ['Generic Object 1', 'tag1', 'tag2']), (generic_obj, 201, GenericData, ['Generic Object 2', 'tag2', 'tag3']), (data_obj, 300, Anchor, "Anchor 1"), (data_obj, 301, Anchor, "Anchor 2"), (data_obj, 302, UniqueAnchor, "UAnchor 1"), (fk_obj, 400, FKData, 300), # Post reference (fk_obj, 401, FKData, 500), # Pre reference (fk_obj, 402, FKData, None), # Empty reference (m2m_obj, 410, M2MData, []), # Empty set (m2m_obj, 411, M2MData, [300, 301]), # Post reference (m2m_obj, 412, M2MData, [500, 501]), # Pre reference (m2m_obj, 413, M2MData, [300, 301, 500, 501]), # Pre and Post reference (o2o_obj, None, O2OData, 300), # Post reference (o2o_obj, None, O2OData, 500), # Pre reference (fk_obj, 430, FKSelfData, 431), # Pre reference (fk_obj, 431, FKSelfData, 430), # Post reference (fk_obj, 432, FKSelfData, None), # Empty reference (m2m_obj, 440, M2MSelfData, []), (m2m_obj, 441, M2MSelfData, []), (m2m_obj, 442, M2MSelfData, [440, 441]), (m2m_obj, 443, M2MSelfData, [445, 446]), (m2m_obj, 444, M2MSelfData, [440, 441, 445, 446]), (m2m_obj, 445, M2MSelfData, []), (m2m_obj, 446, M2MSelfData, []), (fk_obj, 450, FKDataToField, "UAnchor 1"), (fk_obj, 451, FKDataToField, "UAnchor 2"), (fk_obj, 452, FKDataToField, None), (fk_obj, 460, FKDataToO2O, 300), (im2m_obj, 470, M2MIntermediateData, None), # testing post- and pre-references and extra fields (im_obj, 480, Intermediate, {'right': 300, 'left': 470}), (im_obj, 481, Intermediate, {'right': 300, 'left': 490}), (im_obj, 482, Intermediate, {'right': 500, 'left': 470}), (im_obj, 483, Intermediate, {'right': 500, 'left': 490}), (im_obj, 484, Intermediate, {'right': 300, 'left': 470, 'extra': "extra"}), (im_obj, 485, Intermediate, {'right': 300, 'left': 490, 'extra': "extra"}), (im_obj, 486, Intermediate, {'right': 500, 'left': 470, 'extra': "extra"}), (im_obj, 487, Intermediate, {'right': 500, 'left': 490, 'extra': "extra"}), (im2m_obj, 490, M2MIntermediateData, []), (data_obj, 500, Anchor, "Anchor 3"), (data_obj, 501, Anchor, "Anchor 4"), (data_obj, 502, UniqueAnchor, "UAnchor 2"), (pk_obj, 601, BooleanPKData, True), (pk_obj, 602, BooleanPKData, False), (pk_obj, 610, CharPKData, "Test Char PKData"), (pk_obj, 620, DatePKData, datetime.date(2006, 6, 16)), (pk_obj, 630, DateTimePKData, datetime.datetime(2006, 6, 16, 10, 42, 37)), (pk_obj, 640, EmailPKData, "[email protected]"), # (pk_obj, 650, FilePKData, 'file:///foo/bar/whiz.txt'), (pk_obj, 660, FilePathPKData, "/foo/bar/whiz.txt"), (pk_obj, 670, DecimalPKData, decimal.Decimal('12.345')), (pk_obj, 671, DecimalPKData, decimal.Decimal('-12.345')), (pk_obj, 672, DecimalPKData, decimal.Decimal('0.0')), (pk_obj, 673, FloatPKData, 12.345), (pk_obj, 674, FloatPKData, -12.345), (pk_obj, 675, FloatPKData, 0.0), (pk_obj, 680, IntegerPKData, 123456789), (pk_obj, 681, IntegerPKData, -123456789), (pk_obj, 682, IntegerPKData, 0), # (XX, ImagePKData (pk_obj, 695, GenericIPAddressPKData, "fe80:1424:2223:6cff:fe8a:2e8a:2151:abcd"), (pk_obj, 720, PositiveIntegerPKData, 123456789), (pk_obj, 730, PositiveSmallIntegerPKData, 12), (pk_obj, 740, SlugPKData, "this-is-a-slug"), (pk_obj, 750, SmallPKData, 12), (pk_obj, 751, SmallPKData, -12), (pk_obj, 752, SmallPKData, 0), # (pk_obj, 760, TextPKData, """This is a long piece of text. # It contains line breaks. # Several of them. # The end."""), # (pk_obj, 770, TimePKData, datetime.time(10, 42, 37)), # (pk_obj, 790, XMLPKData, "<foo></foo>"), (pk_obj, 791, UUIDData, uuid_obj), (fk_obj, 792, FKToUUID, uuid_obj), (data_obj, 800, AutoNowDateTimeData, datetime.datetime(2006, 6, 16, 10, 42, 37)), (data_obj, 810, ModifyingSaveData, 42), (inherited_obj, 900, InheritAbstractModel, {'child_data': 37, 'parent_data': 42}), (inherited_obj, 910, ExplicitInheritBaseModel, {'child_data': 37, 'parent_data': 42}), (inherited_obj, 920, InheritBaseModel, {'child_data': 37, 'parent_data': 42}), (data_obj, 1000, BigIntegerData, 9223372036854775807), (data_obj, 1001, BigIntegerData, -9223372036854775808), (data_obj, 1002, BigIntegerData, 0), (data_obj, 1003, BigIntegerData, None), (data_obj, 1004, LengthModel, 0), (data_obj, 1005, LengthModel, 1), ] # Because Oracle treats the empty string as NULL, Oracle is expected to fail # when field.empty_strings_allowed is True and the value is None; skip these # tests. if connection.features.interprets_empty_strings_as_nulls: test_data = [data for data in test_data if not (data[0] == data_obj and data[2]._meta.get_field('data').empty_strings_allowed and data[3] is None)] # Regression test for #8651 -- a FK to an object with PK of 0 # This won't work on MySQL since it won't let you create an object # with an autoincrement primary key of 0, if connection.features.allows_auto_pk_0: test_data.extend([ (data_obj, 0, Anchor, "Anchor 0"), (fk_obj, 465, FKData, 0), ]) class SerializerDataTests(TestCase): pass def serializerTest(self, format): # Create all the objects defined in the test data objects = [] instance_count = {} for (func, pk, klass, datum) in test_data: with connection.constraint_checks_disabled(): objects.extend(func[0](pk, klass, datum)) # Get a count of the number of objects created for each class for klass in instance_count: instance_count[klass] = klass.objects.count() # Add the generic tagged objects to the object list objects.extend(Tag.objects.all()) # Serialize the test database serialized_data = serializers.serialize(format, objects, indent=2) for obj in serializers.deserialize(format, serialized_data): obj.save() # Assert that the deserialized data is the same # as the original source for (func, pk, klass, datum) in test_data: func[1](self, pk, klass, datum) # Assert that the number of objects deserialized is the # same as the number that was serialized. for klass, count in instance_count.items(): self.assertEqual(count, klass.objects.count()) register_tests(SerializerDataTests, 'test_%s_serializer', serializerTest)
1222f8ee3238f060d3608a676064417a6a805ffb40042ef185a45c26a6c36467
import datetime import decimal import json import re from django.core import serializers from django.core.serializers.base import DeserializationError from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.test import SimpleTestCase, TestCase, TransactionTestCase from django.test.utils import isolate_apps from django.utils.translation import gettext_lazy, override from .models import Score from .tests import SerializersTestBase, SerializersTransactionTestBase class JsonSerializerTestCase(SerializersTestBase, TestCase): serializer_name = "json" pkless_str = """[ { "pk": null, "model": "serializers.category", "fields": {"name": "Reference"} }, { "model": "serializers.category", "fields": {"name": "Non-fiction"} }]""" mapping_ordering_str = """[ { "model": "serializers.article", "pk": %(article_pk)s, "fields": { "author": %(author_pk)s, "headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T11:00:00", "categories": [ %(first_category_pk)s, %(second_category_pk)s ], "meta_data": [] } } ] """ @staticmethod def _validate_output(serial_str): try: json.loads(serial_str) except Exception: return False else: return True @staticmethod def _get_pk_values(serial_str): serial_list = json.loads(serial_str) return [obj_dict['pk'] for obj_dict in serial_list] @staticmethod def _get_field_values(serial_str, field_name): serial_list = json.loads(serial_str) return [obj_dict['fields'][field_name] for obj_dict in serial_list if field_name in obj_dict['fields']] def test_indentation_whitespace(self): s = serializers.json.Serializer() json_data = s.serialize([Score(score=5.0), Score(score=6.0)], indent=2) for line in json_data.splitlines(): if re.search(r'.+,\s*$', line): self.assertEqual(line, line.rstrip()) @isolate_apps('serializers') def test_custom_encoder(self): class ScoreDecimal(models.Model): score = models.DecimalField() class CustomJSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return str(o) return super().default(o) s = serializers.json.Serializer() json_data = s.serialize( [ScoreDecimal(score=decimal.Decimal(1.0))], cls=CustomJSONEncoder ) self.assertIn('"fields": {"score": "1"}', json_data) def test_json_deserializer_exception(self): with self.assertRaises(DeserializationError): for obj in serializers.deserialize("json", """[{"pk":1}"""): pass def test_helpful_error_message_invalid_pk(self): """ If there is an invalid primary key, the error message should contain the model associated with it. """ test_string = """[{ "pk": "badpk", "model": "serializers.player", "fields": { "name": "Bob", "rank": 1, "team": "Team" } }]""" with self.assertRaisesMessage(DeserializationError, "(serializers.player:pk=badpk)"): list(serializers.deserialize('json', test_string)) def test_helpful_error_message_invalid_field(self): """ If there is an invalid field value, the error message should contain the model associated with it. """ test_string = """[{ "pk": "1", "model": "serializers.player", "fields": { "name": "Bob", "rank": "invalidint", "team": "Team" } }]""" expected = "(serializers.player:pk=1) field_value was 'invalidint'" with self.assertRaisesMessage(DeserializationError, expected): list(serializers.deserialize('json', test_string)) def test_helpful_error_message_for_foreign_keys(self): """ Invalid foreign keys with a natural key should throw a helpful error message, such as what the failing key is. """ test_string = """[{ "pk": 1, "model": "serializers.category", "fields": { "name": "Unknown foreign key", "meta_data": [ "doesnotexist", "metadata" ] } }]""" key = ["doesnotexist", "metadata"] expected = "(serializers.category:pk=1) field_value was '%r'" % key with self.assertRaisesMessage(DeserializationError, expected): list(serializers.deserialize('json', test_string)) def test_helpful_error_message_for_many2many_non_natural(self): """ Invalid many-to-many keys should throw a helpful error message. """ test_string = """[{ "pk": 1, "model": "serializers.article", "fields": { "author": 1, "headline": "Unknown many to many", "pub_date": "2014-09-15T10:35:00", "categories": [1, "doesnotexist"] } }, { "pk": 1, "model": "serializers.author", "fields": { "name": "Agnes" } }, { "pk": 1, "model": "serializers.category", "fields": { "name": "Reference" } }]""" expected = "(serializers.article:pk=1) field_value was 'doesnotexist'" with self.assertRaisesMessage(DeserializationError, expected): list(serializers.deserialize('json', test_string)) def test_helpful_error_message_for_many2many_natural1(self): """ Invalid many-to-many keys should throw a helpful error message. This tests the code path where one of a list of natural keys is invalid. """ test_string = """[{ "pk": 1, "model": "serializers.categorymetadata", "fields": { "kind": "author", "name": "meta1", "value": "Agnes" } }, { "pk": 1, "model": "serializers.article", "fields": { "author": 1, "headline": "Unknown many to many", "pub_date": "2014-09-15T10:35:00", "meta_data": [ ["author", "meta1"], ["doesnotexist", "meta1"], ["author", "meta1"] ] } }, { "pk": 1, "model": "serializers.author", "fields": { "name": "Agnes" } }]""" key = ["doesnotexist", "meta1"] expected = "(serializers.article:pk=1) field_value was '%r'" % key with self.assertRaisesMessage(DeserializationError, expected): for obj in serializers.deserialize('json', test_string): obj.save() def test_helpful_error_message_for_many2many_natural2(self): """ Invalid many-to-many keys should throw a helpful error message. This tests the code path where a natural many-to-many key has only a single value. """ test_string = """[{ "pk": 1, "model": "serializers.article", "fields": { "author": 1, "headline": "Unknown many to many", "pub_date": "2014-09-15T10:35:00", "meta_data": [1, "doesnotexist"] } }, { "pk": 1, "model": "serializers.categorymetadata", "fields": { "kind": "author", "name": "meta1", "value": "Agnes" } }, { "pk": 1, "model": "serializers.author", "fields": { "name": "Agnes" } }]""" expected = "(serializers.article:pk=1) field_value was 'doesnotexist'" with self.assertRaisesMessage(DeserializationError, expected): for obj in serializers.deserialize('json', test_string, ignore=False): obj.save() class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase): serializer_name = "json" fwd_ref_str = """[ { "pk": 1, "model": "serializers.article", "fields": { "headline": "Forward references pose no problem", "pub_date": "2006-06-16T15:00:00", "categories": [1], "author": 1 } }, { "pk": 1, "model": "serializers.category", "fields": { "name": "Reference" } }, { "pk": 1, "model": "serializers.author", "fields": { "name": "Agnes" } }]""" class DjangoJSONEncoderTests(SimpleTestCase): def test_lazy_string_encoding(self): self.assertEqual( json.dumps({'lang': gettext_lazy("French")}, cls=DjangoJSONEncoder), '{"lang": "French"}' ) with override('fr'): self.assertEqual( json.dumps({'lang': gettext_lazy("French")}, cls=DjangoJSONEncoder), '{"lang": "Fran\\u00e7ais"}' ) def test_timedelta(self): duration = datetime.timedelta(days=1, hours=2, seconds=3) self.assertEqual( json.dumps({'duration': duration}, cls=DjangoJSONEncoder), '{"duration": "P1DT02H00M03S"}' ) duration = datetime.timedelta(0) self.assertEqual( json.dumps({'duration': duration}, cls=DjangoJSONEncoder), '{"duration": "P0DT00H00M00S"}' )
e9ccf72da8c839c6c4a0e0ecf4514fef5bcb10453d8a7c03b20da5495b5aecb0
from django.core.serializers.base import DeserializedObject from django.test import SimpleTestCase from .models import Author class TestDeserializedObjectTests(SimpleTestCase): def test_repr(self): author = Author(name='John', pk=1) deserial_obj = DeserializedObject(obj=author) self.assertEqual(repr(deserial_obj), '<DeserializedObject: serializers.Author(pk=1)>')
7da4423c790bd501fcb79debd7dd7bd30c75d0b2469e350a932541ed65fd96c8
# Required for migration detection (#22645)
fe5cc8affb6aca4982d0c82fbbb768bc384588ade44ffa0626ed64dcab475ec7
from datetime import date from django import forms from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry from django.contrib.admin.options import ( HORIZONTAL, VERTICAL, ModelAdmin, TabularInline, get_content_type_for_model, ) from django.contrib.admin.sites import AdminSite from django.contrib.admin.widgets import ( AdminDateWidget, AdminRadioSelect, AutocompleteSelect, AutocompleteSelectMultiple, ) from django.contrib.auth.models import User from django.db import models from django.forms.widgets import Select from django.test import SimpleTestCase, TestCase from django.test.utils import isolate_apps from .models import Band, Concert, Song class MockRequest: pass class MockSuperUser: def has_perm(self, perm): return True request = MockRequest() request.user = MockSuperUser() class ModelAdminTests(TestCase): def setUp(self): self.band = Band.objects.create( name='The Doors', bio='', sign_date=date(1965, 1, 1), ) self.site = AdminSite() def test_modeladmin_str(self): ma = ModelAdmin(Band, self.site) self.assertEqual(str(ma), 'modeladmin.ModelAdmin') # form/fields/fieldsets interaction ############################## def test_default_fields(self): ma = ModelAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date']) self.assertEqual(list(ma.get_fields(request)), ['name', 'bio', 'sign_date']) self.assertEqual(list(ma.get_fields(request, self.band)), ['name', 'bio', 'sign_date']) self.assertIsNone(ma.get_exclude(request, self.band)) def test_default_fieldsets(self): # fieldsets_add and fieldsets_change should return a special data structure that # is used in the templates. They should generate the "right thing" whether we # have specified a custom form, the fields argument, or nothing at all. # # Here's the default case. There are no custom form_add/form_change methods, # no fields argument, and no fieldsets argument. ma = ModelAdmin(Band, self.site) self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name', 'bio', 'sign_date']})]) self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name', 'bio', 'sign_date']})]) def test_get_fieldsets(self): # get_fieldsets() is called when figuring out form fields (#18681). class BandAdmin(ModelAdmin): def get_fieldsets(self, request, obj=None): return [(None, {'fields': ['name', 'bio']})] ma = BandAdmin(Band, self.site) form = ma.get_form(None) self.assertEqual(form._meta.fields, ['name', 'bio']) class InlineBandAdmin(TabularInline): model = Concert fk_name = 'main_band' can_delete = False def get_fieldsets(self, request, obj=None): return [(None, {'fields': ['day', 'transport']})] ma = InlineBandAdmin(Band, self.site) form = ma.get_formset(None).form self.assertEqual(form._meta.fields, ['day', 'transport']) def test_lookup_allowed_allows_nonexistent_lookup(self): """ A lookup_allowed allows a parameter whose field lookup doesn't exist. (#21129). """ class BandAdmin(ModelAdmin): fields = ['name'] ma = BandAdmin(Band, self.site) self.assertTrue(ma.lookup_allowed('name__nonexistent', 'test_value')) @isolate_apps('modeladmin') def test_lookup_allowed_onetoone(self): class Department(models.Model): code = models.CharField(max_length=4, unique=True) class Employee(models.Model): department = models.ForeignKey(Department, models.CASCADE, to_field="code") class EmployeeProfile(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) class EmployeeInfo(models.Model): employee = models.OneToOneField(Employee, models.CASCADE) description = models.CharField(max_length=100) class EmployeeProfileAdmin(ModelAdmin): list_filter = [ 'employee__employeeinfo__description', 'employee__department__code', ] ma = EmployeeProfileAdmin(EmployeeProfile, self.site) # Reverse OneToOneField self.assertIs(ma.lookup_allowed('employee__employeeinfo__description', 'test_value'), True) # OneToOneField and ForeignKey self.assertIs(ma.lookup_allowed('employee__department__code', 'test_value'), True) def test_field_arguments(self): # If fields is specified, fieldsets_add and fieldsets_change should # just stick the fields into a formsets structure and return it. class BandAdmin(ModelAdmin): fields = ['name'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_fields(request)), ['name']) self.assertEqual(list(ma.get_fields(request, self.band)), ['name']) self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name']})]) self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name']})]) def test_field_arguments_restricted_on_form(self): # If fields or fieldsets is specified, it should exclude fields on the # Form class to the fields specified. This may cause errors to be # raised in the db layer if required model fields aren't in fields/ # fieldsets, but that's preferable to ghost errors where a field in the # Form class isn't being displayed because it's not in fields/fieldsets. # Using `fields`. class BandAdmin(ModelAdmin): fields = ['name'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name']) # Using `fieldsets`. class BandAdmin(ModelAdmin): fieldsets = [(None, {'fields': ['name']})] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name']) # Using `exclude`. class BandAdmin(ModelAdmin): exclude = ['bio'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) # You can also pass a tuple to `exclude`. class BandAdmin(ModelAdmin): exclude = ('bio',) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) # Using `fields` and `exclude`. class BandAdmin(ModelAdmin): fields = ['name', 'bio'] exclude = ['bio'] ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) def test_custom_form_meta_exclude_with_readonly(self): """ The custom ModelForm's `Meta.exclude` is respected when used in conjunction with `ModelAdmin.readonly_fields` and when no `ModelAdmin.exclude` is defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ['bio'] class BandAdmin(ModelAdmin): readonly_fields = ['name'] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['sign_date']) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): readonly_fields = ['transport'] form = AdminConcertForm fk_name = 'main_band' model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'opening_band', 'id', 'DELETE']) def test_custom_formfield_override_readonly(self): class AdminBandForm(forms.ModelForm): name = forms.CharField() class Meta: exclude = () model = Band class BandAdmin(ModelAdmin): form = AdminBandForm readonly_fields = ['name'] ma = BandAdmin(Band, self.site) # `name` shouldn't appear in base_fields because it's part of # readonly_fields. self.assertEqual( list(ma.get_form(request).base_fields), ['bio', 'sign_date'] ) # But it should appear in get_fields()/fieldsets() so it can be # displayed as read-only. self.assertEqual( list(ma.get_fields(request)), ['bio', 'sign_date', 'name'] ) self.assertEqual( list(ma.get_fieldsets(request)), [(None, {'fields': ['bio', 'sign_date', 'name']})] ) def test_custom_form_meta_exclude(self): """ The custom ModelForm's `Meta.exclude` is overridden if `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined (#14496). """ # With ModelAdmin class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ['bio'] class BandAdmin(ModelAdmin): exclude = ['name'] form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['bio', 'sign_date']) # With InlineModelAdmin class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): exclude = ['transport'] form = AdminConcertForm fk_name = 'main_band' model = Concert class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'opening_band', 'day', 'id', 'DELETE'] ) def test_overriding_get_exclude(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): return ['name'] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ['bio', 'sign_date'] ) def test_get_exclude_overrides_exclude(self): class BandAdmin(ModelAdmin): exclude = ['bio'] def get_exclude(self, request, obj=None): return ['name'] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request).base_fields), ['bio', 'sign_date'] ) def test_get_exclude_takes_obj(self): class BandAdmin(ModelAdmin): def get_exclude(self, request, obj=None): if obj: return ['sign_date'] return ['name'] self.assertEqual( list(BandAdmin(Band, self.site).get_form(request, self.band).base_fields), ['name', 'bio'] ) def test_custom_form_validation(self): # If a form is specified, it should use it allowing custom validation # to work properly. This won't break any of the admin widgets or media. class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date', 'delete']) self.assertEqual(type(ma.get_form(request).base_fields['sign_date'].widget), AdminDateWidget) def test_form_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `ModelAdmin.get_form()` overrides all other declarations (#8999). """ class AdminBandForm(forms.ModelForm): class Meta: model = Band exclude = ['name'] class BandAdmin(ModelAdmin): exclude = ['sign_date'] form = AdminBandForm def get_form(self, request, obj=None, **kwargs): kwargs['exclude'] = ['bio'] return super().get_form(request, obj, **kwargs) ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) def test_formset_exclude_kwarg_override(self): """ The `exclude` kwarg passed to `InlineModelAdmin.get_formset()` overrides all other declarations (#8999). """ class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): exclude = ['transport'] form = AdminConcertForm fk_name = 'main_band' model = Concert def get_formset(self, request, obj=None, **kwargs): kwargs['exclude'] = ['opening_band'] return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'day', 'transport', 'id', 'DELETE'] ) def test_formset_overriding_get_exclude_with_form_fields(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert fields = ['main_band', 'opening_band', 'day', 'transport'] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = 'main_band' model = Concert def get_exclude(self, request, obj=None): return ['opening_band'] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'day', 'transport', 'id', 'DELETE'] ) def test_formset_overriding_get_exclude_with_form_exclude(self): class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ['day'] class ConcertInline(TabularInline): form = AdminConcertForm fk_name = 'main_band' model = Concert def get_exclude(self, request, obj=None): return ['opening_band'] class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['main_band', 'day', 'transport', 'id', 'DELETE'] ) def test_queryset_override(self): # If the queryset of a ModelChoiceField in a custom form is overridden, # RelatedFieldWidgetWrapper doesn't mess that up. band2 = Band.objects.create(name='The Beatles', bio='', sign_date=date(1962, 1, 1)) ma = ModelAdmin(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper">' '<select name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Beatles</option>' '<option value="%d">The Doors</option>' '</select></div>' % (band2.id, self.band.id) ) class AdminConcertForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["main_band"].queryset = Band.objects.filter(name='The Doors') class ConcertAdminWithForm(ModelAdmin): form = AdminConcertForm ma = ConcertAdminWithForm(Concert, self.site) form = ma.get_form(request)() self.assertHTMLEqual( str(form["main_band"]), '<div class="related-widget-wrapper">' '<select name="main_band" id="id_main_band" required>' '<option value="" selected>---------</option>' '<option value="%d">The Doors</option>' '</select></div>' % self.band.id ) def test_regression_for_ticket_15820(self): """ `obj` is passed from `InlineModelAdmin.get_fieldsets()` to `InlineModelAdmin.get_formset()`. """ class CustomConcertForm(forms.ModelForm): class Meta: model = Concert fields = ['day'] class ConcertInline(TabularInline): model = Concert fk_name = 'main_band' def get_formset(self, request, obj=None, **kwargs): if obj: kwargs['form'] = CustomConcertForm return super().get_formset(request, obj, **kwargs) class BandAdmin(ModelAdmin): inlines = [ConcertInline] Concert.objects.create(main_band=self.band, opening_band=self.band, day=1) ma = BandAdmin(Band, self.site) inline_instances = ma.get_inline_instances(request) fieldsets = list(inline_instances[0].get_fieldsets(request)) self.assertEqual(fieldsets[0][1]['fields'], ['main_band', 'opening_band', 'day', 'transport']) fieldsets = list(inline_instances[0].get_fieldsets(request, inline_instances[0].model)) self.assertEqual(fieldsets[0][1]['fields'], ['day']) # radio_fields behavior ########################################### def test_default_foreign_key_widget(self): # First, without any radio_fields specified, the widgets for ForeignKey # and fields with choices specified ought to be a basic Select widget. # ForeignKey widgets in the admin are wrapped with RelatedFieldWidgetWrapper so # they need to be handled properly when type checking. For Select fields, all of # the choices lists have a first entry of dashes. cma = ModelAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), Select) self.assertEqual( list(cmafa.base_fields['main_band'].widget.choices), [('', '---------'), (self.band.id, 'The Doors')]) self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), Select) self.assertEqual( list(cmafa.base_fields['opening_band'].widget.choices), [('', '---------'), (self.band.id, 'The Doors')] ) self.assertEqual(type(cmafa.base_fields['day'].widget), Select) self.assertEqual( list(cmafa.base_fields['day'].widget.choices), [('', '---------'), (1, 'Fri'), (2, 'Sat')] ) self.assertEqual(type(cmafa.base_fields['transport'].widget), Select) self.assertEqual( list(cmafa.base_fields['transport'].widget.choices), [('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]) def test_foreign_key_as_radio_field(self): # Now specify all the fields as radio_fields. Widgets should now be # RadioSelect, and the choices list should have a first entry of 'None' if # blank=True for the model field. Finally, the widget should have the # 'radiolist' attr, and 'inline' as well if the field is specified HORIZONTAL. class ConcertAdmin(ModelAdmin): radio_fields = { 'main_band': HORIZONTAL, 'opening_band': VERTICAL, 'day': VERTICAL, 'transport': HORIZONTAL, } cma = ConcertAdmin(Concert, self.site) cmafa = cma.get_form(request) self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['main_band'].widget.attrs, {'class': 'radiolist inline'}) self.assertEqual( list(cmafa.base_fields['main_band'].widget.choices), [(self.band.id, 'The Doors')] ) self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs, {'class': 'radiolist'}) self.assertEqual( list(cmafa.base_fields['opening_band'].widget.choices), [('', 'None'), (self.band.id, 'The Doors')] ) self.assertEqual(type(cmafa.base_fields['day'].widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['day'].widget.attrs, {'class': 'radiolist'}) self.assertEqual(list(cmafa.base_fields['day'].widget.choices), [(1, 'Fri'), (2, 'Sat')]) self.assertEqual(type(cmafa.base_fields['transport'].widget), AdminRadioSelect) self.assertEqual(cmafa.base_fields['transport'].widget.attrs, {'class': 'radiolist inline'}) self.assertEqual( list(cmafa.base_fields['transport'].widget.choices), [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')] ) class AdminConcertForm(forms.ModelForm): class Meta: model = Concert exclude = ('transport',) class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['main_band', 'opening_band', 'day']) class AdminConcertForm(forms.ModelForm): extra = forms.CharField() class Meta: model = Concert fields = ['extra', 'transport'] class ConcertAdmin(ModelAdmin): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['extra', 'transport']) class ConcertInline(TabularInline): form = AdminConcertForm model = Concert fk_name = 'main_band' can_delete = True class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), ['extra', 'transport', 'id', 'DELETE', 'main_band'] ) def test_log_actions(self): ma = ModelAdmin(Band, self.site) mock_request = MockRequest() mock_request.user = User.objects.create(username='bill') content_type = get_content_type_for_model(self.band) tests = ( (ma.log_addition, ADDITION, {'added': {}}), (ma.log_change, CHANGE, {'changed': {'fields': ['name', 'bio']}}), (ma.log_deletion, DELETION, str(self.band)), ) for method, flag, message in tests: with self.subTest(name=method.__name__): created = method(mock_request, self.band, message) fetched = LogEntry.objects.filter(action_flag=flag).latest('id') self.assertEqual(created, fetched) self.assertEqual(fetched.action_flag, flag) self.assertEqual(fetched.content_type, content_type) self.assertEqual(fetched.object_id, str(self.band.pk)) self.assertEqual(fetched.user, mock_request.user) if flag == DELETION: self.assertEqual(fetched.change_message, '') self.assertEqual(fetched.object_repr, message) else: self.assertEqual(fetched.change_message, str(message)) self.assertEqual(fetched.object_repr, str(self.band)) def test_get_autocomplete_fields(self): class NameAdmin(ModelAdmin): search_fields = ['name'] class SongAdmin(ModelAdmin): autocomplete_fields = ['featuring'] fields = ['featuring', 'band'] class OtherSongAdmin(SongAdmin): def get_autocomplete_fields(self, request): return ['band'] self.site.register(Band, NameAdmin) try: # Uses autocomplete_fields if not overridden. model_admin = SongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance(form.fields['featuring'].widget.widget, AutocompleteSelectMultiple) # Uses overridden get_autocomplete_fields model_admin = OtherSongAdmin(Song, self.site) form = model_admin.get_form(request)() self.assertIsInstance(form.fields['band'].widget.widget, AutocompleteSelect) finally: self.site.unregister(Band) def test_get_deleted_objects(self): mock_request = MockRequest() mock_request.user = User.objects.create_superuser(username='bob', email='[email protected]', password='test') self.site.register(Band, ModelAdmin) ma = self.site._registry[Band] deletable_objects, model_count, perms_needed, protected = ma.get_deleted_objects([self.band], request) self.assertEqual(deletable_objects, ['Band: The Doors']) self.assertEqual(model_count, {'bands': 1}) self.assertEqual(perms_needed, set()) self.assertEqual(protected, []) def test_get_deleted_objects_with_custom_has_delete_permission(self): """ ModelAdmin.get_deleted_objects() uses ModelAdmin.has_delete_permission() for permissions checking. """ mock_request = MockRequest() mock_request.user = User.objects.create_superuser(username='bob', email='[email protected]', password='test') class TestModelAdmin(ModelAdmin): def has_delete_permission(self, request, obj=None): return False self.site.register(Band, TestModelAdmin) ma = self.site._registry[Band] deletable_objects, model_count, perms_needed, protected = ma.get_deleted_objects([self.band], request) self.assertEqual(deletable_objects, ['Band: The Doors']) self.assertEqual(model_count, {'bands': 1}) self.assertEqual(perms_needed, {'band'}) self.assertEqual(protected, []) class ModelAdminPermissionTests(SimpleTestCase): class MockUser: def has_module_perms(self, app_label): return app_label == 'modeladmin' class MockViewUser(MockUser): def has_perm(self, perm): return perm == 'modeladmin.view_band' class MockAddUser(MockUser): def has_perm(self, perm): return perm == 'modeladmin.add_band' class MockChangeUser(MockUser): def has_perm(self, perm): return perm == 'modeladmin.change_band' class MockDeleteUser(MockUser): def has_perm(self, perm): return perm == 'modeladmin.delete_band' def test_has_view_permission(self): """ has_view_permission() returns True for users who can view objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_view_permission(request), True) request.user = self.MockAddUser() self.assertIs(ma.has_view_permission(request), False) request.user = self.MockChangeUser() self.assertIs(ma.has_view_permission(request), True) request.user = self.MockDeleteUser() self.assertIs(ma.has_view_permission(request), False) def test_has_add_permission(self): """ has_add_permission returns True for users who can add objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertFalse(ma.has_add_permission(request)) request.user = self.MockAddUser() self.assertTrue(ma.has_add_permission(request)) request.user = self.MockChangeUser() self.assertFalse(ma.has_add_permission(request)) request.user = self.MockDeleteUser() self.assertFalse(ma.has_add_permission(request)) def test_inline_has_add_permission_uses_obj(self): class ConcertInline(TabularInline): model = Concert def has_add_permission(self, request, obj): return bool(obj) class BandAdmin(ModelAdmin): inlines = [ConcertInline] ma = BandAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockAddUser() self.assertEqual(ma.get_inline_instances(request), []) band = Band(name='The Doors', bio='', sign_date=date(1965, 1, 1)) inline_instances = ma.get_inline_instances(request, band) self.assertEqual(len(inline_instances), 1) self.assertIsInstance(inline_instances[0], ConcertInline) def test_has_change_permission(self): """ has_change_permission returns True for users who can edit objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_change_permission(request), False) request.user = self.MockAddUser() self.assertFalse(ma.has_change_permission(request)) request.user = self.MockChangeUser() self.assertTrue(ma.has_change_permission(request)) request.user = self.MockDeleteUser() self.assertFalse(ma.has_change_permission(request)) def test_has_delete_permission(self): """ has_delete_permission returns True for users who can delete objects and False for users who can't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_delete_permission(request), False) request.user = self.MockAddUser() self.assertFalse(ma.has_delete_permission(request)) request.user = self.MockChangeUser() self.assertFalse(ma.has_delete_permission(request)) request.user = self.MockDeleteUser() self.assertTrue(ma.has_delete_permission(request)) def test_has_module_permission(self): """ as_module_permission returns True for users who have any permission for the module and False for users who don't. """ ma = ModelAdmin(Band, AdminSite()) request = MockRequest() request.user = self.MockViewUser() self.assertIs(ma.has_module_permission(request), True) request.user = self.MockAddUser() self.assertTrue(ma.has_module_permission(request)) request.user = self.MockChangeUser() self.assertTrue(ma.has_module_permission(request)) request.user = self.MockDeleteUser() self.assertTrue(ma.has_module_permission(request)) original_app_label = ma.opts.app_label ma.opts.app_label = 'anotherapp' try: request.user = self.MockViewUser() self.assertIs(ma.has_module_permission(request), False) request.user = self.MockAddUser() self.assertFalse(ma.has_module_permission(request)) request.user = self.MockChangeUser() self.assertFalse(ma.has_module_permission(request)) request.user = self.MockDeleteUser() self.assertFalse(ma.has_module_permission(request)) finally: ma.opts.app_label = original_app_label
8e60973f18eed3c240acd359a5dcceb57b2e5ac39fb0331adbc2d4a9eb9a7eb1
from django.contrib.auth.models import User from django.db import models class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() sign_date = models.DateField() class Meta: ordering = ('name',) def __str__(self): return self.name class Song(models.Model): name = models.CharField(max_length=100) band = models.ForeignKey(Band, models.CASCADE) featuring = models.ManyToManyField(Band, related_name='featured') def __str__(self): return self.name class Concert(models.Model): main_band = models.ForeignKey(Band, models.CASCADE, related_name='main_concerts') opening_band = models.ForeignKey(Band, models.CASCADE, related_name='opening_concerts', blank=True) day = models.CharField(max_length=3, choices=((1, 'Fri'), (2, 'Sat'))) transport = models.CharField(max_length=100, choices=( (1, 'Plane'), (2, 'Train'), (3, 'Bus') ), blank=True) class ValidationTestModel(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() users = models.ManyToManyField(User) state = models.CharField(max_length=2, choices=(("CO", "Colorado"), ("WA", "Washington"))) is_active = models.BooleanField(default=False) pub_date = models.DateTimeField() band = models.ForeignKey(Band, models.CASCADE) best_friend = models.OneToOneField(User, models.CASCADE, related_name='best_friend') # This field is intentionally 2 characters long (#16080). no = models.IntegerField(verbose_name="Number", blank=True, null=True) def decade_published_in(self): return self.pub_date.strftime('%Y')[:3] + "0's" class ValidationTestInlineModel(models.Model): parent = models.ForeignKey(ValidationTestModel, models.CASCADE)
f08d96f0f6dabb61419fceb2fbe894f73d600aa17f2d9e35a8ae8ef48d375bc1
from django.contrib import admin from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase from .models import Band class AdminActionsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', password='secret', email='[email protected]') content_type = ContentType.objects.get_for_model(Band) Permission.objects.create(name='custom', codename='custom_band', content_type=content_type) for user_type in ('view', 'add', 'change', 'delete', 'custom'): username = '%suser' % user_type user = User.objects.create_user(username=username, password='secret', is_staff=True) permission = Permission.objects.get(codename='%s_band' % user_type, content_type=content_type) user.user_permissions.add(permission) setattr(cls, username, user) def test_get_actions_respects_permissions(self): class MockRequest: pass class BandAdmin(admin.ModelAdmin): actions = ['custom_action'] def custom_action(modeladmin, request, queryset): pass def has_custom_permission(self, request): return request.user.has_perm('%s.custom_band' % self.opts.app_label) ma = BandAdmin(Band, admin.AdminSite()) mock_request = MockRequest() mock_request.GET = {} cases = [ (None, self.viewuser, ['custom_action']), ('view', self.superuser, ['delete_selected', 'custom_action']), ('view', self.viewuser, ['custom_action']), ('add', self.adduser, ['custom_action']), ('change', self.changeuser, ['custom_action']), ('delete', self.deleteuser, ['delete_selected', 'custom_action']), ('custom', self.customuser, ['custom_action']), ] for permission, user, expected in cases: with self.subTest(permission=permission, user=user): if permission is None: if hasattr(BandAdmin.custom_action, 'allowed_permissions'): del BandAdmin.custom_action.allowed_permissions else: BandAdmin.custom_action.allowed_permissions = (permission,) mock_request.user = user actions = ma.get_actions(mock_request) self.assertEqual(list(actions.keys()), expected)
59afd5ad17b1e7bbd6f1762d2bb68d9351126fab2724dec531edac62db5ac694
from django.contrib.admin.options import ModelAdmin, TabularInline from django.utils.deprecation import RemovedInDjango30Warning from .models import Band, Song from .test_checks import CheckTestCase class HasAddPermissionObjTests(CheckTestCase): def test_model_admin_inherited_valid(self): class BandAdmin(ModelAdmin): pass self.assertIsValid(BandAdmin, Band) def test_model_admin_valid(self): class BandAdmin(ModelAdmin): def has_add_permission(self, request): return super().has_add_permission(request) self.assertIsValid(BandAdmin, Band) def test_inline_admin_inherited_valid(self): class SongInlineAdmin(TabularInline): model = Song class BandAdmin(ModelAdmin): inlines = [SongInlineAdmin] self.assertIsValid(BandAdmin, Band) def test_inline_admin_valid(self): class SongInlineAdmin(TabularInline): model = Song def has_add_permission(self, request, obj): return super().has_add_permission(request, obj) class BandAdmin(ModelAdmin): inlines = [SongInlineAdmin] self.assertIsValid(BandAdmin, Band) def test_inline_admin_warning(self): class SongInlineAdmin(TabularInline): model = Song def has_add_permission(self, request): return super().has_add_permission(request) class BandAdmin(ModelAdmin): inlines = [SongInlineAdmin] msg = ( "Update SongInlineAdmin.has_add_permission() to accept a " "positional `obj` argument." ) with self.assertWarnsMessage(RemovedInDjango30Warning, msg): self.assertIsValid(BandAdmin, Band)
7f6fb9ee7ec5ac461340550c4339f21c6b877c275ec6846710c8cb4450575267
from django import forms from django.contrib.admin import BooleanFieldListFilter, SimpleListFilter from django.contrib.admin.options import VERTICAL, ModelAdmin, TabularInline from django.contrib.admin.sites import AdminSite from django.core.checks import Error from django.db.models import F from django.db.models.functions import Upper from django.forms.models import BaseModelFormSet from django.test import SimpleTestCase from .models import ( Band, Song, User, ValidationTestInlineModel, ValidationTestModel, ) class CheckTestCase(SimpleTestCase): def assertIsInvalid(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None, admin_site=None): if admin_site is None: admin_site = AdminSite() invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), [Error(msg, hint=hint, obj=invalid_obj, id=id)]) def assertIsInvalidRegexp(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None): """ Same as assertIsInvalid but treats the given msg as a regexp. """ invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, AdminSite()) errors = admin_obj.check() self.assertEqual(len(errors), 1) error = errors[0] self.assertEqual(error.hint, hint) self.assertEqual(error.obj, invalid_obj) self.assertEqual(error.id, id) self.assertRegex(error.msg, msg) def assertIsValid(self, model_admin, model, admin_site=None): if admin_site is None: admin_site = AdminSite() admin_obj = model_admin(model, admin_site) self.assertEqual(admin_obj.check(), []) class RawIdCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): raw_id_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields' must be a list or tuple.", 'admin.E001' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E002' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'raw_id_fields[0]' must be a foreign key or a " "many-to-many field.", 'admin.E003' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): raw_id_fields = ('users',) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FieldsetsCheckTests(CheckTestCase): def test_valid_case(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', {'fields': ('name',)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_not_iterable(self): class TestModelAdmin(ModelAdmin): fieldsets = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets' must be a list or tuple.", 'admin.E007' ) def test_non_iterable_item(self): class TestModelAdmin(ModelAdmin): fieldsets = ({},) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be a list or tuple.", 'admin.E008' ) def test_item_not_a_pair(self): class TestModelAdmin(ModelAdmin): fieldsets = ((),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0]' must be of length 2.", 'admin.E009' ) def test_second_element_of_item_not_a_dict(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', ()),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must be a dictionary.", 'admin.E010' ) def test_missing_fields_key(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', {}),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fieldsets[0][1]' must contain the key 'fields'.", 'admin.E011' ) class TestModelAdmin(ModelAdmin): fieldsets = (('General', {'fields': ('name',)}),) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_specified_both_fields_and_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = (('General', {'fields': ('name',)}),) fields = ['name'] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "Both 'fieldsets' and 'fields' are specified.", 'admin.E005' ) def test_duplicate_fields(self): class TestModelAdmin(ModelAdmin): fieldsets = [(None, {'fields': ['name', 'name']})] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[0][1]'.", 'admin.E012' ) def test_duplicate_fields_in_fieldsets(self): class TestModelAdmin(ModelAdmin): fieldsets = [ (None, {'fields': ['name']}), (None, {'fields': ['name']}), ] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "There are duplicate field(s) in 'fieldsets[1][1]'.", 'admin.E012' ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (('Band', {'fields': ('name',)}),) self.assertIsValid(BandAdmin, Band) class FieldsCheckTests(CheckTestCase): def test_duplicate_fields_in_fields(self): class TestModelAdmin(ModelAdmin): fields = ['name', 'name'] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' contains duplicate field(s).", 'admin.E006' ) def test_inline(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fields = 10 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' must be a list or tuple.", 'admin.E004', invalid_obj=ValidationTestInline ) class FormCheckTests(CheckTestCase): def test_invalid_type(self): class FakeForm: pass class TestModelAdmin(ModelAdmin): form = FakeForm self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'form' must inherit from 'BaseModelForm'.", 'admin.E016' ) def test_fieldsets_with_custom_form_validation(self): class BandAdmin(ModelAdmin): fieldsets = (('Band', {'fields': ('name',)}),) self.assertIsValid(BandAdmin, Band) def test_valid_case(self): class AdminBandForm(forms.ModelForm): delete = forms.BooleanField() class BandAdmin(ModelAdmin): form = AdminBandForm fieldsets = ( ('Band', { 'fields': ('name', 'bio', 'sign_date', 'delete') }), ) self.assertIsValid(BandAdmin, Band) class FilterVerticalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_vertical = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical' must be a list or tuple.", 'admin.E017' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_vertical = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E019' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_vertical = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_vertical[0]' must be a many-to-many field.", 'admin.E020' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_vertical = ('users',) self.assertIsValid(TestModelAdmin, ValidationTestModel) class FilterHorizontalCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): filter_horizontal = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal' must be a list or tuple.", 'admin.E018' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E019' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'filter_horizontal[0]' must be a many-to-many field.", 'admin.E020' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): filter_horizontal = ('users',) self.assertIsValid(TestModelAdmin, ValidationTestModel) class RadioFieldsCheckTests(CheckTestCase): def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): radio_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' must be a dictionary.", 'admin.E021' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): radio_fields = {'non_existent_field': VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E022' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): radio_fields = {'name': VERTICAL} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields' refers to 'name', which is not an instance " "of ForeignKey, and does not have a 'choices' definition.", 'admin.E023' ) def test_invalid_value(self): class TestModelAdmin(ModelAdmin): radio_fields = {'state': None} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or admin.VERTICAL.", 'admin.E024' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): radio_fields = {'state': VERTICAL} self.assertIsValid(TestModelAdmin, ValidationTestModel) class PrepopulatedFieldsCheckTests(CheckTestCase): def test_not_list_or_tuple(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'slug': 'test'} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, 'The value of \'prepopulated_fields["slug"]\' must be a list ' 'or tuple.', 'admin.E029' ) def test_not_dictionary(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = () self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' must be a dictionary.", 'admin.E026' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'non_existent_field': ('slug',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E027' ) def test_missing_field_again(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'slug': ('non_existent_field',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields[\"slug\"][0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E030' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'users': ('name',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'users', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", 'admin.E028' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'slug': ('name',)} self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_one_to_one_field(self): class TestModelAdmin(ModelAdmin): prepopulated_fields = {'best_friend': ('name',)} self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'prepopulated_fields' refers to 'best_friend', which must not be " "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.", 'admin.E028' ) class ListDisplayTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display' must be a list or tuple.", 'admin.E107' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' refers to 'non_existent_field', " "which is not a callable, an attribute of 'TestModelAdmin', " "or an attribute or method on 'modeladmin.ValidationTestModel'.", 'admin.E108' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): list_display = ('users',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display[0]' must not be a ManyToManyField.", 'admin.E109' ) def test_valid_case(self): def a_callable(obj): pass class TestModelAdmin(ModelAdmin): def a_method(self, obj): pass list_display = ('name', 'decade_published_in', 'a_method', a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListDisplayLinksCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): list_display_links = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", 'admin.E110' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_display_links = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, ( "The value of 'list_display_links[0]' refers to " "'non_existent_field', which is not defined in 'list_display'." ), 'admin.E111' ) def test_missing_in_list_display(self): class TestModelAdmin(ModelAdmin): list_display_links = ('name',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links[0]' refers to 'name', which is not defined in 'list_display'.", 'admin.E111' ) def test_valid_case(self): def a_callable(obj): pass class TestModelAdmin(ModelAdmin): def a_method(self, obj): pass list_display = ('name', 'decade_published_in', 'a_method', a_callable) list_display_links = ('name', 'decade_published_in', 'a_method', a_callable) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_None_is_valid_case(self): class TestModelAdmin(ModelAdmin): list_display_links = None self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_links_check_skipped_if_get_list_display_overridden(self): """ list_display_links check is skipped if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = ['name', 'subtitle'] def get_list_display(self, request): pass self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_list_display_link_checked_for_list_tuple_if_get_list_display_overridden(self): """ list_display_links is checked for list/tuple/None even if get_list_display() is overridden. """ class TestModelAdmin(ModelAdmin): list_display_links = 'non-list/tuple' def get_list_display(self, request): pass self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_display_links' must be a list, a tuple, or None.", 'admin.E110' ) class ListFilterTests(CheckTestCase): def test_list_filter_validation(self): class TestModelAdmin(ModelAdmin): list_filter = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter' must be a list or tuple.", 'admin.E112' ) def test_missing_field(self): class TestModelAdmin(ModelAdmin): list_filter = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' refers to 'non_existent_field', " "which does not refer to a Field.", 'admin.E116' ) def test_not_filter(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (RandomClass,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must inherit from 'ListFilter'.", 'admin.E113' ) def test_not_filter_again(self): class RandomClass: pass class TestModelAdmin(ModelAdmin): list_filter = (('is_active', RandomClass),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", 'admin.E115' ) def test_not_filter_again_again(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return 'awesomeness' def get_choices(self, request): return (('bit', 'A bit awesome'), ('very', 'Very awesome')) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = (('is_active', AwesomeFilter),) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.", 'admin.E115' ) def test_not_associated_with_field_name(self): class TestModelAdmin(ModelAdmin): list_filter = (BooleanFieldListFilter,) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_filter[0]' must not inherit from 'FieldListFilter'.", 'admin.E114' ) def test_valid_case(self): class AwesomeFilter(SimpleListFilter): def get_title(self): return 'awesomeness' def get_choices(self, request): return (('bit', 'A bit awesome'), ('very', 'Very awesome')) def get_queryset(self, cl, qs): return qs class TestModelAdmin(ModelAdmin): list_filter = ('is_active', AwesomeFilter, ('is_active', BooleanFieldListFilter), 'no') self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListPerPageCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_per_page = 'hello' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_per_page' must be an integer.", 'admin.E118' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_per_page = 100 self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListMaxShowAllCheckTests(CheckTestCase): def test_not_integer(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 'hello' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_max_show_all' must be an integer.", 'admin.E119' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_max_show_all = 200 self.assertIsValid(TestModelAdmin, ValidationTestModel) class SearchFieldsCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): search_fields = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'search_fields' must be a list or tuple.", 'admin.E126' ) class DateHierarchyCheckTests(CheckTestCase): def test_missing_field(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'non_existent_field' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' refers to 'non_existent_field', " "which does not refer to a Field.", 'admin.E127' ) def test_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'name' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", 'admin.E128' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'pub_date' self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_valid_case(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'band__sign_date' self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_related_invalid_field_type(self): class TestModelAdmin(ModelAdmin): date_hierarchy = 'band__name' self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'date_hierarchy' must be a DateField or DateTimeField.", 'admin.E128' ) class OrderingCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): ordering = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' must be a list or tuple.", 'admin.E031' ) class TestModelAdmin(ModelAdmin): ordering = ('non_existent_field',) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'non_existent_field', " "which is not an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E033' ) def test_random_marker_not_alone(self): class TestModelAdmin(ModelAdmin): ordering = ('?', 'name') self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering' has the random ordering marker '?', but contains " "other fields as well.", 'admin.E032', hint='Either remove the "?", or remove the other fields.' ) def test_valid_random_marker_case(self): class TestModelAdmin(ModelAdmin): ordering = ('?',) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_complex_case(self): class TestModelAdmin(ModelAdmin): ordering = ('band__name',) self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_valid_case(self): class TestModelAdmin(ModelAdmin): ordering = ('name', 'pk') self.assertIsValid(TestModelAdmin, ValidationTestModel) def test_invalid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (F('nonexistent'), ) self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'ordering[0]' refers to 'nonexistent', which is not " "an attribute of 'modeladmin.ValidationTestModel'.", 'admin.E033' ) def test_valid_expression(self): class TestModelAdmin(ModelAdmin): ordering = (Upper('name'), Upper('band__name').desc()) self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListSelectRelatedCheckTests(CheckTestCase): def test_invalid_type(self): class TestModelAdmin(ModelAdmin): list_select_related = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'list_select_related' must be a boolean, tuple or list.", 'admin.E117' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): list_select_related = False self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveAsCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_as = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_as' must be a boolean.", 'admin.E101' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_as = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class SaveOnTopCheckTests(CheckTestCase): def test_not_boolean(self): class TestModelAdmin(ModelAdmin): save_on_top = 1 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'save_on_top' must be a boolean.", 'admin.E102' ) def test_valid_case(self): class TestModelAdmin(ModelAdmin): save_on_top = True self.assertIsValid(TestModelAdmin, ValidationTestModel) class InlinesCheckTests(CheckTestCase): def test_not_iterable(self): class TestModelAdmin(ModelAdmin): inlines = 10 self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'inlines' must be a list or tuple.", 'admin.E103' ) def test_not_model_admin(self): class ValidationTestInline: pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must inherit from 'InlineModelAdmin'\.", 'admin.E104' ) def test_missing_model_field(self): class ValidationTestInline(TabularInline): pass class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"'.*\.ValidationTestInline' must have a 'model' attribute\.", 'admin.E105' ) def test_invalid_model_type(self): class SomethingBad: pass class ValidationTestInline(TabularInline): model = SomethingBad class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalidRegexp( TestModelAdmin, ValidationTestModel, r"The value of '.*\.ValidationTestInline.model' must be a Model\.", 'admin.E106' ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FkNameCheckTests(CheckTestCase): def test_missing_field(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = 'non_existent_field' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "'modeladmin.ValidationTestInlineModel' has no field named 'non_existent_field'.", 'admin.E202', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel fk_name = 'parent' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class ExtraCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = 'hello' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'extra' must be an integer.", 'admin.E203', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel extra = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MaxNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = 'hello' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'max_num' must be an integer.", 'admin.E204', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel max_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class MinNumCheckTests(CheckTestCase): def test_not_integer(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = 'hello' class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'min_num' must be an integer.", 'admin.E205', invalid_obj=ValidationTestInline ) def test_valid_case(self): class ValidationTestInline(TabularInline): model = ValidationTestInlineModel min_num = 2 class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class FormsetCheckTests(CheckTestCase): def test_invalid_type(self): class FakeFormSet: pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = FakeFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'formset' must inherit from 'BaseModelFormSet'.", 'admin.E206', invalid_obj=ValidationTestInline ) def test_valid_case(self): class RealModelFormSet(BaseModelFormSet): pass class ValidationTestInline(TabularInline): model = ValidationTestInlineModel formset = RealModelFormSet class TestModelAdmin(ModelAdmin): inlines = [ValidationTestInline] self.assertIsValid(TestModelAdmin, ValidationTestModel) class ListDisplayEditableTests(CheckTestCase): def test_list_display_links_is_none(self): """ list_display and list_editable can contain the same values when list_display_links is None """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = list_display list_display_links = None self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_first_item(self): """ The first item in list_display can be the same as the first in list_editable. """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = ['name', 'slug'] list_display_links = ['pub_date'] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_in_list_editable(self): """ The first item in list_display can be in list_editable as long as list_display_links is defined. """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = ['slug', 'name'] list_display_links = ['pub_date'] self.assertIsValid(ProductAdmin, ValidationTestModel) def test_list_display_first_item_same_as_list_editable_no_list_display_links(self): """ The first item in list_display cannot be the same as the first item in list_editable if list_display_links is not defined. """ class ProductAdmin(ModelAdmin): list_display = ['name'] list_editable = ['name'] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[0]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id='admin.E124', ) def test_list_display_first_item_in_list_editable_no_list_display_links(self): """ The first item in list_display cannot be in list_editable if list_display_links isn't defined. """ class ProductAdmin(ModelAdmin): list_display = ['name', 'slug', 'pub_date'] list_editable = ['slug', 'name'] self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'list_editable[1]' refers to the first field " "in 'list_display' ('name'), which cannot be used unless " "'list_display_links' is set.", id='admin.E124', ) def test_both_list_editable_and_list_display_links(self): class ProductAdmin(ModelAdmin): list_editable = ('name',) list_display = ('name',) list_display_links = ('name',) self.assertIsInvalid( ProductAdmin, ValidationTestModel, "The value of 'name' cannot be in both 'list_editable' and " "'list_display_links'.", id='admin.E123', ) class AutocompleteFieldsTests(CheckTestCase): def test_autocomplete_e036(self): class Admin(ModelAdmin): autocomplete_fields = 'name' self.assertIsInvalid( Admin, Band, msg="The value of 'autocomplete_fields' must be a list or tuple.", id='admin.E036', invalid_obj=Admin, ) def test_autocomplete_e037(self): class Admin(ModelAdmin): autocomplete_fields = ('nonexistent',) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' refers to 'nonexistent', " "which is not an attribute of 'modeladmin.ValidationTestModel'." ), id='admin.E037', invalid_obj=Admin, ) def test_autocomplete_e38(self): class Admin(ModelAdmin): autocomplete_fields = ('name',) self.assertIsInvalid( Admin, ValidationTestModel, msg=( "The value of 'autocomplete_fields[0]' must be a foreign " "key or a many-to-many field." ), id='admin.E038', invalid_obj=Admin, ) def test_autocomplete_e039(self): class Admin(ModelAdmin): autocomplete_fields = ('band',) self.assertIsInvalid( Admin, Song, msg=( 'An admin for model "Band" has to be registered ' 'to be referenced by Admin.autocomplete_fields.' ), id='admin.E039', invalid_obj=Admin, ) def test_autocomplete_e040(self): class NoSearchFieldsAdmin(ModelAdmin): pass class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ('featuring',) site = AdminSite() site.register(Band, NoSearchFieldsAdmin) self.assertIsInvalid( AutocompleteAdmin, Song, msg=( 'NoSearchFieldsAdmin must define "search_fields", because ' 'it\'s referenced by AutocompleteAdmin.autocomplete_fields.' ), id='admin.E040', invalid_obj=AutocompleteAdmin, admin_site=site, ) def test_autocomplete_is_valid(self): class SearchFieldsAdmin(ModelAdmin): search_fields = 'name' class AutocompleteAdmin(ModelAdmin): autocomplete_fields = ('featuring',) site = AdminSite() site.register(Band, SearchFieldsAdmin) self.assertIsValid(AutocompleteAdmin, Song, admin_site=site) def test_autocomplete_is_onetoone(self): class UserAdmin(ModelAdmin): search_fields = ('name',) class Admin(ModelAdmin): autocomplete_fields = ('best_friend',) site = AdminSite() site.register(User, UserAdmin) self.assertIsValid(Admin, ValidationTestModel, admin_site=site) class ActionsCheckTests(CheckTestCase): def test_custom_permissions_require_matching_has_method(self): def custom_permission_action(modeladmin, request, queryset): pass custom_permission_action.allowed_permissions = ('custom',) class BandAdmin(ModelAdmin): actions = (custom_permission_action,) self.assertIsInvalid( BandAdmin, Band, 'BandAdmin must define a has_custom_permission() method for the ' 'custom_permission_action action.', id='admin.E129', )
46e28818ab3fc16f560399ff01036b57ac1a20e989a61c15c0d8a9a750f1ba51
""" Tests for django test runner """ 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.test import ( TestCase, TransactionTestCase, skipUnlessDBFeature, testcases, ) from django.test.runner import DiscoverRunner from django.test.testcases import connections_support_transactions from django.test.utils import dependency_ordered from .models import Person 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): pass 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') class CustomTestRunnerOptionsTests(AdminScriptTestCase): def setUp(self): settings = { 'TEST_RUNNER': '\'test_runner.runner.CustomOptionsTestRunner\'', } self.write_settings('settings.py', sdict=settings) def tearDown(self): self.remove_settings('settings.py') 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 Ticket17477RegressionTests(AdminScriptTestCase): def setUp(self): self.write_settings('settings.py') def tearDown(self): self.remove_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 Sqlite3InMemoryTestDbs(TestCase): multi_db = True @unittest.skipUnless(all(db.connections[conn].vendor == 'sqlite' for conn in db.connections), "This is an sqlite-specific issue") def test_transaction_support(self): """Ticket #16329: sqlite3 in-memory test databases""" 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.db.connections', new=tested_connections): with mock.patch('django.test.testcases.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 should be properly initialized for the 'other' DB self.assertTrue(other.features.supports_transactions, msg) # And all the DBs should 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_datebases() 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_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 ) def test_serialized_off(self): tested_connections = db.ConnectionHandler({ 'default': { 'ENGINE': 'django.db.backends.dummy', 'TEST': {'SERIALIZE': False}, }, }) 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=False, keepdb=False ) class AutoIncrementResetTest(TransactionTestCase): """ Here we test creating the same model two times in different test methods, and check that both times they get "1" as their PK value. That is, we test that AutoField values start from 1 for each transactional test case. """ available_apps = ['test_runner'] reset_sequences = True @skipUnlessDBFeature('supports_sequence_reset') def test_autoincrement_reset1(self): p = Person.objects.create(first_name='Jack', last_name='Smith') self.assertEqual(p.pk, 1) @skipUnlessDBFeature('supports_sequence_reset') def test_autoincrement_reset2(self): p = Person.objects.create(first_name='Jack', last_name='Smith') self.assertEqual(p.pk, 1) 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. """ testcases.connections = db.ConnectionHandler({'default': {}}) connection = testcases.connections[db.utils.DEFAULT_DB_ALIAS] self.assertEqual(connection.settings_dict['ENGINE'], 'django.db.backends.dummy') connections_support_transactions()
9174192862967a59bb7da27cbf1c2452de18c5fab994f0296f017e123692450f
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20)
3a23cd3fd5c790b0446a7d11c90e2e17239dfe1dbe30447c8b65993473774cbc
from django.test.runner import DiscoverRunner class CustomOptionsTestRunner(DiscoverRunner): def __init__(self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs): super().__init__(verbosity=verbosity, interactive=interactive, failfast=failfast) self.option_a = option_a self.option_b = option_b self.option_c = option_c @classmethod def add_arguments(cls, parser): parser.add_argument('--option_a', '-a', action='store', dest='option_a', default='1'), parser.add_argument('--option_b', '-b', action='store', dest='option_b', default='2'), parser.add_argument('--option_c', '-c', action='store', dest='option_c', default='3'), def run_tests(self, test_labels, extra_tests=None, **kwargs): print("%s:%s:%s" % (self.option_a, self.option_b, self.option_c))
5e698f1b940e913cef02b0f624a07a49ee6e688d5cd9537188c1637eb9616bd1
import unittest from io import StringIO from django.db import connection from django.test import TestCase from django.test.runner import DiscoverRunner from .models import Person @unittest.skipUnless(connection.vendor == 'sqlite', 'Only run on sqlite so we can check output SQL.') class TestDebugSQL(unittest.TestCase): class PassingTest(TestCase): def runTest(self): Person.objects.filter(first_name='pass').count() class FailingTest(TestCase): def runTest(self): Person.objects.filter(first_name='fail').count() self.fail() class ErrorTest(TestCase): def runTest(self): Person.objects.filter(first_name='error').count() raise Exception class PassingSubTest(TestCase): def runTest(self): with self.subTest(): Person.objects.filter(first_name='subtest-pass').count() class FailingSubTest(TestCase): def runTest(self): with self.subTest(): Person.objects.filter(first_name='subtest-fail').count() self.fail() class ErrorSubTest(TestCase): def runTest(self): with self.subTest(): Person.objects.filter(first_name='subtest-error').count() raise Exception def _test_output(self, verbosity): runner = DiscoverRunner(debug_sql=True, verbosity=0) suite = runner.test_suite() suite.addTest(self.FailingTest()) suite.addTest(self.ErrorTest()) suite.addTest(self.PassingTest()) suite.addTest(self.PassingSubTest()) suite.addTest(self.FailingSubTest()) suite.addTest(self.ErrorSubTest()) old_config = runner.setup_databases() stream = StringIO() resultclass = runner.get_resultclass() runner.test_runner( verbosity=verbosity, stream=stream, resultclass=resultclass, ).run(suite) runner.teardown_databases(old_config) return stream.getvalue() def test_output_normal(self): full_output = self._test_output(1) for output in self.expected_outputs: self.assertIn(output, full_output) for output in self.verbose_expected_outputs: self.assertNotIn(output, full_output) def test_output_verbose(self): full_output = self._test_output(2) for output in self.expected_outputs: self.assertIn(output, full_output) for output in self.verbose_expected_outputs: self.assertIn(output, full_output) expected_outputs = [ ('''SELECT COUNT(*) AS "__count" ''' '''FROM "test_runner_person" WHERE ''' '''"test_runner_person"."first_name" = 'error';'''), ('''SELECT COUNT(*) AS "__count" ''' '''FROM "test_runner_person" WHERE ''' '''"test_runner_person"."first_name" = 'fail';'''), ('''SELECT COUNT(*) AS "__count" ''' '''FROM "test_runner_person" WHERE ''' '''"test_runner_person"."first_name" = 'subtest-error';'''), ('''SELECT COUNT(*) AS "__count" ''' '''FROM "test_runner_person" WHERE ''' '''"test_runner_person"."first_name" = 'subtest-fail';'''), ] verbose_expected_outputs = [ 'runTest (test_runner.test_debug_sql.TestDebugSQL.FailingTest) ... FAIL', 'runTest (test_runner.test_debug_sql.TestDebugSQL.ErrorTest) ... ERROR', 'runTest (test_runner.test_debug_sql.TestDebugSQL.PassingTest) ... ok', # If there are errors/failures in subtests but not in test itself, # the status is not written. That behavior comes from Python. 'runTest (test_runner.test_debug_sql.TestDebugSQL.FailingSubTest) ...', 'runTest (test_runner.test_debug_sql.TestDebugSQL.ErrorSubTest) ...', ('''SELECT COUNT(*) AS "__count" ''' '''FROM "test_runner_person" WHERE ''' '''"test_runner_person"."first_name" = 'pass';'''), ('''SELECT COUNT(*) AS "__count" ''' '''FROM "test_runner_person" WHERE ''' '''"test_runner_person"."first_name" = 'subtest-pass';'''), ]
1275cff1264f729ecda63db2285b6d275515508d5e951cb30aad846fd63b3c24
import os from argparse import ArgumentParser from contextlib import contextmanager from unittest import TestSuite, TextTestRunner, defaultTestLoader from django.test import TestCase from django.test.runner import DiscoverRunner from django.test.utils import captured_stdout @contextmanager def change_cwd(directory): current_dir = os.path.abspath(os.path.dirname(__file__)) new_dir = os.path.join(current_dir, directory) old_cwd = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdir(old_cwd) class DiscoverRunnerTest(TestCase): def test_init_debug_mode(self): runner = DiscoverRunner() self.assertFalse(runner.debug_mode) def test_add_arguments_debug_mode(self): parser = ArgumentParser() DiscoverRunner.add_arguments(parser) ns = parser.parse_args([]) self.assertFalse(ns.debug_mode) ns = parser.parse_args(["--debug-mode"]) self.assertTrue(ns.debug_mode) def test_dotted_test_module(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample'], ).countTestCases() self.assertEqual(count, 4) def test_dotted_test_class_vanilla_unittest(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.TestVanillaUnittest'], ).countTestCases() self.assertEqual(count, 1) def test_dotted_test_class_django_testcase(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.TestDjangoTestCase'], ).countTestCases() self.assertEqual(count, 1) def test_dotted_test_method_django_testcase(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.TestDjangoTestCase.test_sample'], ).countTestCases() self.assertEqual(count, 1) def test_pattern(self): count = DiscoverRunner( pattern="*_tests.py", ).build_suite(['test_runner_apps.sample']).countTestCases() self.assertEqual(count, 1) def test_file_path(self): with change_cwd(".."): count = DiscoverRunner().build_suite( ['test_runner_apps/sample/'], ).countTestCases() self.assertEqual(count, 5) def test_empty_label(self): """ If the test label is empty, discovery should happen on the current working directory. """ with change_cwd("."): suite = DiscoverRunner().build_suite([]) self.assertEqual( suite._tests[0].id().split(".")[0], os.path.basename(os.getcwd()), ) def test_empty_test_case(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.EmptyTestCase'], ).countTestCases() self.assertEqual(count, 0) def test_discovery_on_package(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests'], ).countTestCases() self.assertEqual(count, 1) def test_ignore_adjacent(self): """ When given a dotted path to a module, unittest discovery searches not just the module, but also the directory containing the module. This results in tests from adjacent modules being run when they should not. The discover runner avoids this behavior. """ count = DiscoverRunner().build_suite( ['test_runner_apps.sample.empty'], ).countTestCases() self.assertEqual(count, 0) def test_testcase_ordering(self): with change_cwd(".."): suite = DiscoverRunner().build_suite(['test_runner_apps/sample/']) self.assertEqual( suite._tests[0].__class__.__name__, 'TestDjangoTestCase', msg="TestDjangoTestCase should be the first test case") self.assertEqual( suite._tests[1].__class__.__name__, 'TestZimpleTestCase', msg="TestZimpleTestCase should be the second test case") # All others can follow in unspecified order, including doctests self.assertIn('DocTestCase', [t.__class__.__name__ for t in suite._tests[2:]]) def test_duplicates_ignored(self): """ Tests shouldn't be discovered twice when discovering on overlapping paths. """ base_app = 'forms_tests' sub_app = 'forms_tests.field_tests' with self.modify_settings(INSTALLED_APPS={'append': sub_app}): single = DiscoverRunner().build_suite([base_app]).countTestCases() dups = DiscoverRunner().build_suite([base_app, sub_app]).countTestCases() self.assertEqual(single, dups) def test_reverse(self): """ Reverse should reorder tests while maintaining the grouping specified by ``DiscoverRunner.reorder_by``. """ runner = DiscoverRunner(reverse=True) suite = runner.build_suite( test_labels=('test_runner_apps.sample', 'test_runner_apps.simple')) self.assertIn('test_runner_apps.simple', next(iter(suite)).id(), msg="Test labels should be reversed.") suite = runner.build_suite(test_labels=('test_runner_apps.simple',)) suite = tuple(suite) self.assertIn('DjangoCase', suite[0].id(), msg="Test groups should not be reversed.") self.assertIn('SimpleCase', suite[4].id(), msg="Test groups order should be preserved.") self.assertIn('DjangoCase2', suite[0].id(), msg="Django test cases should be reversed.") self.assertIn('SimpleCase2', suite[4].id(), msg="Simple test cases should be reversed.") self.assertIn('UnittestCase2', suite[8].id(), msg="Unittest test cases should be reversed.") self.assertIn('test_2', suite[0].id(), msg="Methods of Django cases should be reversed.") self.assertIn('test_2', suite[4].id(), msg="Methods of simple cases should be reversed.") self.assertIn('test_2', suite[8].id(), msg="Methods of unittest cases should be reversed.") def test_overridable_get_test_runner_kwargs(self): self.assertIsInstance(DiscoverRunner().get_test_runner_kwargs(), dict) def test_overridable_test_suite(self): self.assertEqual(DiscoverRunner().test_suite, TestSuite) def test_overridable_test_runner(self): self.assertEqual(DiscoverRunner().test_runner, TextTestRunner) def test_overridable_test_loader(self): self.assertEqual(DiscoverRunner().test_loader, defaultTestLoader) def test_tags(self): runner = DiscoverRunner(tags=['core']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 1) runner = DiscoverRunner(tags=['fast']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 2) runner = DiscoverRunner(tags=['slow']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 2) def test_exclude_tags(self): runner = DiscoverRunner(tags=['fast'], exclude_tags=['core']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 1) runner = DiscoverRunner(tags=['fast'], exclude_tags=['slow']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 0) runner = DiscoverRunner(exclude_tags=['slow']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 0) def test_tag_inheritance(self): def count_tests(**kwargs): suite = DiscoverRunner(**kwargs).build_suite(['test_runner_apps.tagged.tests_inheritance']) return suite.countTestCases() self.assertEqual(count_tests(tags=['foo']), 4) self.assertEqual(count_tests(tags=['bar']), 2) self.assertEqual(count_tests(tags=['baz']), 2) self.assertEqual(count_tests(tags=['foo'], exclude_tags=['bar']), 2) self.assertEqual(count_tests(tags=['foo'], exclude_tags=['bar', 'baz']), 1) self.assertEqual(count_tests(exclude_tags=['foo']), 0) def test_included_tags_displayed(self): runner = DiscoverRunner(tags=['foo', 'bar'], verbosity=2) with captured_stdout() as stdout: runner.build_suite(['test_runner_apps.tagged.tests']) self.assertIn('Including test tag(s): bar, foo.\n', stdout.getvalue()) def test_excluded_tags_displayed(self): runner = DiscoverRunner(exclude_tags=['foo', 'bar'], verbosity=3) with captured_stdout() as stdout: runner.build_suite(['test_runner_apps.tagged.tests']) self.assertIn('Excluding test tag(s): bar, foo.\n', stdout.getvalue())
d6051e7229a189fbd9a1ecc11a4bb0cc203ca9d45ee82bd1d20c356fa255ea5b
import unittest from django.test import SimpleTestCase from django.test.runner import RemoteTestResult from django.utils.version import PY37 try: import tblib except ImportError: tblib = None class ExceptionThatFailsUnpickling(Exception): """ After pickling, this class fails unpickling with an error about incorrect arguments passed to __init__(). """ def __init__(self, arg): super().__init__() class ParallelTestRunnerTest(SimpleTestCase): """ End-to-end tests of the parallel test runner. These tests are only meaningful when running tests in parallel using the --parallel option, though it doesn't hurt to run them not in parallel. """ def test_subtest(self): """ Passing subtests work. """ for i in range(2): with self.subTest(index=i): self.assertEqual(i, i) class SampleFailingSubtest(SimpleTestCase): # This method name doesn't begin with "test" to prevent test discovery # from seeing it. def dummy_test(self): """ A dummy test for testing subTest failures. """ for i in range(3): with self.subTest(index=i): self.assertEqual(i, 1) class RemoteTestResultTest(SimpleTestCase): def test_pickle_errors_detection(self): picklable_error = RuntimeError('This is fine') not_unpicklable_error = ExceptionThatFailsUnpickling('arg') result = RemoteTestResult() result._confirm_picklable(picklable_error) msg = '__init__() missing 1 required positional argument' with self.assertRaisesMessage(TypeError, msg): result._confirm_picklable(not_unpicklable_error) @unittest.skipUnless(tblib is not None, 'requires tblib to be installed') def test_add_failing_subtests(self): """ Failing subtests are added correctly using addSubTest(). """ # Manually run a test with failing subtests to prevent the failures # from affecting the actual test run. result = RemoteTestResult() subtest_test = SampleFailingSubtest(methodName='dummy_test') subtest_test.run(result=result) events = result.events self.assertEqual(len(events), 4) event = events[1] self.assertEqual(event[0], 'addSubTest') self.assertEqual(str(event[2]), 'dummy_test (test_runner.test_parallel.SampleFailingSubtest) (index=0)') trailing_comma = '' if PY37 else ',' self.assertEqual(repr(event[3][1]), "AssertionError('0 != 1'%s)" % trailing_comma) event = events[2] self.assertEqual(repr(event[3][1]), "AssertionError('2 != 1'%s)" % trailing_comma)
3499c51692dee813ff1b5a1db989df010166b935bfdf42f3dd8ce38c14191239
from django.db.models import Q from django.test import TestCase from .models import ( Comment, Forum, Item, Post, PropertyValue, SystemDetails, SystemInfo, ) class NullFkTests(TestCase): def test_null_fk(self): d = SystemDetails.objects.create(details='First details') s = SystemInfo.objects.create(system_name='First forum', system_details=d) f = Forum.objects.create(system_info=s, forum_name='First forum') p = Post.objects.create(forum=f, title='First Post') c1 = Comment.objects.create(post=p, comment_text='My first comment') c2 = Comment.objects.create(comment_text='My second comment') # Starting from comment, make sure that a .select_related(...) with a specified # set of fields will properly LEFT JOIN multiple levels of NULLs (and the things # that come after the NULLs, or else data that should exist won't). Regression # test for #7369. c = Comment.objects.select_related().get(id=c1.id) self.assertEqual(c.post, p) self.assertIsNone(Comment.objects.select_related().get(id=c2.id).post) self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info').all(), [ (c1.id, 'My first comment', '<Post: First Post>'), (c2.id, 'My second comment', 'None') ], transform=lambda c: (c.id, c.comment_text, repr(c.post)) ) # Regression test for #7530, #7716. self.assertIsNone(Comment.objects.select_related('post').filter(post__isnull=True)[0].post) self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info__system_details'), [ (c1.id, 'My first comment', '<Post: First Post>'), (c2.id, 'My second comment', 'None') ], transform=lambda c: (c.id, c.comment_text, repr(c.post)) ) def test_combine_isnull(self): item = Item.objects.create(title='Some Item') pv = PropertyValue.objects.create(label='Some Value') item.props.create(key='a', value=pv) item.props.create(key='b') # value=NULL q1 = Q(props__key='a', props__value=pv) q2 = Q(props__key='b', props__value__isnull=True) # Each of these individually should return the item. self.assertEqual(Item.objects.get(q1), item) self.assertEqual(Item.objects.get(q2), item) # Logically, qs1 and qs2, and qs3 and qs4 should be the same. qs1 = Item.objects.filter(q1) & Item.objects.filter(q2) qs2 = Item.objects.filter(q2) & Item.objects.filter(q1) qs3 = Item.objects.filter(q1) | Item.objects.filter(q2) qs4 = Item.objects.filter(q2) | Item.objects.filter(q1) # Regression test for #15823. self.assertEqual(list(qs1), list(qs2)) self.assertEqual(list(qs3), list(qs4))
81f1fbef82ecc8c00f831670fe00a0525bff31325994cd7131512247ad0c6bb9
""" Regression tests for proper working of ForeignKey(null=True). """ from django.db import models class SystemDetails(models.Model): details = models.TextField() class SystemInfo(models.Model): system_details = models.ForeignKey(SystemDetails, models.CASCADE) system_name = models.CharField(max_length=32) class Forum(models.Model): system_info = models.ForeignKey(SystemInfo, models.CASCADE) forum_name = models.CharField(max_length=32) class Post(models.Model): forum = models.ForeignKey(Forum, models.SET_NULL, null=True) title = models.CharField(max_length=32) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, models.SET_NULL, null=True) comment_text = models.CharField(max_length=250) class Meta: ordering = ('comment_text',) def __str__(self): return self.comment_text # Ticket 15823 class Item(models.Model): title = models.CharField(max_length=100) class PropertyValue(models.Model): label = models.CharField(max_length=100) class Property(models.Model): item = models.ForeignKey(Item, models.CASCADE, related_name='props') key = models.CharField(max_length=100) value = models.ForeignKey(PropertyValue, models.SET_NULL, null=True)
a0f71d1af94ead4199f678416acd9dd46c8f47f8159012a72a37f66ed5de0696
from datetime import datetime from decimal import Decimal from django import forms from django.conf import settings from django.contrib.admin import helpers from django.contrib.admin.utils import ( NestedObjects, display_for_field, display_for_value, flatten, flatten_fieldsets, label_for_field, lookup_field, quote, ) from django.db import DEFAULT_DB_ALIAS, models from django.test import SimpleTestCase, TestCase, override_settings from django.utils.formats import localize from django.utils.safestring import mark_safe from .models import ( Article, Car, Count, Event, EventGuide, Location, Site, Vehicle, ) class NestedObjectsTests(TestCase): """ Tests for ``NestedObject`` utility collection. """ def setUp(self): self.n = NestedObjects(using=DEFAULT_DB_ALIAS) self.objs = [Count.objects.create(num=i) for i in range(5)] def _check(self, target): self.assertEqual(self.n.nested(lambda obj: obj.num), target) def _connect(self, i, j): self.objs[i].parent = self.objs[j] self.objs[i].save() def _collect(self, *indices): self.n.collect([self.objs[i] for i in indices]) def test_unrelated_roots(self): self._connect(2, 1) self._collect(0) self._collect(1) self._check([0, 1, [2]]) def test_siblings(self): self._connect(1, 0) self._connect(2, 0) self._collect(0) self._check([0, [1, 2]]) def test_non_added_parent(self): self._connect(0, 1) self._collect(0) self._check([0]) def test_cyclic(self): self._connect(0, 2) self._connect(1, 0) self._connect(2, 1) self._collect(0) self._check([0, [1, [2]]]) def test_queries(self): self._connect(1, 0) self._connect(2, 0) # 1 query to fetch all children of 0 (1 and 2) # 1 query to fetch all children of 1 and 2 (none) # Should not require additional queries to populate the nested graph. self.assertNumQueries(2, self._collect, 0) def test_on_delete_do_nothing(self): """ The nested collector doesn't query for DO_NOTHING objects. """ n = NestedObjects(using=DEFAULT_DB_ALIAS) objs = [Event.objects.create()] EventGuide.objects.create(event=objs[0]) with self.assertNumQueries(2): # One for Location, one for Guest, and no query for EventGuide n.collect(objs) def test_relation_on_abstract(self): """ NestedObjects.collect() doesn't trip (AttributeError) on the special notation for relations on abstract models (related_name that contains %(app_label)s and/or %(class)s) (#21846). """ n = NestedObjects(using=DEFAULT_DB_ALIAS) Car.objects.create() n.collect([Vehicle.objects.first()]) class UtilsTests(SimpleTestCase): empty_value = '-empty-' def test_values_from_lookup_field(self): """ Regression test for #12654: lookup_field """ SITE_NAME = 'example.com' TITLE_TEXT = 'Some title' CREATED_DATE = datetime.min ADMIN_METHOD = 'admin method' SIMPLE_FUNCTION = 'function' INSTANCE_ATTRIBUTE = 'attr' class MockModelAdmin: def get_admin_value(self, obj): return ADMIN_METHOD def simple_function(obj): return SIMPLE_FUNCTION site_obj = Site(domain=SITE_NAME) article = Article( site=site_obj, title=TITLE_TEXT, created=CREATED_DATE, ) article.non_field = INSTANCE_ATTRIBUTE verifications = ( ('site', SITE_NAME), ('created', localize(CREATED_DATE)), ('title', TITLE_TEXT), ('get_admin_value', ADMIN_METHOD), (simple_function, SIMPLE_FUNCTION), ('test_from_model', article.test_from_model()), ('non_field', INSTANCE_ATTRIBUTE) ) mock_admin = MockModelAdmin() for name, value in verifications: field, attr, resolved_value = lookup_field(name, article, mock_admin) if field is not None: resolved_value = display_for_field(resolved_value, field, self.empty_value) self.assertEqual(value, resolved_value) def test_null_display_for_field(self): """ Regression test for #12550: display_for_field should handle None value. """ display_value = display_for_field(None, models.CharField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.CharField( choices=( (None, "test_none"), ) ), self.empty_value) self.assertEqual(display_value, "test_none") display_value = display_for_field(None, models.DateField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.TimeField(), self.empty_value) self.assertEqual(display_value, self.empty_value) # Regression test for #13071: NullBooleanField has special # handling. display_value = display_for_field(None, models.NullBooleanField(), self.empty_value) expected = '<img src="%sadmin/img/icon-unknown.svg" alt="None">' % settings.STATIC_URL self.assertHTMLEqual(display_value, expected) display_value = display_for_field(None, models.BooleanField(null=True), self.empty_value) expected = '<img src="%sadmin/img/icon-unknown.svg" alt="None" />' % settings.STATIC_URL self.assertHTMLEqual(display_value, expected) display_value = display_for_field(None, models.DecimalField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.FloatField(), self.empty_value) self.assertEqual(display_value, self.empty_value) def test_number_formats_display_for_field(self): display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value) self.assertEqual(display_value, '12345.6789') display_value = display_for_field(Decimal('12345.6789'), models.DecimalField(), self.empty_value) self.assertEqual(display_value, '12345.6789') display_value = display_for_field(12345, models.IntegerField(), self.empty_value) self.assertEqual(display_value, '12345') @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_number_formats_with_thousand_separator_display_for_field(self): display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value) self.assertEqual(display_value, '12,345.6789') display_value = display_for_field(Decimal('12345.6789'), models.DecimalField(), self.empty_value) self.assertEqual(display_value, '12,345.6789') display_value = display_for_field(12345, models.IntegerField(), self.empty_value) self.assertEqual(display_value, '12,345') def test_list_display_for_value(self): display_value = display_for_value([1, 2, 3], self.empty_value) self.assertEqual(display_value, '1, 2, 3') display_value = display_for_value([1, 2, 'buckle', 'my', 'shoe'], self.empty_value) self.assertEqual(display_value, '1, 2, buckle, my, shoe') @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_list_display_for_value_boolean(self): self.assertEqual( display_for_value(True, '', boolean=True), '<img src="/static/admin/img/icon-yes.svg" alt="True">' ) self.assertEqual( display_for_value(False, '', boolean=True), '<img src="/static/admin/img/icon-no.svg" alt="False">' ) self.assertEqual(display_for_value(True, ''), 'True') self.assertEqual(display_for_value(False, ''), 'False') def test_label_for_field(self): """ Tests for label_for_field """ self.assertEqual( label_for_field("title", Article), "title" ) self.assertEqual( label_for_field("hist", Article), "History" ) self.assertEqual( label_for_field("hist", Article, return_attr=True), ("History", None) ) self.assertEqual( label_for_field("__str__", Article), "article" ) with self.assertRaisesMessage(AttributeError, "Unable to lookup 'unknown' on Article"): label_for_field("unknown", Article) def test_callable(obj): return "nothing" self.assertEqual( label_for_field(test_callable, Article), "Test callable" ) self.assertEqual( label_for_field(test_callable, Article, return_attr=True), ("Test callable", test_callable) ) self.assertEqual( label_for_field("test_from_model", Article), "Test from model" ) self.assertEqual( label_for_field("test_from_model", Article, return_attr=True), ("Test from model", Article.test_from_model) ) self.assertEqual( label_for_field("test_from_model_with_override", Article), "not What you Expect" ) self.assertEqual( label_for_field(lambda x: "nothing", Article), "--" ) self.assertEqual(label_for_field('site_id', Article), 'Site id') class MockModelAdmin: def test_from_model(self, obj): return "nothing" test_from_model.short_description = "not Really the Model" self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin), "not Really the Model" ) self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin, return_attr=True), ("not Really the Model", MockModelAdmin.test_from_model) ) def test_label_for_property(self): # NOTE: cannot use @property decorator, because of # AttributeError: 'property' object has no attribute 'short_description' class MockModelAdmin: def my_property(self): return "this if from property" my_property.short_description = 'property short description' test_from_property = property(my_property) self.assertEqual( label_for_field("test_from_property", Article, model_admin=MockModelAdmin), 'property short description' ) def test_related_name(self): """ Regression test for #13963 """ self.assertEqual( label_for_field('location', Event, return_attr=True), ('location', None), ) self.assertEqual( label_for_field('event', Location, return_attr=True), ('awesome event', None), ) self.assertEqual( label_for_field('guest', Event, return_attr=True), ('awesome guest', None), ) def test_safestring_in_field_label(self): # safestring should not be escaped class MyForm(forms.Form): text = forms.CharField(label=mark_safe('<i>text</i>')) cb = forms.BooleanField(label=mark_safe('<i>cb</i>')) form = MyForm() self.assertHTMLEqual(helpers.AdminField(form, 'text', is_first=False).label_tag(), '<label for="id_text" class="required inline"><i>text</i>:</label>') self.assertHTMLEqual(helpers.AdminField(form, 'cb', is_first=False).label_tag(), '<label for="id_cb" class="vCheckboxLabel required inline"><i>cb</i></label>') # normal strings needs to be escaped class MyForm(forms.Form): text = forms.CharField(label='&text') cb = forms.BooleanField(label='&cb') form = MyForm() self.assertHTMLEqual(helpers.AdminField(form, 'text', is_first=False).label_tag(), '<label for="id_text" class="required inline">&amp;text:</label>') self.assertHTMLEqual(helpers.AdminField(form, 'cb', is_first=False).label_tag(), '<label for="id_cb" class="vCheckboxLabel required inline">&amp;cb</label>') def test_flatten(self): flat_all = ['url', 'title', 'content', 'sites'] inputs = ( ((), []), (('url', 'title', ('content', 'sites')), flat_all), (('url', 'title', 'content', 'sites'), flat_all), ((('url', 'title'), ('content', 'sites')), flat_all) ) for orig, expected in inputs: self.assertEqual(flatten(orig), expected) def test_flatten_fieldsets(self): """ Regression test for #18051 """ fieldsets = ( (None, { 'fields': ('url', 'title', ('content', 'sites')) }), ) self.assertEqual(flatten_fieldsets(fieldsets), ['url', 'title', 'content', 'sites']) fieldsets = ( (None, { 'fields': ('url', 'title', ['content', 'sites']) }), ) self.assertEqual(flatten_fieldsets(fieldsets), ['url', 'title', 'content', 'sites']) def test_quote(self): self.assertEqual(quote('something\nor\nother'), 'something_0Aor_0Aother')
7a025fe4bbeb3ec75a0f059ab064fd606dc637c6be456003b80e9501554014b9
from django.db import models from django.utils.translation import gettext_lazy as _ class Site(models.Model): domain = models.CharField(max_length=100) def __str__(self): return self.domain class Article(models.Model): """ A simple Article model for testing """ site = models.ForeignKey(Site, models.CASCADE, related_name="admin_articles") title = models.CharField(max_length=100) hist = models.CharField(max_length=100, verbose_name=_("History")) created = models.DateTimeField(null=True) def __str__(self): return self.title def test_from_model(self): return "nothing" def test_from_model_with_override(self): return "nothing" test_from_model_with_override.short_description = "not What you Expect" class ArticleProxy(Article): class Meta: proxy = True class Count(models.Model): num = models.PositiveSmallIntegerField() parent = models.ForeignKey('self', models.CASCADE, null=True) def __str__(self): return str(self.num) class Event(models.Model): date = models.DateTimeField(auto_now_add=True) class Location(models.Model): event = models.OneToOneField(Event, models.CASCADE, verbose_name='awesome event') class Guest(models.Model): event = models.OneToOneField(Event, models.CASCADE) name = models.CharField(max_length=255) class Meta: verbose_name = "awesome guest" class EventGuide(models.Model): event = models.ForeignKey(Event, models.DO_NOTHING) class Vehicle(models.Model): pass class VehicleMixin(Vehicle): vehicle = models.OneToOneField( Vehicle, models.CASCADE, parent_link=True, related_name='vehicle_%(app_label)s_%(class)s', ) class Meta: abstract = True class Car(VehicleMixin): pass
eb82bb9fd654ba3540a8d73d4b3b46f31e943241a649775c5c1e0348d9a532a0
from django.contrib import admin from .models import Article, ArticleProxy, Site class ArticleInline(admin.TabularInline): model = Article fields = ['title'] class SiteAdmin(admin.ModelAdmin): inlines = [ArticleInline] site = admin.AdminSite(name='admin') site.register(Article) site.register(ArticleProxy) site.register(Site, SiteAdmin)
5f45dd424099f2457b504131a0d071e45a0a3f51b8e692a8292db87cc2973ce8
import json from datetime import datetime from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry from django.contrib.admin.utils import quote from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase, override_settings from django.urls import reverse from django.utils import translation from django.utils.html import escape from .models import Article, ArticleProxy, Site @override_settings(ROOT_URLCONF='admin_utils.urls') class LogEntryTests(TestCase): def setUp(self): self.user = User.objects.create_superuser(username='super', password='secret', email='[email protected]') self.site = Site.objects.create(domain='example.org') self.a1 = Article.objects.create( site=self.site, title="Title", created=datetime(2008, 3, 12, 11, 54), ) content_type_pk = ContentType.objects.get_for_model(Article).pk LogEntry.objects.log_action( self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, change_message='Changed something' ) self.client.force_login(self.user) def test_logentry_save(self): """ LogEntry.action_time is a timestamp of the date when the entry was created. It shouldn't be updated on a subsequent save(). """ logentry = LogEntry.objects.get(content_type__model__iexact="article") action_time = logentry.action_time logentry.save() self.assertEqual(logentry.action_time, action_time) def test_logentry_change_message(self): """ LogEntry.change_message is stored as a dumped JSON structure to be able to get the message dynamically translated at display time. """ post_data = { 'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content', 'created_0': '2008-03-12', 'created_1': '11:54', } change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Changed title and hist.') with translation.override('fr'): self.assertEqual(logentry.get_change_message(), 'Modification de title et hist.') add_url = reverse('admin:admin_utils_article_add') post_data['title'] = 'New' response = self.client.post(add_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Added.') with translation.override('fr'): self.assertEqual(logentry.get_change_message(), 'Ajout.') def test_logentry_change_message_not_json(self): """LogEntry.change_message was a string before Django 1.10.""" logentry = LogEntry(change_message='non-JSON string') self.assertEqual(logentry.get_change_message(), logentry.change_message) @override_settings(USE_L10N=True) def test_logentry_change_message_localized_datetime_input(self): """ Localized date/time inputs shouldn't affect changed form data detection. """ post_data = { 'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content', 'created_0': '12/03/2008', 'created_1': '11:54', } with translation.override('fr'): change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Changed title and hist.') def test_logentry_change_message_formsets(self): """ All messages for changed formsets are logged in a change message. """ a2 = Article.objects.create( site=self.site, title="Title second article", created=datetime(2012, 3, 18, 11, 54), ) post_data = { 'domain': 'example.com', # domain changed 'admin_articles-TOTAL_FORMS': '5', 'admin_articles-INITIAL_FORMS': '2', 'admin_articles-MIN_NUM_FORMS': '0', 'admin_articles-MAX_NUM_FORMS': '1000', # Changed title for 1st article 'admin_articles-0-id': str(self.a1.pk), 'admin_articles-0-site': str(self.site.pk), 'admin_articles-0-title': 'Changed Title', # Second article is deleted 'admin_articles-1-id': str(a2.pk), 'admin_articles-1-site': str(self.site.pk), 'admin_articles-1-title': 'Title second article', 'admin_articles-1-DELETE': 'on', # A new article is added 'admin_articles-2-site': str(self.site.pk), 'admin_articles-2-title': 'Added article', } change_url = reverse('admin:admin_utils_site_change', args=[quote(self.site.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_site_changelist')) self.assertQuerysetEqual(Article.objects.filter(pk=a2.pk), []) logentry = LogEntry.objects.filter(content_type__model__iexact='site').latest('action_time') self.assertEqual( json.loads(logentry.change_message), [ {"changed": {"fields": ["domain"]}}, {"added": {"object": "Added article", "name": "article"}}, {"changed": {"fields": ["title"], "object": "Changed Title", "name": "article"}}, {"deleted": {"object": "Title second article", "name": "article"}}, ] ) self.assertEqual( logentry.get_change_message(), 'Changed domain. Added article "Added article". ' 'Changed title for article "Changed Title". Deleted article "Title second article".' ) with translation.override('fr'): self.assertEqual( logentry.get_change_message(), "Modification de domain. Ajout de article « Added article ». " "Modification de title pour l'objet article « Changed Title ». " "Suppression de article « Title second article »." ) def test_logentry_get_edited_object(self): """ LogEntry.get_edited_object() returns the edited object of a LogEntry object. """ logentry = LogEntry.objects.get(content_type__model__iexact="article") edited_obj = logentry.get_edited_object() self.assertEqual(logentry.object_id, str(edited_obj.pk)) def test_logentry_get_admin_url(self): """ LogEntry.get_admin_url returns a URL to edit the entry's object or None for nonexistent (possibly deleted) models. """ logentry = LogEntry.objects.get(content_type__model__iexact='article') expected_url = reverse('admin:admin_utils_article_change', args=(quote(self.a1.pk),)) self.assertEqual(logentry.get_admin_url(), expected_url) self.assertIn('article/%d/change/' % self.a1.pk, logentry.get_admin_url()) logentry.content_type.model = "nonexistent" self.assertIsNone(logentry.get_admin_url()) def test_logentry_unicode(self): log_entry = LogEntry() log_entry.action_flag = ADDITION self.assertTrue(str(log_entry).startswith('Added ')) log_entry.action_flag = CHANGE self.assertTrue(str(log_entry).startswith('Changed ')) log_entry.action_flag = DELETION self.assertTrue(str(log_entry).startswith('Deleted ')) # Make sure custom action_flags works log_entry.action_flag = 4 self.assertEqual(str(log_entry), 'LogEntry Object') def test_logentry_repr(self): logentry = LogEntry.objects.first() self.assertEqual(repr(logentry), str(logentry.action_time)) def test_log_action(self): content_type_pk = ContentType.objects.get_for_model(Article).pk log_entry = LogEntry.objects.log_action( self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, change_message='Changed something else', ) self.assertEqual(log_entry, LogEntry.objects.latest('id')) def test_recentactions_without_content_type(self): """ If a LogEntry is missing content_type it will not display it in span tag under the hyperlink. """ response = self.client.get(reverse('admin:index')) link = reverse('admin:admin_utils_article_change', args=(quote(self.a1.pk),)) should_contain = """<a href="%s">%s</a>""" % (escape(link), escape(repr(self.a1))) self.assertContains(response, should_contain) should_contain = "Article" self.assertContains(response, should_contain) logentry = LogEntry.objects.get(content_type__model__iexact='article') # If the log entry doesn't have a content type it should still be # possible to view the Recent Actions part (#10275). logentry.content_type = None logentry.save() should_contain = should_contain.encode() counted_presence_before = response.content.count(should_contain) response = self.client.get(reverse('admin:index')) counted_presence_after = response.content.count(should_contain) self.assertEqual(counted_presence_before - 1, counted_presence_after) def test_proxy_model_content_type_is_used_for_log_entries(self): """ Log entries for proxy models should have the proxy model's contenttype (#21084). """ proxy_content_type = ContentType.objects.get_for_model(ArticleProxy, for_concrete_model=False) post_data = { 'site': self.site.pk, 'title': "Foo", 'hist': "Bar", 'created_0': '2015-12-25', 'created_1': '00:00', } changelist_url = reverse('admin:admin_utils_articleproxy_changelist') # add proxy_add_url = reverse('admin:admin_utils_articleproxy_add') response = self.client.post(proxy_add_url, post_data) self.assertRedirects(response, changelist_url) proxy_addition_log = LogEntry.objects.latest('id') self.assertEqual(proxy_addition_log.action_flag, ADDITION) self.assertEqual(proxy_addition_log.content_type, proxy_content_type) # change article_id = proxy_addition_log.object_id proxy_change_url = reverse('admin:admin_utils_articleproxy_change', args=(article_id,)) post_data['title'] = 'New' response = self.client.post(proxy_change_url, post_data) self.assertRedirects(response, changelist_url) proxy_change_log = LogEntry.objects.latest('id') self.assertEqual(proxy_change_log.action_flag, CHANGE) self.assertEqual(proxy_change_log.content_type, proxy_content_type) # delete proxy_delete_url = reverse('admin:admin_utils_articleproxy_delete', args=(article_id,)) response = self.client.post(proxy_delete_url, {'post': 'yes'}) self.assertRedirects(response, changelist_url) proxy_delete_log = LogEntry.objects.latest('id') self.assertEqual(proxy_delete_log.action_flag, DELETION) self.assertEqual(proxy_delete_log.content_type, proxy_content_type) def test_action_flag_choices(self): tests = ((1, 'Addition'), (2, 'Change'), (3, 'Deletion')) for action_flag, display_name in tests: with self.subTest(action_flag=action_flag): log = LogEntry(action_flag=action_flag) self.assertEqual(log.get_action_flag_display(), display_name)
b049728e158723aeea68a9e1e91e587886b380c232555d52cb926afd0d612c8b
from django.conf.urls import url from .admin import site urlpatterns = [ url(r'^test_admin/admin/', site.urls), ]
3420fb3ab84e9e0166756e32986df1ec3de29bca8edd94fe6091762630f9292b
from django.db import transaction from django.test import TestCase from .models import Article, InheritedArticleA, InheritedArticleB, Publication class ManyToManyTests(TestCase): def setUp(self): # Create a couple of Publications. self.p1 = Publication.objects.create(title='The Python Journal') self.p2 = Publication.objects.create(title='Science News') self.p3 = Publication.objects.create(title='Science Weekly') self.p4 = Publication.objects.create(title='Highlights for Children') self.a1 = Article.objects.create(headline='Django lets you build Web apps easily') self.a1.publications.add(self.p1) self.a2 = Article.objects.create(headline='NASA uses Python') self.a2.publications.add(self.p1, self.p2, self.p3, self.p4) self.a3 = Article.objects.create(headline='NASA finds intelligent life on Earth') self.a3.publications.add(self.p2) self.a4 = Article.objects.create(headline='Oxygen-free diet works wonders') self.a4.publications.add(self.p2) def test_add(self): # Create an Article. a5 = Article(headline='Django lets you create Web apps easily') # You can't associate it with a Publication until it's been saved. msg = ( '"<Article: Django lets you create Web apps easily>" needs to have ' 'a value for field "id" before this many-to-many relationship can be used.' ) with self.assertRaisesMessage(ValueError, msg): getattr(a5, 'publications') # Save it! a5.save() # Associate the Article with a Publication. a5.publications.add(self.p1) self.assertQuerysetEqual(a5.publications.all(), ['<Publication: The Python Journal>']) # Create another Article, and set it to appear in both Publications. a6 = Article(headline='ESA uses Python') a6.save() a6.publications.add(self.p1, self.p2) a6.publications.add(self.p3) # Adding a second time is OK a6.publications.add(self.p3) self.assertQuerysetEqual( a6.publications.all(), [ '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) # Adding an object of the wrong type raises TypeError with self.assertRaisesMessage(TypeError, "'Publication' instance expected, got <Article"): with transaction.atomic(): a6.publications.add(a5) # Add a Publication directly via publications.add by using keyword arguments. a6.publications.create(title='Highlights for Adults') self.assertQuerysetEqual( a6.publications.all(), [ '<Publication: Highlights for Adults>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) def test_reverse_add(self): # Adding via the 'other' end of an m2m a5 = Article(headline='NASA finds intelligent life on Mars') a5.save() self.p2.article_set.add(a5) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Mars>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(a5.publications.all(), ['<Publication: Science News>']) # Adding via the other end using keywords self.p2.article_set.create(headline='Carbon-free diet works wonders') self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: Carbon-free diet works wonders>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Mars>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) a6 = self.p2.article_set.all()[3] self.assertQuerysetEqual( a6.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) def test_related_sets(self): # Article objects have access to their related Publication objects. self.assertQuerysetEqual(self.a1.publications.all(), ['<Publication: The Python Journal>']) self.assertQuerysetEqual( self.a2.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) # Publication objects have access to their related Article objects. self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( self.p1.article_set.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Publication.objects.get(id=self.p4.id).article_set.all(), ['<Article: NASA uses Python>'] ) def test_selects(self): # We can perform kwarg queries across m2m relationships self.assertQuerysetEqual( Article.objects.filter(publications__id__exact=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__pk=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications=self.p1), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications__title__startswith="Science"), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications__title__startswith="Science").distinct(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) # The count() function respects distinct() as well. self.assertEqual(Article.objects.filter(publications__title__startswith="Science").count(), 4) self.assertEqual(Article.objects.filter(publications__title__startswith="Science").distinct().count(), 3) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1.id, self.p2.id]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1.id, self.p2]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1, self.p2]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) # Excluding a related item works as you would expect, too (although the SQL # involved is a little complex). self.assertQuerysetEqual( Article.objects.exclude(publications=self.p2), ['<Article: Django lets you build Web apps easily>'] ) def test_reverse_selects(self): # Reverse m2m queries are supported (i.e., starting at the table that # doesn't have a ManyToManyField). python_journal = ['<Publication: The Python Journal>'] self.assertQuerysetEqual(Publication.objects.filter(id__exact=self.p1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(pk=self.p1.id), python_journal) self.assertQuerysetEqual( Publication.objects.filter(article__headline__startswith="NASA"), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual(Publication.objects.filter(article__id__exact=self.a1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(article__pk=self.a1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(article=self.a1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(article=self.a1), python_journal) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1.id, self.a2.id]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1.id, self.a2]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1, self.a2]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) def test_delete(self): # If we delete a Publication, its Articles won't be able to access it. self.p1.delete() self.assertQuerysetEqual( Publication.objects.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', ] ) self.assertQuerysetEqual(self.a1.publications.all(), []) # If we delete an Article, its Publications won't be able to access it. self.a2.delete() self.assertQuerysetEqual( Article.objects.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) def test_bulk_delete(self): # Bulk delete some Publications - references to deleted publications should go Publication.objects.filter(title__startswith='Science').delete() self.assertQuerysetEqual( Publication.objects.all(), [ '<Publication: Highlights for Children>', '<Publication: The Python Journal>', ] ) self.assertQuerysetEqual( Article.objects.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( self.a2.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: The Python Journal>', ] ) # Bulk delete some articles - references to deleted objects should go q = Article.objects.filter(headline__startswith='Django') self.assertQuerysetEqual(q, ['<Article: Django lets you build Web apps easily>']) q.delete() # After the delete, the QuerySet cache needs to be cleared, # and the referenced objects should be gone self.assertQuerysetEqual(q, []) self.assertQuerysetEqual(self.p1.article_set.all(), ['<Article: NASA uses Python>']) def test_remove(self): # Removing publication from an article: self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.a4.publications.remove(self.p2) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), []) # And from the other end self.p2.article_set.remove(self.a3) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA uses Python>']) self.assertQuerysetEqual(self.a3.publications.all(), []) def test_set(self): self.p2.article_set.set([self.a4, self.a3]) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id]) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) self.p2.article_set.set([]) self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications.set([]) self.assertQuerysetEqual(self.a4.publications.all(), []) self.p2.article_set.set([self.a4, self.a3], clear=True) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id], clear=True) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) self.p2.article_set.set([], clear=True) self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications.set([], clear=True) self.assertQuerysetEqual(self.a4.publications.all(), []) def test_assign_forward(self): msg = ( "Direct assignment to the reverse side of a many-to-many set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.p2.article_set = [self.a4, self.a3] def test_assign_reverse(self): msg = ( "Direct assignment to the forward side of a many-to-many " "set is prohibited. Use publications.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.a1.publications = [self.p1, self.p2] def test_assign(self): # Relation sets can be assigned using set(). self.p2.article_set.set([self.a4, self.a3]) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id]) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) # An alternate to calling clear() is to set an empty set. self.p2.article_set.set([]) self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications.set([]) self.assertQuerysetEqual(self.a4.publications.all(), []) def test_assign_ids(self): # Relation sets can also be set using primary key values self.p2.article_set.set([self.a4.id, self.a3.id]) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id]) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) def test_forward_assign_with_queryset(self): # Querysets used in m2m assignments are pre-evaluated so their value # isn't affected by the clearing operation in ManyRelatedManager.set() # (#19816). self.a1.publications.set([self.p1, self.p2]) qs = self.a1.publications.filter(title='The Python Journal') self.a1.publications.set(qs) self.assertEqual(1, self.a1.publications.count()) self.assertEqual(1, qs.count()) def test_reverse_assign_with_queryset(self): # Querysets used in M2M assignments are pre-evaluated so their value # isn't affected by the clearing operation in ManyRelatedManager.set() # (#19816). self.p1.article_set.set([self.a1, self.a2]) qs = self.p1.article_set.filter(headline='Django lets you build Web apps easily') self.p1.article_set.set(qs) self.assertEqual(1, self.p1.article_set.count()) self.assertEqual(1, qs.count()) def test_clear(self): # Relation sets can be cleared: self.p2.article_set.clear() self.assertQuerysetEqual(self.p2.article_set.all(), []) self.assertQuerysetEqual(self.a4.publications.all(), []) # And you can clear from the other end self.p2.article_set.add(self.a3, self.a4) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.clear() self.assertQuerysetEqual(self.a4.publications.all(), []) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) def test_clear_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertQuerysetEqual(a4.publications.all(), ['<Publication: Science News>']) a4.publications.clear() self.assertQuerysetEqual(a4.publications.all(), []) def test_remove_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertQuerysetEqual(a4.publications.all(), ['<Publication: Science News>']) a4.publications.remove(self.p2) self.assertQuerysetEqual(a4.publications.all(), []) def test_add_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertEqual(a4.publications.count(), 1) a4.publications.add(self.p1) self.assertEqual(a4.publications.count(), 2) def test_set_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertEqual(a4.publications.count(), 1) a4.publications.set([self.p2, self.p1]) self.assertEqual(a4.publications.count(), 2) a4.publications.set([self.p1]) self.assertEqual(a4.publications.count(), 1) def test_add_then_remove_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertEqual(a4.publications.count(), 1) a4.publications.add(self.p1) self.assertEqual(a4.publications.count(), 2) a4.publications.remove(self.p1) self.assertQuerysetEqual(a4.publications.all(), ['<Publication: Science News>']) def test_inherited_models_selects(self): """ #24156 - Objects from child models where the parent's m2m field uses related_name='+' should be retrieved correctly. """ a = InheritedArticleA.objects.create() b = InheritedArticleB.objects.create() a.publications.add(self.p1, self.p2) self.assertQuerysetEqual( a.publications.all(), [ '<Publication: Science News>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual(b.publications.all(), []) b.publications.add(self.p3) self.assertQuerysetEqual( a.publications.all(), [ '<Publication: Science News>', '<Publication: The Python Journal>', ] ) self.assertQuerysetEqual(b.publications.all(), ['<Publication: Science Weekly>'])
3eaecccd21bf9feb4b3c5ac6dbd540d5ccf6659fb79e312ddaab6827df2dc54c
""" Many-to-many relationships To define a many-to-many relationship, use ``ManyToManyField()``. In this example, an ``Article`` can be published in multiple ``Publication`` objects, and a ``Publication`` has multiple ``Article`` objects. """ from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) def __str__(self): return self.title class Meta: ordering = ('title',) class Tag(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Article(models.Model): headline = models.CharField(max_length=100) # Assign a string as name to make sure the intermediary model is # correctly created. Refs #20207 publications = models.ManyToManyField(Publication, name='publications') tags = models.ManyToManyField(Tag, related_name='tags') def __str__(self): return self.headline class Meta: ordering = ('headline',) # Models to test correct related_name inheritance class AbstractArticle(models.Model): class Meta: abstract = True publications = models.ManyToManyField(Publication, name='publications', related_name='+') class InheritedArticleA(AbstractArticle): pass class InheritedArticleB(AbstractArticle): pass
1cd51ee55be043aa38cafbfd9ecc13f888d84cbe5ac288f82edf0d49d75639d1
from io import BytesIO from django.core.exceptions import RequestDataTooBig, TooManyFieldsSent from django.core.handlers.wsgi import WSGIRequest from django.test import SimpleTestCase from django.test.client import FakePayload TOO_MANY_FIELDS_MSG = 'The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.' TOO_MUCH_DATA_MSG = 'Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.' class DataUploadMaxMemorySizeFormPostTests(SimpleTestCase): def setUp(self): payload = FakePayload('a=1&a=2;a=3\r\n') self.request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) def test_size_exceeded(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=12): with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): self.request._load_post_and_files() def test_size_not_exceeded(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=13): self.request._load_post_and_files() def test_no_limit(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): self.request._load_post_and_files() class DataUploadMaxMemorySizeMultipartPostTests(SimpleTestCase): def setUp(self): payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' '' ])) self.request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) def test_size_exceeded(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=10): with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): self.request._load_post_and_files() def test_size_not_exceeded(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=11): self.request._load_post_and_files() def test_no_limit(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): self.request._load_post_and_files() def test_file_passes(self): payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="file1"; filename="test.file"', '', 'value', '--boundary--' '' ])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=1): request._load_post_and_files() self.assertIn('file1', request.FILES, "Upload file not present") class DataUploadMaxMemorySizeGetTests(SimpleTestCase): def setUp(self): self.request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': BytesIO(b''), 'CONTENT_LENGTH': 3, }) def test_data_upload_max_memory_size_exceeded(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=2): with self.assertRaisesMessage(RequestDataTooBig, TOO_MUCH_DATA_MSG): self.request.body def test_size_not_exceeded(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=3): self.request.body def test_no_limit(self): with self.settings(DATA_UPLOAD_MAX_MEMORY_SIZE=None): self.request.body def test_empty_content_length(self): self.request.environ['CONTENT_LENGTH'] = '' self.request.body class DataUploadMaxNumberOfFieldsGet(SimpleTestCase): def test_get_max_fields_exceeded(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=1): with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG): request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': BytesIO(b''), 'QUERY_STRING': 'a=1&a=2;a=3', }) request.GET['a'] def test_get_max_fields_not_exceeded(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=3): request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': BytesIO(b''), 'QUERY_STRING': 'a=1&a=2;a=3', }) request.GET['a'] class DataUploadMaxNumberOfFieldsMultipartPost(SimpleTestCase): def setUp(self): payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name1"', '', 'value1', '--boundary', 'Content-Disposition: form-data; name="name2"', '', 'value2', '--boundary--' '' ])) self.request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) def test_number_exceeded(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=1): with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG): self.request._load_post_and_files() def test_number_not_exceeded(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=2): self.request._load_post_and_files() def test_no_limit(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=None): self.request._load_post_and_files() class DataUploadMaxNumberOfFieldsFormPost(SimpleTestCase): def setUp(self): payload = FakePayload("\r\n".join(['a=1&a=2;a=3', ''])) self.request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) def test_number_exceeded(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=2): with self.assertRaisesMessage(TooManyFieldsSent, TOO_MANY_FIELDS_MSG): self.request._load_post_and_files() def test_number_not_exceeded(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=3): self.request._load_post_and_files() def test_no_limit(self): with self.settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=None): self.request._load_post_and_files()
2e4b2221423b6628ddfd1602ed4b3e351c20998d8522a52fbd139892deeb3c74
from io import BytesIO from itertools import chain from urllib.parse import urlencode from django.core.exceptions import DisallowedHost from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import HttpRequest, RawPostDataException, UnreadablePostError from django.http.request import split_domain_port from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client import FakePayload class RequestsTests(SimpleTestCase): def test_httprequest(self): request = HttpRequest() self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual(list(request.META), []) # .GET and .POST should be QueryDicts self.assertEqual(request.GET.urlencode(), '') self.assertEqual(request.POST.urlencode(), '') # and FILES should be MultiValueDict self.assertEqual(request.FILES.getlist('foo'), []) self.assertIsNone(request.content_type) self.assertIsNone(request.content_params) def test_httprequest_full_path(self): request = HttpRequest() request.path = '/;some/?awful/=path/foo:bar/' request.path_info = '/prefix' + request.path request.META['QUERY_STRING'] = ';some=query&+query=string' expected = '/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string' self.assertEqual(request.get_full_path(), expected) self.assertEqual(request.get_full_path_info(), '/prefix' + expected) def test_httprequest_full_path_with_query_string_and_fragment(self): request = HttpRequest() request.path = '/foo#bar' request.path_info = '/prefix' + request.path request.META['QUERY_STRING'] = 'baz#quux' self.assertEqual(request.get_full_path(), '/foo%23bar?baz#quux') self.assertEqual(request.get_full_path_info(), '/prefix/foo%23bar?baz#quux') def test_httprequest_repr(self): request = HttpRequest() request.path = '/somepath/' request.method = 'GET' request.GET = {'get-key': 'get-value'} request.POST = {'post-key': 'post-value'} request.COOKIES = {'post-key': 'post-value'} request.META = {'post-key': 'post-value'} self.assertEqual(repr(request), "<HttpRequest: GET '/somepath/'>") def test_httprequest_repr_invalid_method_and_path(self): request = HttpRequest() self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.method = "GET" self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.path = "" self.assertEqual(repr(request), "<HttpRequest>") def test_wsgirequest(self): request = WSGIRequest({ 'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'CONTENT_TYPE': 'text/html; charset=utf8', 'wsgi.input': BytesIO(b''), }) self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual( set(request.META), {'PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'CONTENT_TYPE', 'wsgi.input'} ) self.assertEqual(request.META['PATH_INFO'], 'bogus') self.assertEqual(request.META['REQUEST_METHOD'], 'bogus') self.assertEqual(request.META['SCRIPT_NAME'], '') self.assertEqual(request.content_type, 'text/html') self.assertEqual(request.content_params, {'charset': 'utf8'}) def test_wsgirequest_with_script_name(self): """ The request's path is correctly assembled, regardless of whether or not the SCRIPT_NAME has a trailing slash (#20169). """ # With trailing slash request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/PREFIX/somepath/') # Without trailing slash request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/PREFIX/somepath/') def test_wsgirequest_script_url_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest should take that into account when populating request.path and request.META['SCRIPT_NAME'] (#17133). """ request = WSGIRequest({ 'SCRIPT_URL': '/mst/milestones//accounts/login//help', 'PATH_INFO': '/milestones/accounts/login/help', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/mst/milestones/accounts/login/help') self.assertEqual(request.META['SCRIPT_NAME'], '/mst') def test_wsgirequest_with_force_script_name(self): """ The FORCE_SCRIPT_NAME setting takes precedence over the request's SCRIPT_NAME environment parameter (#20169). """ with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_path_with_force_script_name_trailing_slash(self): """ The request's path is correctly assembled, regardless of whether or not the FORCE_SCRIPT_NAME setting has a trailing slash (#20169). """ # With trailing slash with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') # Without trailing slash with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'): request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_repr(self): request = WSGIRequest({'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(repr(request), "<WSGIRequest: GET '/'>") request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) request.GET = {'get-key': 'get-value'} request.POST = {'post-key': 'post-value'} request.COOKIES = {'post-key': 'post-value'} request.META = {'post-key': 'post-value'} self.assertEqual(repr(request), "<WSGIRequest: GET '/somepath/'>") def test_wsgirequest_path_info(self): def wsgi_str(path_info, encoding='utf-8'): path_info = path_info.encode(encoding) # Actual URL sent by the browser (bytestring) path_info = path_info.decode('iso-8859-1') # Value in the WSGI environ dict (native string) return path_info # Regression for #19468 request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") # The URL may be incorrectly encoded in a non-UTF-8 encoding (#26971) request = WSGIRequest({ 'PATH_INFO': wsgi_str("/café/", encoding='iso-8859-1'), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) # Since it's impossible to decide the (wrong) encoding of the URL, it's # left percent-encoded in the path. self.assertEqual(request.path, "/caf%E9/") def test_limited_stream(self): # Read all of a limited stream stream = LimitedStream(BytesIO(b'test'), 2) self.assertEqual(stream.read(), b'te') # Reading again returns nothing. self.assertEqual(stream.read(), b'') # Read a number of characters greater than the stream has to offer stream = LimitedStream(BytesIO(b'test'), 2) self.assertEqual(stream.read(5), b'te') # Reading again returns nothing. self.assertEqual(stream.readline(5), b'') # Read sequentially from a stream stream = LimitedStream(BytesIO(b'12345678'), 8) self.assertEqual(stream.read(5), b'12345') self.assertEqual(stream.read(5), b'678') # Reading again returns nothing. self.assertEqual(stream.readline(5), b'') # Read lines from a stream stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24) # Read a full line, unconditionally self.assertEqual(stream.readline(), b'1234\n') # Read a number of characters less than a line self.assertEqual(stream.readline(2), b'56') # Read the rest of the partial line self.assertEqual(stream.readline(), b'78\n') # Read a full line, with a character limit greater than the line length self.assertEqual(stream.readline(6), b'abcd\n') # Read the next line, deliberately terminated at the line end self.assertEqual(stream.readline(4), b'efgh') # Read the next line... just the line end self.assertEqual(stream.readline(), b'\n') # Read everything else. self.assertEqual(stream.readline(), b'ijkl') # Regression for #15018 # If a stream contains a newline, but the provided length # is less than the number of provided characters, the newline # doesn't reset the available character count stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9) self.assertEqual(stream.readline(10), b'1234\n') self.assertEqual(stream.readline(3), b'abc') # Now expire the available characters self.assertEqual(stream.readline(3), b'd') # Reading again returns nothing. self.assertEqual(stream.readline(2), b'') # Same test, but with read, not readline. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9) self.assertEqual(stream.read(6), b'1234\na') self.assertEqual(stream.read(2), b'bc') self.assertEqual(stream.read(2), b'd') self.assertEqual(stream.read(2), b'') self.assertEqual(stream.read(), b'') def test_stream(self): payload = FakePayload('name=value') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(request.read(), b'name=value') def test_read_after_value(self): """ Reading from request is allowed after accessing request contents as POST or body. """ payload = FakePayload('name=value') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.body, b'name=value') self.assertEqual(request.read(), b'name=value') def test_value_after_read(self): """ Construction of POST or body is not allowed after reading from request. """ payload = FakePayload('name=value') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(request.read(2), b'na') with self.assertRaises(RawPostDataException): request.body self.assertEqual(request.POST, {}) def test_non_ascii_POST(self): payload = FakePayload(urlencode({'key': 'España'})) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'wsgi.input': payload, }) self.assertEqual(request.POST, {'key': ['España']}) def test_alternate_charset_POST(self): """ Test a POST with non-utf-8 payload encoding. """ payload = FakePayload(urlencode({'key': 'España'.encode('latin-1')})) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=iso-8859-1', 'wsgi.input': payload, }) self.assertEqual(request.POST, {'key': ['España']}) def test_body_after_POST_multipart_form_data(self): """ Reading body after parsing multipart/form-data is not allowed """ # Because multipart is used for large amounts of data i.e. file uploads, # we don't want the data held in memory twice, and we don't want to # silence the error by setting body = '' either. payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(request.POST, {'name': ['value']}) with self.assertRaises(RawPostDataException): request.body def test_body_after_POST_multipart_related(self): """ Reading body after parsing multipart that isn't form-data is allowed """ # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join([ b'--boundary', b'Content-ID: id; name="name"', b'', b'value', b'--boundary--' b'']) payload = FakePayload(payload_data) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/related; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(request.POST, {}) self.assertEqual(request.body, payload_data) def test_POST_multipart_with_content_length_zero(self): """ Multipart POST requests with Content-Length >= 0 are valid and need to be handled. """ # According to: # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13 # Every request.POST with Content-Length >= 0 is a valid request, # this test ensures that we handle Content-Length == 0. payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': 0, 'wsgi.input': payload}) self.assertEqual(request.POST, {}) def test_POST_binary_only(self): payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@' environ = {'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/octet-stream', 'CONTENT_LENGTH': len(payload), 'wsgi.input': BytesIO(payload)} request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) # Same test without specifying content-type environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)}) request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) def test_read_by_lines(self): payload = FakePayload('name=value') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) self.assertEqual(list(request), [b'name=value']) def test_POST_after_body_read(self): """ POST should be populated even if body is read first """ payload = FakePayload('name=value') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) request.body # evaluate self.assertEqual(request.POST, {'name': ['value']}) def test_POST_after_body_read_and_stream_read(self): """ POST should be populated even if body is read first, and then the stream is read second. """ payload = FakePayload('name=value') request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) request.body # evaluate self.assertEqual(request.read(1), b'n') self.assertEqual(request.POST, {'name': ['value']}) def test_POST_after_body_read_and_stream_read_multipart(self): """ POST should be populated even if body is read first, and then the stream is read second. Using multipart/form-data instead of urlencoded. """ payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}) request.body # evaluate # Consume enough data to mess up the parsing: self.assertEqual(request.read(13), b'--boundary\r\nC') self.assertEqual(request.POST, {'name': ['value']}) def test_POST_immutable_for_mutipart(self): """ MultiPartParser.parse() leaves request.POST immutable. """ payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--', ])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertFalse(request.POST._mutable) def test_POST_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the POST, the exception should be identifiable (not a generic IOError). """ class ExplodingBytesIO(BytesIO): def read(self, len=0): raise IOError("kaboom!") payload = b'name=value' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingBytesIO(payload)}) with self.assertRaises(UnreadablePostError): request.body def test_set_encoding_clears_POST(self): payload = FakePayload('name=Hello Günter') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.POST, {'name': ['Hello GĂŒnter']}) def test_set_encoding_clears_GET(self): request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': '', 'QUERY_STRING': 'name=Hello%20G%C3%BCnter', }) self.assertEqual(request.GET, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.GET, {'name': ['Hello G\u0102\u0152nter']}) def test_FILES_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the FILES, the exception should be identifiable (not a generic IOError). """ class ExplodingBytesIO(BytesIO): def read(self, len=0): raise IOError("kaboom!") payload = b'x' request = WSGIRequest({'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=foo_', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingBytesIO(payload)}) with self.assertRaises(UnreadablePostError): request.FILES @override_settings(ALLOWED_HOSTS=['example.com']) def test_get_raw_uri(self): factory = RequestFactory(HTTP_HOST='evil.com') request = factory.get('////absolute-uri') self.assertEqual(request.get_raw_uri(), 'http://evil.com//absolute-uri') request = factory.get('/?foo=bar') self.assertEqual(request.get_raw_uri(), 'http://evil.com/?foo=bar') request = factory.get('/path/with:colons') self.assertEqual(request.get_raw_uri(), 'http://evil.com/path/with:colons') class HostValidationTests(SimpleTestCase): poisoned_hosts = [ '[email protected]', 'example.com:[email protected]', 'example.com:[email protected]:80', 'example.com:80/badpath', 'example.com: recovermypassword.com', ] @override_settings( USE_X_FORWARDED_HOST=False, ALLOWED_HOSTS=[ 'forward.com', 'example.com', 'internal.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com', '.multitenant.com', 'INSENSITIVE.com', '[::ffff:169.254.169.254]', ]) def test_http_get_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_HOST': 'forward.com', 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } # X_FORWARDED_HOST is ignored. self.assertEqual(request.get_host(), 'example.com') # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'example.com') # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'internal.com') # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 8042, } self.assertEqual(request.get_host(), 'internal.com:8042') legit_hosts = [ 'example.com', 'example.com:80', '12.34.56.78', '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', 'xn--4ca9at.com', # Punycode for öäü.com 'anything.multitenant.com', 'multitenant.com', 'insensitive.com', 'example.com.', 'example.com.:80', '[::ffff:169.254.169.254]', ] for host in legit_hosts: request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() # Poisoned host headers are rejected as suspicious for host in chain(self.poisoned_hosts, ['other.com', 'example.com..']): with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=['*']) def test_http_get_host_with_x_forwarded_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_HOST': 'forward.com', 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } # X_FORWARDED_HOST is obeyed. self.assertEqual(request.get_host(), 'forward.com') # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'example.com') # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'internal.com') # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 8042, } self.assertEqual(request.get_host(), 'internal.com:8042') # Poisoned host headers are rejected as suspicious legit_hosts = [ 'example.com', 'example.com:80', '12.34.56.78', '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', 'xn--4ca9at.com', # Punycode for öäü.com ] for host in legit_hosts: request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() for host in self.poisoned_hosts: with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() @override_settings(USE_X_FORWARDED_PORT=False) def test_get_port(self): request = HttpRequest() request.META = { 'SERVER_PORT': '8080', 'HTTP_X_FORWARDED_PORT': '80', } # Shouldn't use the X-Forwarded-Port header self.assertEqual(request.get_port(), '8080') request = HttpRequest() request.META = { 'SERVER_PORT': '8080', } self.assertEqual(request.get_port(), '8080') @override_settings(USE_X_FORWARDED_PORT=True) def test_get_port_with_x_forwarded_port(self): request = HttpRequest() request.META = { 'SERVER_PORT': '8080', 'HTTP_X_FORWARDED_PORT': '80', } # Should use the X-Forwarded-Port header self.assertEqual(request.get_port(), '80') request = HttpRequest() request.META = { 'SERVER_PORT': '8080', } self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ valid_hosts = ['localhost', '127.0.0.1', '[::1]'] for host in valid_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} self.assertEqual(request.get_host(), host) # Other hostnames raise a DisallowedHost. with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = {'HTTP_HOST': 'example.com'} request.get_host() @override_settings(ALLOWED_HOSTS=[]) def test_get_host_suggestion_of_allowed_host(self): """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS.""" msg_invalid_host = "Invalid HTTP_HOST header: %r." msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS." msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035" for host in [ # Valid-looking hosts 'example.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com', # Punycode for öäü.com ]: request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, host)): request.get_host() for domain, port in [ # Valid-looking hosts with a port number ('example.com', 80), ('12.34.56.78', 443), ('[2001:19f0:feee::dead:beef:cafe]', 8080), ]: host = '%s:%s' % (domain, port) request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, domain)): request.get_host() for host in self.poisoned_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host): request.get_host() request = HttpRequest() request.META = {'HTTP_HOST': "invalid_hostname.com"} with self.assertRaisesMessage(DisallowedHost, msg_suggestion2 % "invalid_hostname.com"): request.get_host() def test_split_domain_port_removes_trailing_dot(self): domain, port = split_domain_port('example.com.:8080') self.assertEqual(domain, 'example.com') self.assertEqual(port, '8080') class BuildAbsoluteURITests(SimpleTestCase): factory = RequestFactory() def test_absolute_url(self): request = HttpRequest() url = 'https://www.example.com/asdf' self.assertEqual(request.build_absolute_uri(location=url), url) def test_host_retrieval(self): request = HttpRequest() request.get_host = lambda: 'www.example.com' request.path = '' self.assertEqual( request.build_absolute_uri(location='/path/with:colons'), 'http://www.example.com/path/with:colons' ) def test_request_path_begins_with_two_slashes(self): # //// creates a request with a path beginning with // request = self.factory.get('////absolute-uri') tests = ( # location isn't provided (None, 'http://testserver//absolute-uri'), # An absolute URL ('http://example.com/?foo=bar', 'http://example.com/?foo=bar'), # A schema-relative URL ('//example.com/?foo=bar', 'http://example.com/?foo=bar'), # Relative URLs ('/foo/bar/', 'http://testserver/foo/bar/'), ('/foo/./bar/', 'http://testserver/foo/bar/'), ('/foo/../bar/', 'http://testserver/bar/'), ('///foo/bar/', 'http://testserver/foo/bar/'), ) for location, expected_url in tests: with self.subTest(location=location): self.assertEqual(request.build_absolute_uri(location=location), expected_url)
6a4ee35c2405441325f50c2714bd7b8e965ad3bef1c5adbfcad93c4eb0afd436
import datetime from unittest import mock from django.db.models.sql.compiler import cursor_iter from django.test import TestCase from .models import Article class QuerySetIteratorTests(TestCase): itersize_index_in_mock_args = 3 @classmethod def setUpTestData(cls): Article.objects.create(name='Article 1', created=datetime.datetime.now()) Article.objects.create(name='Article 2', created=datetime.datetime.now()) def test_iterator_invalid_chunk_size(self): for size in (0, -1): with self.subTest(size=size): with self.assertRaisesMessage(ValueError, 'Chunk size must be strictly positive.'): Article.objects.iterator(chunk_size=size) def test_default_iterator_chunk_size(self): qs = Article.objects.iterator() with mock.patch('django.db.models.sql.compiler.cursor_iter', side_effect=cursor_iter) as cursor_iter_mock: next(qs) self.assertEqual(cursor_iter_mock.call_count, 1) mock_args, _mock_kwargs = cursor_iter_mock.call_args self.assertEqual(mock_args[self.itersize_index_in_mock_args], 2000) def test_iterator_chunk_size(self): batch_size = 3 qs = Article.objects.iterator(chunk_size=batch_size) with mock.patch('django.db.models.sql.compiler.cursor_iter', side_effect=cursor_iter) as cursor_iter_mock: next(qs) self.assertEqual(cursor_iter_mock.call_count, 1) mock_args, _mock_kwargs = cursor_iter_mock.call_args self.assertEqual(mock_args[self.itersize_index_in_mock_args], batch_size)
88b01a20cab6e12a091235fa1ceb872d001c6dcbcdd5dfe5347e0d45bc45dde7
from django.db.models import F, Q from django.test import SimpleTestCase class QTests(SimpleTestCase): def test_combine_and_empty(self): q = Q(x=1) self.assertEqual(q & Q(), q) self.assertEqual(Q() & q, q) def test_combine_and_both_empty(self): self.assertEqual(Q() & Q(), Q()) def test_combine_or_empty(self): q = Q(x=1) self.assertEqual(q | Q(), q) self.assertEqual(Q() | q, q) def test_combine_or_both_empty(self): self.assertEqual(Q() | Q(), Q()) def test_combine_not_q_object(self): obj = object() q = Q(x=1) with self.assertRaisesMessage(TypeError, str(obj)): q | obj with self.assertRaisesMessage(TypeError, str(obj)): q & obj def test_deconstruct(self): q = Q(price__gt=F('discounted_price')) path, args, kwargs = q.deconstruct() self.assertEqual(path, 'django.db.models.Q') self.assertEqual(args, ()) self.assertEqual(kwargs, {'price__gt': F('discounted_price')}) def test_deconstruct_negated(self): q = ~Q(price__gt=F('discounted_price')) path, args, kwargs = q.deconstruct() self.assertEqual(args, ()) self.assertEqual(kwargs, { 'price__gt': F('discounted_price'), '_negated': True, }) def test_deconstruct_or(self): q1 = Q(price__gt=F('discounted_price')) q2 = Q(price=F('discounted_price')) q = q1 | q2 path, args, kwargs = q.deconstruct() self.assertEqual(args, ( ('price__gt', F('discounted_price')), ('price', F('discounted_price')), )) self.assertEqual(kwargs, {'_connector': 'OR'}) def test_deconstruct_and(self): q1 = Q(price__gt=F('discounted_price')) q2 = Q(price=F('discounted_price')) q = q1 & q2 path, args, kwargs = q.deconstruct() self.assertEqual(args, ( ('price__gt', F('discounted_price')), ('price', F('discounted_price')), )) self.assertEqual(kwargs, {}) def test_deconstruct_multiple_kwargs(self): q = Q(price__gt=F('discounted_price'), price=F('discounted_price')) path, args, kwargs = q.deconstruct() self.assertEqual(args, ( ('price', F('discounted_price')), ('price__gt', F('discounted_price')), )) self.assertEqual(kwargs, {}) def test_deconstruct_nested(self): q = Q(Q(price__gt=F('discounted_price'))) path, args, kwargs = q.deconstruct() self.assertEqual(args, (Q(price__gt=F('discounted_price')),)) self.assertEqual(kwargs, {}) def test_reconstruct(self): q = Q(price__gt=F('discounted_price')) path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_negated(self): q = ~Q(price__gt=F('discounted_price')) path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_or(self): q1 = Q(price__gt=F('discounted_price')) q2 = Q(price=F('discounted_price')) q = q1 | q2 path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q) def test_reconstruct_and(self): q1 = Q(price__gt=F('discounted_price')) q2 = Q(price=F('discounted_price')) q = q1 & q2 path, args, kwargs = q.deconstruct() self.assertEqual(Q(*args, **kwargs), q)
d4bea741701fa0771a4fc7850378032713532b0903463eb9321c6bbed0cf5290
import datetime import pickle import unittest from collections import OrderedDict from operator import attrgetter from django.core.exceptions import EmptyResultSet, FieldError from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import Count, F, Q from django.db.models.sql.constants import LOUTER from django.db.models.sql.where import NothingNode, WhereNode from django.test import TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import ( FK1, Annotation, Article, Author, BaseA, Book, CategoryItem, CategoryRelationship, Celebrity, Channel, Chapter, Child, ChildObjectA, Classroom, CommonMixedCaseForeignKeys, Company, Cover, CustomPk, CustomPkTag, Detail, DumbCategory, Eaten, Employment, ExtraInfo, Fan, Food, Identifier, Individual, Item, Job, JobResponsibilities, Join, LeafA, LeafB, LoopX, LoopZ, ManagedModel, Member, MixedCaseDbColumnCategoryItem, MixedCaseFieldCategoryItem, ModelA, ModelB, ModelC, ModelD, MyObject, NamedCategory, Node, Note, NullableName, Number, ObjectA, ObjectB, ObjectC, OneToOneCategory, Order, OrderItem, Page, Paragraph, Person, Plaything, PointerA, Program, ProxyCategory, ProxyObjectA, ProxyObjectB, Ranking, Related, RelatedIndividual, RelatedObject, Report, ReportComment, ReservedName, Responsibility, School, SharedConnection, SimpleCategory, SingleObject, SpecialCategory, Staff, StaffUser, Student, Tag, Task, Teacher, Ticket21203Child, Ticket21203Parent, Ticket23605A, Ticket23605B, Ticket23605C, TvChef, Valid, X, ) class Queries1Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) cls.t2 = Tag.objects.create(name='t2', parent=cls.t1, category=generic) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) t4 = Tag.objects.create(name='t4', parent=cls.t3) cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) cls.n1 = Note.objects.create(note='n1', misc='foo', id=1) n2 = Note.objects.create(note='n2', misc='bar', id=2) cls.n3 = Note.objects.create(note='n3', misc='foo', id=3) ann1 = Annotation.objects.create(name='a1', tag=cls.t1) ann1.notes.add(cls.n1) ann2 = Annotation.objects.create(name='a2', tag=t4) ann2.notes.add(n2, cls.n3) # Create these out of order so that sorting by 'id' will be different to sorting # by 'info'. Helps detect some problems later. cls.e2 = ExtraInfo.objects.create(info='e2', note=n2, value=41) e1 = ExtraInfo.objects.create(info='e1', note=cls.n1, value=42) cls.a1 = Author.objects.create(name='a1', num=1001, extra=e1) cls.a2 = Author.objects.create(name='a2', num=2002, extra=e1) a3 = Author.objects.create(name='a3', num=3003, extra=cls.e2) cls.a4 = Author.objects.create(name='a4', num=4004, extra=cls.e2) cls.time1 = datetime.datetime(2007, 12, 19, 22, 25, 0) cls.time2 = datetime.datetime(2007, 12, 19, 21, 0, 0) time3 = datetime.datetime(2007, 12, 20, 22, 25, 0) time4 = datetime.datetime(2007, 12, 20, 21, 0, 0) cls.i1 = Item.objects.create(name='one', created=cls.time1, modified=cls.time1, creator=cls.a1, note=cls.n3) cls.i1.tags.set([cls.t1, cls.t2]) cls.i2 = Item.objects.create(name='two', created=cls.time2, creator=cls.a2, note=n2) cls.i2.tags.set([cls.t1, cls.t3]) cls.i3 = Item.objects.create(name='three', created=time3, creator=cls.a2, note=cls.n3) i4 = Item.objects.create(name='four', created=time4, creator=cls.a4, note=cls.n3) i4.tags.set([t4]) cls.r1 = Report.objects.create(name='r1', creator=cls.a1) Report.objects.create(name='r2', creator=a3) Report.objects.create(name='r3') # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the Meta.ordering # will be rank3, rank2, rank1. cls.rank1 = Ranking.objects.create(rank=2, author=cls.a2) Cover.objects.create(title="first", item=i4) Cover.objects.create(title="second", item=cls.i2) def test_subquery_condition(self): qs1 = Tag.objects.filter(pk__lte=0) qs2 = Tag.objects.filter(parent__in=qs1) qs3 = Tag.objects.filter(parent__in=qs2) self.assertEqual(qs3.query.subq_aliases, {'T', 'U', 'V'}) self.assertIn('v0', str(qs3.query).lower()) qs4 = qs3.filter(parent__in=qs1) self.assertEqual(qs4.query.subq_aliases, {'T', 'U', 'V'}) # It is possible to reuse U for the second subquery, no need to use W. self.assertNotIn('w0', str(qs4.query).lower()) # So, 'U0."id"' is referenced twice. self.assertTrue(str(qs4.query).lower().count('u0'), 2) def test_ticket1050(self): self.assertQuerysetEqual( Item.objects.filter(tags__isnull=True), ['<Item: three>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__id__isnull=True), ['<Item: three>'] ) def test_ticket1801(self): self.assertQuerysetEqual( Author.objects.filter(item=self.i2), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(item=self.i3), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(item=self.i2) & Author.objects.filter(item=self.i3), ['<Author: a2>'] ) def test_ticket2306(self): # Checking that no join types are "left outer" joins. query = Item.objects.filter(tags=self.t2).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).order_by('name'), ['<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(tags=self.t2)), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(creator__name='fred') | Q(tags=self.t2)), ['<Item: one>'] ) # Each filter call is processed "at once" against a single table, so this is # different from the previous example as it tries to find tags that are two # things at once (rather than two tags). self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1) & Q(tags=self.t2)), [] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1), Q(creator__name='fred') | Q(tags=self.t2)), [] ) qs = Author.objects.filter(ranking__rank=2, ranking__id=self.rank1.id) self.assertQuerysetEqual(list(qs), ['<Author: a2>']) self.assertEqual(2, qs.query.count_active_tables(), 2) qs = Author.objects.filter(ranking__rank=2).filter(ranking__id=self.rank1.id) self.assertEqual(qs.query.count_active_tables(), 3) def test_ticket4464(self): self.assertQuerysetEqual( Item.objects.filter(tags=self.t1).filter(tags=self.t2), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name'), ['<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).filter(tags=self.t3), ['<Item: two>'] ) # Make sure .distinct() works with slicing (this was broken in Oracle). self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).order_by('name')[:3], ['<Item: one>', '<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name')[:3], ['<Item: one>', '<Item: two>'] ) def test_tickets_2080_3592(self): self.assertQuerysetEqual( Author.objects.filter(item__name='one') | Author.objects.filter(name='a3'), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(item__name='one') | Q(name='a3')), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(name='a3') | Q(item__name='one')), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(item__name='three') | Q(report__name='r3')), ['<Author: a2>'] ) def test_ticket6074(self): # Merging two empty result sets shouldn't leave a queryset with no constraints # (which would match everything). self.assertQuerysetEqual(Author.objects.filter(Q(id__in=[])), []) self.assertQuerysetEqual( Author.objects.filter(Q(id__in=[]) | Q(id__in=[])), [] ) def test_tickets_1878_2939(self): self.assertEqual(Item.objects.values('creator').distinct().count(), 3) # Create something with a duplicate 'name' so that we can test multi-column # cases (which require some tricky SQL transformations under the covers). xx = Item(name='four', created=self.time1, creator=self.a2, note=self.n1) xx.save() self.assertEqual( Item.objects.exclude(name='two').values('creator', 'name').distinct().count(), 4 ) self.assertEqual( ( Item.objects .exclude(name='two') .extra(select={'foo': '%s'}, select_params=(1,)) .values('creator', 'name', 'foo') .distinct() .count() ), 4 ) self.assertEqual( ( Item.objects .exclude(name='two') .extra(select={'foo': '%s'}, select_params=(1,)) .values('creator', 'name') .distinct() .count() ), 4 ) xx.delete() def test_ticket7323(self): self.assertEqual(Item.objects.values('creator', 'name').count(), 4) def test_ticket2253(self): q1 = Item.objects.order_by('name') q2 = Item.objects.filter(id=self.i1.id) self.assertQuerysetEqual( q1, ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual(q2, ['<Item: one>']) self.assertQuerysetEqual( (q1 | q2).order_by('name'), ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual((q1 & q2).order_by('name'), ['<Item: one>']) q1 = Item.objects.filter(tags=self.t1) q2 = Item.objects.filter(note=self.n3, tags=self.t2) q3 = Item.objects.filter(creator=self.a4) self.assertQuerysetEqual( ((q1 & q2) | q3).order_by('name'), ['<Item: four>', '<Item: one>'] ) def test_order_by_tables(self): q1 = Item.objects.order_by('name') q2 = Item.objects.filter(id=self.i1.id) list(q2) combined_query = (q1 & q2).order_by('name').query self.assertEqual(len([ t for t in combined_query.alias_map if combined_query.alias_refcount[t] ]), 1) def test_order_by_join_unref(self): """ This test is related to the above one, testing that there aren't old JOINs in the query. """ qs = Celebrity.objects.order_by('greatest_fan__fan_of') self.assertIn('OUTER JOIN', str(qs.query)) qs = qs.order_by('id') self.assertNotIn('OUTER JOIN', str(qs.query)) def test_get_clears_ordering(self): """ get() should clear ordering for optimization purposes. """ with CaptureQueriesContext(connection) as captured_queries: Author.objects.order_by('name').get(pk=self.a1.pk) self.assertNotIn('order by', captured_queries[0]['sql'].lower()) def test_tickets_4088_4306(self): self.assertQuerysetEqual( Report.objects.filter(creator=1001), ['<Report: r1>'] ) self.assertQuerysetEqual( Report.objects.filter(creator__num=1001), ['<Report: r1>'] ) self.assertQuerysetEqual(Report.objects.filter(creator__id=1001), []) self.assertQuerysetEqual( Report.objects.filter(creator__id=self.a1.id), ['<Report: r1>'] ) self.assertQuerysetEqual( Report.objects.filter(creator__name='a1'), ['<Report: r1>'] ) def test_ticket4510(self): self.assertQuerysetEqual( Author.objects.filter(report__name='r1'), ['<Author: a1>'] ) def test_ticket7378(self): self.assertQuerysetEqual(self.a1.report_set.all(), ['<Report: r1>']) def test_tickets_5324_6704(self): self.assertQuerysetEqual( Item.objects.filter(tags__name='t4'), ['<Item: four>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4').order_by('name').distinct(), ['<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4').order_by('name').distinct().reverse(), ['<Item: two>', '<Item: three>', '<Item: one>'] ) self.assertQuerysetEqual( Author.objects.exclude(item__name='one').distinct().order_by('name'), ['<Author: a2>', '<Author: a3>', '<Author: a4>'] ) # Excluding across a m2m relation when there is more than one related # object associated was problematic. self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1').order_by('name'), ['<Item: four>', '<Item: three>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1').exclude(tags__name='t4'), ['<Item: three>'] ) # Excluding from a relation that cannot be NULL should not use outer joins. query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) # Similarly, when one of the joins cannot possibly, ever, involve NULL # values (Author -> ExtraInfo, in the following), it should never be # promoted to a left outer join. So the following query should only # involve one "left outer" join (Author -> Item is 0-to-many). qs = Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)) self.assertEqual( len([ x for x in qs.query.alias_map.values() if x.join_type == LOUTER and qs.query.alias_refcount[x.table_alias] ]), 1 ) # The previous changes shouldn't affect nullable foreign key joins. self.assertQuerysetEqual( Tag.objects.filter(parent__isnull=True).order_by('name'), ['<Tag: t1>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent__isnull=True).order_by('name'), ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__name='t1') | Q(parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__isnull=True) | Q(parent__name='t1')).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.filter(~Q(parent__parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) def test_ticket2091(self): t = Tag.objects.get(name='t4') self.assertQuerysetEqual( Item.objects.filter(tags__in=[t]), ['<Item: four>'] ) def test_avoid_infinite_loop_on_too_many_subqueries(self): x = Tag.objects.filter(pk=1) local_recursion_limit = 127 msg = 'Maximum recursion depth exceeded: too many subqueries.' with self.assertRaisesMessage(RuntimeError, msg): for i in range(local_recursion_limit * 2): x = Tag.objects.filter(pk__in=x) def test_reasonable_number_of_subq_aliases(self): x = Tag.objects.filter(pk=1) for _ in range(20): x = Tag.objects.filter(pk__in=x) self.assertEqual( x.query.subq_aliases, { 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', } ) def test_heterogeneous_qs_combination(self): # Combining querysets built on different models should behave in a well-defined # fashion. We raise an error. with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): Author.objects.all() & Tag.objects.all() with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): Author.objects.all() | Tag.objects.all() def test_ticket3141(self): self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4) self.assertEqual( Author.objects.extra(select={'foo': '%s'}, select_params=(1,)).count(), 4 ) def test_ticket2400(self): self.assertQuerysetEqual( Author.objects.filter(item__isnull=True), ['<Author: a3>'] ) self.assertQuerysetEqual( Tag.objects.filter(item__isnull=True), ['<Tag: t5>'] ) def test_ticket2496(self): self.assertQuerysetEqual( Item.objects.extra(tables=['queries_author']).select_related().order_by('name')[:1], ['<Item: four>'] ) def test_error_raised_on_filter_with_dictionary(self): with self.assertRaisesMessage(FieldError, 'Cannot parse keyword query as dict'): Note.objects.filter({'note': 'n1', 'misc': 'foo'}) def test_tickets_2076_7256(self): # Ordering on related tables should be possible, even if the table is # not otherwise involved. self.assertQuerysetEqual( Item.objects.order_by('note__note', 'name'), ['<Item: two>', '<Item: four>', '<Item: one>', '<Item: three>'] ) # Ordering on a related field should use the remote model's default # ordering as a final step. self.assertQuerysetEqual( Author.objects.order_by('extra', '-name'), ['<Author: a2>', '<Author: a1>', '<Author: a4>', '<Author: a3>'] ) # Using remote model default ordering can span multiple models (in this # case, Cover is ordered by Item's default, which uses Note's default). self.assertQuerysetEqual( Cover.objects.all(), ['<Cover: first>', '<Cover: second>'] ) # If the remote model does not have a default ordering, we order by its 'id' # field. self.assertQuerysetEqual( Item.objects.order_by('creator', 'name'), ['<Item: one>', '<Item: three>', '<Item: two>', '<Item: four>'] ) # Ordering by a many-valued attribute (e.g. a many-to-many or reverse # ForeignKey) is legal, but the results might not make sense. That # isn't Django's problem. Garbage in, garbage out. self.assertQuerysetEqual( Item.objects.filter(tags__isnull=False).order_by('tags', 'id'), ['<Item: one>', '<Item: two>', '<Item: one>', '<Item: two>', '<Item: four>'] ) # If we replace the default ordering, Django adjusts the required # tables automatically. Item normally requires a join with Note to do # the default ordering, but that isn't needed here. qs = Item.objects.order_by('name') self.assertQuerysetEqual( qs, ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertEqual(len(qs.query.alias_map), 1) def test_tickets_2874_3002(self): qs = Item.objects.select_related().order_by('note__note', 'name') self.assertQuerysetEqual( qs, ['<Item: two>', '<Item: four>', '<Item: one>', '<Item: three>'] ) # This is also a good select_related() test because there are multiple # Note entries in the SQL. The two Note items should be different. self.assertTrue(repr(qs[0].note), '<Note: n2>') self.assertEqual(repr(qs[0].creator.extra.note), '<Note: n1>') def test_ticket3037(self): self.assertQuerysetEqual( Item.objects.filter(Q(creator__name='a3', name='two') | Q(creator__name='a4', name='four')), ['<Item: four>'] ) def test_tickets_5321_7070(self): # Ordering columns must be included in the output columns. Note that # this means results that might otherwise be distinct are not (if there # are multiple values in the ordering cols), as in this example. This # isn't a bug; it's a warning to be careful with the selection of # ordering columns. self.assertSequenceEqual( Note.objects.values('misc').distinct().order_by('note', '-misc'), [{'misc': 'foo'}, {'misc': 'bar'}, {'misc': 'foo'}] ) def test_ticket4358(self): # If you don't pass any fields to values(), relation fields are # returned as "foo_id" keys, not "foo". For consistency, you should be # able to pass "foo_id" in the fields list and have it work, too. We # actually allow both "foo" and "foo_id". # The *_id version is returned by default. self.assertIn('note_id', ExtraInfo.objects.values()[0]) # You can also pass it in explicitly. self.assertSequenceEqual(ExtraInfo.objects.values('note_id'), [{'note_id': 1}, {'note_id': 2}]) # ...or use the field name. self.assertSequenceEqual(ExtraInfo.objects.values('note'), [{'note': 1}, {'note': 2}]) def test_ticket2902(self): # Parameters can be given to extra_select, *if* you use an OrderedDict. # (First we need to know which order the keys fall in "naturally" on # your system, so we can put things in the wrong way around from # normal. A normal dict would thus fail.) s = [('a', '%s'), ('b', '%s')] params = ['one', 'two'] if list({'a': 1, 'b': 2}) == ['a', 'b']: s.reverse() params.reverse() d = Item.objects.extra(select=OrderedDict(s), select_params=params).values('a', 'b')[0] self.assertEqual(d, {'a': 'one', 'b': 'two'}) # Order by the number of tags attached to an item. qs = ( Item.objects .extra(select={ 'count': 'select count(*) from queries_item_tags where queries_item_tags.item_id = queries_item.id' }) .order_by('-count') ) self.assertEqual([o.count for o in qs], [2, 2, 1, 0]) def test_ticket6154(self): # Multiple filter statements are joined using "AND" all the time. self.assertQuerysetEqual( Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)), ['<Author: a1>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(extra__note=self.n1) | Q(item__note=self.n3)).filter(id=self.a1.id), ['<Author: a1>'] ) def test_ticket6981(self): self.assertQuerysetEqual( Tag.objects.select_related('parent').order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) def test_ticket9926(self): self.assertQuerysetEqual( Tag.objects.select_related("parent", "category").order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.select_related('parent', "parent__category").order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) def test_tickets_6180_6203(self): # Dates with limits and/or counts self.assertEqual(Item.objects.count(), 4) self.assertEqual(Item.objects.datetimes('created', 'month').count(), 1) self.assertEqual(Item.objects.datetimes('created', 'day').count(), 2) self.assertEqual(len(Item.objects.datetimes('created', 'day')), 2) self.assertEqual(Item.objects.datetimes('created', 'day')[0], datetime.datetime(2007, 12, 19, 0, 0)) def test_tickets_7087_12242(self): # Dates with extra select columns self.assertQuerysetEqual( Item.objects.datetimes('created', 'day').extra(select={'a': 1}), ['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)'] ) self.assertQuerysetEqual( Item.objects.extra(select={'a': 1}).datetimes('created', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)'] ) name = "one" self.assertQuerysetEqual( Item.objects.datetimes('created', 'day').extra(where=['name=%s'], params=[name]), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) self.assertQuerysetEqual( Item.objects.extra(where=['name=%s'], params=[name]).datetimes('created', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) def test_ticket7155(self): # Nullable dates self.assertQuerysetEqual( Item.objects.datetimes('modified', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) def test_ticket7098(self): # Make sure semi-deprecated ordering by related models syntax still # works. self.assertSequenceEqual( Item.objects.values('note__note').order_by('queries_note.note', 'id'), [{'note__note': 'n2'}, {'note__note': 'n3'}, {'note__note': 'n3'}, {'note__note': 'n3'}] ) def test_ticket7096(self): # Make sure exclude() with multiple conditions continues to work. self.assertQuerysetEqual( Tag.objects.filter(parent=self.t1, name='t3').order_by('name'), ['<Tag: t3>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent=self.t1, name='t3').order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1', name='one').order_by('name').distinct(), ['<Item: four>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(name__in=['three', 'four']).exclude(tags__name='t1').order_by('name'), ['<Item: four>', '<Item: three>'] ) # More twisted cases, involving nested negations. self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t1', name='one')), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(~Q(tags__name='t1', name='one'), name='two'), ['<Item: two>'] ) self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t1', name='one'), name='two'), ['<Item: four>', '<Item: one>', '<Item: three>'] ) def test_tickets_7204_7506(self): # Make sure querysets with related fields can be pickled. If this # doesn't crash, it's a Good Thing. pickle.dumps(Item.objects.all()) def test_ticket7813(self): # We should also be able to pickle things that use select_related(). # The only tricky thing here is to ensure that we do the related # selections properly after unpickling. qs = Item.objects.select_related() query = qs.query.get_compiler(qs.db).as_sql()[0] query2 = pickle.loads(pickle.dumps(qs.query)) self.assertEqual( query2.get_compiler(qs.db).as_sql()[0], query ) def test_deferred_load_qs_pickling(self): # Check pickling of deferred-loading querysets qs = Item.objects.defer('name', 'creator') q2 = pickle.loads(pickle.dumps(qs)) self.assertEqual(list(qs), list(q2)) q3 = pickle.loads(pickle.dumps(qs, pickle.HIGHEST_PROTOCOL)) self.assertEqual(list(qs), list(q3)) def test_ticket7277(self): self.assertQuerysetEqual( self.n1.annotation_set.filter( Q(tag=self.t5) | Q(tag__children=self.t5) | Q(tag__children__children=self.t5) ), ['<Annotation: a1>'] ) def test_tickets_7448_7707(self): # Complex objects should be converted to strings before being used in # lookups. self.assertQuerysetEqual( Item.objects.filter(created__in=[self.time1, self.time2]), ['<Item: one>', '<Item: two>'] ) def test_ticket7235(self): # An EmptyQuerySet should not raise exceptions if it is filtered. Eaten.objects.create(meal='m') q = Eaten.objects.none() with self.assertNumQueries(0): self.assertQuerysetEqual(q.all(), []) self.assertQuerysetEqual(q.filter(meal='m'), []) self.assertQuerysetEqual(q.exclude(meal='m'), []) self.assertQuerysetEqual(q.complex_filter({'pk': 1}), []) self.assertQuerysetEqual(q.select_related('food'), []) self.assertQuerysetEqual(q.annotate(Count('food')), []) self.assertQuerysetEqual(q.order_by('meal', 'food'), []) self.assertQuerysetEqual(q.distinct(), []) self.assertQuerysetEqual( q.extra(select={'foo': "1"}), [] ) self.assertQuerysetEqual(q.reverse(), []) q.query.low_mark = 1 with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken'): q.extra(select={'foo': "1"}) self.assertQuerysetEqual(q.defer('meal'), []) self.assertQuerysetEqual(q.only('meal'), []) def test_ticket7791(self): # There were "issues" when ordering and distinct-ing on fields related # via ForeignKeys. self.assertEqual( len(Note.objects.order_by('extrainfo__info').distinct()), 3 ) # Pickling of QuerySets using datetimes() should work. qs = Item.objects.datetimes('created', 'month') pickle.loads(pickle.dumps(qs)) def test_ticket9997(self): # If a ValuesList or Values queryset is passed as an inner query, we # make sure it's only requesting a single value and use that as the # thing to select. self.assertQuerysetEqual( Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name')), ['<Tag: t2>', '<Tag: t3>'] ) # Multi-valued values() and values_list() querysets should raise errors. with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id')) with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id')) def test_ticket9985(self): # qs.values_list(...).values(...) combinations should work. self.assertSequenceEqual( Note.objects.values_list("note", flat=True).values("id").order_by("id"), [{'id': 1}, {'id': 2}, {'id': 3}] ) self.assertQuerysetEqual( Annotation.objects.filter(notes__in=Note.objects.filter(note="n1").values_list('note').values('id')), ['<Annotation: a1>'] ) def test_ticket10205(self): # When bailing out early because of an empty "__in" filter, we need # to set things up correctly internally so that subqueries can continue properly. self.assertEqual(Tag.objects.filter(name__in=()).update(name="foo"), 0) def test_ticket10432(self): # Testing an empty "__in" filter with a generator as the value. def f(): return iter([]) n_obj = Note.objects.all()[0] def g(): yield n_obj.pk self.assertQuerysetEqual(Note.objects.filter(pk__in=f()), []) self.assertEqual(list(Note.objects.filter(pk__in=g())), [n_obj]) def test_ticket10742(self): # Queries used in an __in clause don't execute subqueries subq = Author.objects.filter(num__lt=3000) qs = Author.objects.filter(pk__in=subq) self.assertQuerysetEqual(qs, ['<Author: a1>', '<Author: a2>']) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) subq = Author.objects.filter(num__lt=3000) qs = Author.objects.exclude(pk__in=subq) self.assertQuerysetEqual(qs, ['<Author: a3>', '<Author: a4>']) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) subq = Author.objects.filter(num__lt=3000) self.assertQuerysetEqual( Author.objects.filter(Q(pk__in=subq) & Q(name='a1')), ['<Author: a1>'] ) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) def test_ticket7076(self): # Excluding shouldn't eliminate NULL entries. self.assertQuerysetEqual( Item.objects.exclude(modified=self.time1).order_by('name'), ['<Item: four>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent__name=self.t1.name), ['<Tag: t1>', '<Tag: t4>', '<Tag: t5>'] ) def test_ticket7181(self): # Ordering by related tables should accommodate nullable fields (this # test is a little tricky, since NULL ordering is database dependent. # Instead, we just count the number of results). self.assertEqual(len(Tag.objects.order_by('parent__name')), 5) # Empty querysets can be merged with others. self.assertQuerysetEqual( Note.objects.none() | Note.objects.all(), ['<Note: n1>', '<Note: n2>', '<Note: n3>'] ) self.assertQuerysetEqual( Note.objects.all() | Note.objects.none(), ['<Note: n1>', '<Note: n2>', '<Note: n3>'] ) self.assertQuerysetEqual(Note.objects.none() & Note.objects.all(), []) self.assertQuerysetEqual(Note.objects.all() & Note.objects.none(), []) def test_ticket9411(self): # Make sure bump_prefix() (an internal Query method) doesn't (re-)break. It's # sufficient that this query runs without error. qs = Tag.objects.values_list('id', flat=True).order_by('id') qs.query.bump_prefix(qs.query) first = qs[0] self.assertEqual(list(qs), list(range(first, first + 5))) def test_ticket8439(self): # Complex combinations of conjunctions, disjunctions and nullable # relations. self.assertQuerysetEqual( Author.objects.filter(Q(item__note__extrainfo=self.e2) | Q(report=self.r1, name='xyz')), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(report=self.r1, name='xyz') | Q(item__note__extrainfo=self.e2)), ['<Author: a2>'] ) self.assertQuerysetEqual( Annotation.objects.filter(Q(tag__parent=self.t1) | Q(notes__note='n1', name='a1')), ['<Annotation: a1>'] ) xx = ExtraInfo.objects.create(info='xx', note=self.n3) self.assertQuerysetEqual( Note.objects.filter(Q(extrainfo__author=self.a1) | Q(extrainfo=xx)), ['<Note: n1>', '<Note: n3>'] ) q = Note.objects.filter(Q(extrainfo__author=self.a1) | Q(extrainfo=xx)).query self.assertEqual( len([x for x in q.alias_map.values() if x.join_type == LOUTER and q.alias_refcount[x.table_alias]]), 1 ) def test_ticket17429(self): """ Meta.ordering=None works the same as Meta.ordering=[] """ original_ordering = Tag._meta.ordering Tag._meta.ordering = None try: self.assertQuerysetEqual( Tag.objects.all(), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ordered=False ) finally: Tag._meta.ordering = original_ordering def test_exclude(self): self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4'), [repr(i) for i in Item.objects.filter(~Q(tags__name='t4'))]) self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name='t4') | Q(tags__name='t3')), [repr(i) for i in Item.objects.filter(~(Q(tags__name='t4') | Q(tags__name='t3')))]) self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name='t4') | ~Q(tags__name='t3')), [repr(i) for i in Item.objects.filter(~(Q(tags__name='t4') | ~Q(tags__name='t3')))]) def test_nested_exclude(self): self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~~Q(tags__name='t4'))]) def test_double_exclude(self): self.assertQuerysetEqual( Item.objects.filter(Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~~Q(tags__name='t4'))]) self.assertQuerysetEqual( Item.objects.filter(Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~Q(~Q(tags__name='t4')))]) def test_exclude_in(self): self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name__in=['t4', 't3'])), [repr(i) for i in Item.objects.filter(~Q(tags__name__in=['t4', 't3']))]) self.assertQuerysetEqual( Item.objects.filter(Q(tags__name__in=['t4', 't3'])), [repr(i) for i in Item.objects.filter(~~Q(tags__name__in=['t4', 't3']))]) def test_ticket_10790_1(self): # Querying direct fields with isnull should trim the left outer join. # It also should not create INNER JOIN. q = Tag.objects.filter(parent__isnull=True) self.assertQuerysetEqual(q, ['<Tag: t1>']) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.filter(parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__isnull=True) self.assertQuerysetEqual( q, ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__isnull=False) self.assertQuerysetEqual(q, ['<Tag: t1>']) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertNotIn('INNER JOIN', str(q.query)) def test_ticket_10790_2(self): # Querying across several tables should strip only the last outer join, # while preserving the preceding inner joins. q = Tag.objects.filter(parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) # Querying without isnull should not convert anything to left outer join. q = Tag.objects.filter(parent__parent=self.t1) self.assertQuerysetEqual( q, ['<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) def test_ticket_10790_3(self): # Querying via indirect fields should populate the left outer join q = NamedCategory.objects.filter(tag__isnull=True) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) # join to dumbcategory ptr_id self.assertEqual(str(q.query).count('INNER JOIN'), 1) self.assertQuerysetEqual(q, []) # Querying across several tables should strip only the last join, while # preserving the preceding left outer joins. q = NamedCategory.objects.filter(tag__parent__isnull=True) self.assertEqual(str(q.query).count('INNER JOIN'), 1) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertQuerysetEqual(q, ['<NamedCategory: Generic>']) def test_ticket_10790_4(self): # Querying across m2m field should not strip the m2m table from join. q = Author.objects.filter(item__tags__isnull=True) self.assertQuerysetEqual( q, ['<Author: a2>', '<Author: a3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 2) self.assertNotIn('INNER JOIN', str(q.query)) q = Author.objects.filter(item__tags__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3) self.assertNotIn('INNER JOIN', str(q.query)) def test_ticket_10790_5(self): # Querying with isnull=False across m2m field should not create outer joins q = Author.objects.filter(item__tags__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 2) q = Author.objects.filter(item__tags__parent__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 3) q = Author.objects.filter(item__tags__parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 4) def test_ticket_10790_6(self): # Querying with isnull=True across m2m field should not create inner joins # and strip last outer join q = Author.objects.filter(item__tags__parent__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a2>', '<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 4) self.assertEqual(str(q.query).count('INNER JOIN'), 0) q = Author.objects.filter(item__tags__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3) self.assertEqual(str(q.query).count('INNER JOIN'), 0) def test_ticket_10790_7(self): # Reverse querying with isnull should not strip the join q = Author.objects.filter(item__isnull=True) self.assertQuerysetEqual( q, ['<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q.query).count('INNER JOIN'), 0) q = Author.objects.filter(item__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) def test_ticket_10790_8(self): # Querying with combined q-objects should also strip the left outer join q = Tag.objects.filter(Q(parent__isnull=True) | Q(parent=self.t1)) self.assertQuerysetEqual( q, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 0) def test_ticket_10790_combine(self): # Combining queries should not re-populate the left outer join q1 = Tag.objects.filter(parent__isnull=True) q2 = Tag.objects.filter(parent__isnull=False) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q1 & q2 self.assertQuerysetEqual(q3, []) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q2 = Tag.objects.filter(parent=self.t1) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q2 | q1 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q1 = Tag.objects.filter(parent__isnull=True) q2 = Tag.objects.filter(parent__parent__isnull=True) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q2 | q1 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) def test_ticket19672(self): self.assertQuerysetEqual( Report.objects.filter(Q(creator__isnull=False) & ~Q(creator__extra__value=41)), ['<Report: r1>'] ) def test_ticket_20250(self): # A negated Q along with an annotated queryset failed in Django 1.4 qs = Author.objects.annotate(Count('item')) qs = qs.filter(~Q(extra__value=0)) self.assertIn('SELECT', str(qs.query)) self.assertQuerysetEqual( qs, ['<Author: a1>', '<Author: a2>', '<Author: a3>', '<Author: a4>'] ) def test_lookup_constraint_fielderror(self): msg = ( "Cannot resolve keyword 'unknown_field' into field. Choices are: " "annotation, category, category_id, children, id, item, " "managedmodel, name, note, parent, parent_id" ) with self.assertRaisesMessage(FieldError, msg): Tag.objects.filter(unknown_field__name='generic') def test_common_mixed_case_foreign_keys(self): """ Valid query should be generated when fields fetched from joined tables include FKs whose names only differ by case. """ c1 = SimpleCategory.objects.create(name='c1') c2 = SimpleCategory.objects.create(name='c2') c3 = SimpleCategory.objects.create(name='c3') category = CategoryItem.objects.create(category=c1) mixed_case_field_category = MixedCaseFieldCategoryItem.objects.create(CaTeGoRy=c2) mixed_case_db_column_category = MixedCaseDbColumnCategoryItem.objects.create(category=c3) CommonMixedCaseForeignKeys.objects.create( category=category, mixed_case_field_category=mixed_case_field_category, mixed_case_db_column_category=mixed_case_db_column_category, ) qs = CommonMixedCaseForeignKeys.objects.values( 'category', 'mixed_case_field_category', 'mixed_case_db_column_category', 'category__category', 'mixed_case_field_category__CaTeGoRy', 'mixed_case_db_column_category__category', ) self.assertTrue(qs.first()) class Queries2Tests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=4) Number.objects.create(num=8) Number.objects.create(num=12) def test_ticket4289(self): # A slight variation on the restricting the filtering choices by the # lookup constraints. self.assertQuerysetEqual(Number.objects.filter(num__lt=4), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=8, num__lt=12), []) self.assertQuerysetEqual( Number.objects.filter(num__gt=8, num__lt=13), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__lt=4) | Q(num__gt=8, num__lt=12)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=8, num__lt=12) | Q(num__lt=4)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=8) & Q(num__lt=12) | Q(num__lt=4)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=7) & Q(num__lt=12) | Q(num__lt=4)), ['<Number: 8>'] ) def test_ticket12239(self): # Custom lookups are registered to round float values correctly on gte # and lt IntegerField queries. self.assertQuerysetEqual( Number.objects.filter(num__gt=11.9), ['<Number: 12>'] ) self.assertQuerysetEqual(Number.objects.filter(num__gt=12), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=12.0), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=12.1), []) self.assertQuerysetEqual( Number.objects.filter(num__lt=12), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lt=12.0), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lt=12.1), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__gte=11.9), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(num__gte=12), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(num__gte=12.0), ['<Number: 12>'] ) self.assertQuerysetEqual(Number.objects.filter(num__gte=12.1), []) self.assertQuerysetEqual(Number.objects.filter(num__gte=12.9), []) self.assertQuerysetEqual( Number.objects.filter(num__lte=11.9), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.0), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.1), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.9), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) def test_ticket7759(self): # Count should work with a partially read result set. count = Number.objects.count() qs = Number.objects.all() def run(): for obj in qs: return qs.count() == count self.assertTrue(run()) class Queries3Tests(TestCase): def test_ticket7107(self): # This shouldn't create an infinite loop. self.assertQuerysetEqual(Valid.objects.all(), []) def test_ticket8683(self): # An error should be raised when QuerySet.datetimes() is passed the # wrong type of field. with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."): Item.objects.datetimes('name', 'month') def test_ticket22023(self): with self.assertRaisesMessage(TypeError, "Cannot call only() after .values() or .values_list()"): Valid.objects.values().only() with self.assertRaisesMessage(TypeError, "Cannot call defer() after .values() or .values_list()"): Valid.objects.values().defer() class Queries4Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) n1 = Note.objects.create(note='n1', misc='foo') n2 = Note.objects.create(note='n2', misc='bar') e1 = ExtraInfo.objects.create(info='e1', note=n1) e2 = ExtraInfo.objects.create(info='e2', note=n2) cls.a1 = Author.objects.create(name='a1', num=1001, extra=e1) cls.a3 = Author.objects.create(name='a3', num=3003, extra=e2) cls.r1 = Report.objects.create(name='r1', creator=cls.a1) cls.r2 = Report.objects.create(name='r2', creator=cls.a3) cls.r3 = Report.objects.create(name='r3') Item.objects.create(name='i1', created=datetime.datetime.now(), note=n1, creator=cls.a1) Item.objects.create(name='i2', created=datetime.datetime.now(), note=n1, creator=cls.a3) def test_ticket24525(self): tag = Tag.objects.create() anth100 = tag.note_set.create(note='ANTH', misc='100') math101 = tag.note_set.create(note='MATH', misc='101') s1 = tag.annotation_set.create(name='1') s2 = tag.annotation_set.create(name='2') s1.notes.set([math101, anth100]) s2.notes.set([math101]) result = math101.annotation_set.all() & tag.annotation_set.exclude(notes__in=[anth100]) self.assertEqual(list(result), [s2]) def test_ticket11811(self): unsaved_category = NamedCategory(name="Other") msg = 'Unsaved model instance <NamedCategory: Other> cannot be used in an ORM query.' with self.assertRaisesMessage(ValueError, msg): Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category) def test_ticket14876(self): # Note: when combining the query we need to have information available # about the join type of the trimmed "creator__isnull" join. If we # don't have that information, then the join is created as INNER JOIN # and results will be incorrect. q1 = Report.objects.filter(Q(creator__isnull=True) | Q(creator__extra__info='e1')) q2 = Report.objects.filter(Q(creator__isnull=True)) | Report.objects.filter(Q(creator__extra__info='e1')) self.assertQuerysetEqual(q1, ["<Report: r1>", "<Report: r3>"], ordered=False) self.assertEqual(str(q1.query), str(q2.query)) q1 = Report.objects.filter(Q(creator__extra__info='e1') | Q(creator__isnull=True)) q2 = Report.objects.filter(Q(creator__extra__info='e1')) | Report.objects.filter(Q(creator__isnull=True)) self.assertQuerysetEqual(q1, ["<Report: r1>", "<Report: r3>"], ordered=False) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator=self.a1) | Q(creator__report__name='r1')).order_by() q2 = ( Item.objects .filter(Q(creator=self.a1)).order_by() | Item.objects.filter(Q(creator__report__name='r1')) .order_by() ) self.assertQuerysetEqual(q1, ["<Item: i1>"]) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator__report__name='e1') | Q(creator=self.a1)).order_by() q2 = ( Item.objects.filter(Q(creator__report__name='e1')).order_by() | Item.objects.filter(Q(creator=self.a1)).order_by() ) self.assertQuerysetEqual(q1, ["<Item: i1>"]) self.assertEqual(str(q1.query), str(q2.query)) def test_combine_join_reuse(self): # Joins having identical connections are correctly recreated in the # rhs query, in case the query is ORed together (#18748). Report.objects.create(name='r4', creator=self.a1) q1 = Author.objects.filter(report__name='r5') q2 = Author.objects.filter(report__name='r4').filter(report__name='r1') combined = q1 | q2 self.assertEqual(str(combined.query).count('JOIN'), 2) self.assertEqual(len(combined), 1) self.assertEqual(combined[0].name, 'a1') def test_join_reuse_order(self): # Join aliases are reused in order. This shouldn't raise AssertionError # because change_map contains a circular reference (#26522). s1 = School.objects.create() s2 = School.objects.create() s3 = School.objects.create() t1 = Teacher.objects.create() otherteachers = Teacher.objects.exclude(pk=t1.pk).exclude(friends=t1) qs1 = otherteachers.filter(schools=s1).filter(schools=s2) qs2 = otherteachers.filter(schools=s1).filter(schools=s3) self.assertQuerysetEqual(qs1 | qs2, []) def test_ticket7095(self): # Updates that are filtered on the model being updated are somewhat # tricky in MySQL. ManagedModel.objects.create(data='mm1', tag=self.t1, public=True) self.assertEqual(ManagedModel.objects.update(data='mm'), 1) # A values() or values_list() query across joined models must use outer # joins appropriately. # Note: In Oracle, we expect a null CharField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_charfield_repr = '' else: expected_null_charfield_repr = None self.assertSequenceEqual( Report.objects.values_list("creator__extra__info", flat=True).order_by("name"), ['e1', 'e2', expected_null_charfield_repr], ) # Similarly for select_related(), joins beyond an initial nullable join # must use outer joins so that all results are included. self.assertQuerysetEqual( Report.objects.select_related("creator", "creator__extra").order_by("name"), ['<Report: r1>', '<Report: r2>', '<Report: r3>'] ) # When there are multiple paths to a table from another table, we have # to be careful not to accidentally reuse an inappropriate join when # using select_related(). We used to return the parent's Detail record # here by mistake. d1 = Detail.objects.create(data="d1") d2 = Detail.objects.create(data="d2") m1 = Member.objects.create(name="m1", details=d1) m2 = Member.objects.create(name="m2", details=d2) Child.objects.create(person=m2, parent=m1) obj = m1.children.select_related("person__details")[0] self.assertEqual(obj.person.details.data, 'd2') def test_order_by_resetting(self): # Calling order_by() with no parameters removes any existing ordering on the # model. But it should still be possible to add new ordering after that. qs = Author.objects.order_by().order_by('name') self.assertIn('ORDER BY', qs.query.get_compiler(qs.db).as_sql()[0]) def test_order_by_reverse_fk(self): # It is possible to order by reverse of foreign key, although that can lead # to duplicate results. c1 = SimpleCategory.objects.create(name="category1") c2 = SimpleCategory.objects.create(name="category2") CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c1) self.assertSequenceEqual(SimpleCategory.objects.order_by('categoryitem', 'pk'), [c1, c2, c1]) def test_ticket10181(self): # Avoid raising an EmptyResultSet if an inner query is probably # empty (and hence, not executed). self.assertQuerysetEqual( Tag.objects.filter(id__in=Tag.objects.filter(id__in=[])), [] ) def test_ticket15316_filter_false(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) ci3 = CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.filter(category__specialcategory__isnull=False) self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_exclude_false(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=False) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_filter_true(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.filter(category__specialcategory__isnull=True) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_exclude_true(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) ci3 = CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=True) self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_one2one_filter_false(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") CategoryItem.objects.create(category=c) ci2 = CategoryItem.objects.create(category=c0) ci3 = CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=False).order_by('pk') self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_one2one_exclude_false(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=False) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_one2one_filter_true(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=True) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_one2one_exclude_true(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") CategoryItem.objects.create(category=c) ci2 = CategoryItem.objects.create(category=c0) ci3 = CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=True).order_by('pk') self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) class Queries5Tests(TestCase): @classmethod def setUpTestData(cls): # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the # Meta.ordering will be rank3, rank2, rank1. n1 = Note.objects.create(note='n1', misc='foo', id=1) n2 = Note.objects.create(note='n2', misc='bar', id=2) e1 = ExtraInfo.objects.create(info='e1', note=n1) e2 = ExtraInfo.objects.create(info='e2', note=n2) a1 = Author.objects.create(name='a1', num=1001, extra=e1) a2 = Author.objects.create(name='a2', num=2002, extra=e1) a3 = Author.objects.create(name='a3', num=3003, extra=e2) cls.rank1 = Ranking.objects.create(rank=2, author=a2) Ranking.objects.create(rank=1, author=a3) Ranking.objects.create(rank=3, author=a1) def test_ordering(self): # Cross model ordering is possible in Meta, too. self.assertQuerysetEqual( Ranking.objects.all(), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) self.assertQuerysetEqual( Ranking.objects.all().order_by('rank'), ['<Ranking: 1: a3>', '<Ranking: 2: a2>', '<Ranking: 3: a1>'] ) # Ordering of extra() pieces is possible, too and you can mix extra # fields and model fields in the ordering. self.assertQuerysetEqual( Ranking.objects.extra(tables=['django_site'], order_by=['-django_site.id', 'rank']), ['<Ranking: 1: a3>', '<Ranking: 2: a2>', '<Ranking: 3: a1>'] ) sql = 'case when %s > 2 then 1 else 0 end' % connection.ops.quote_name('rank') qs = Ranking.objects.extra(select={'good': sql}) self.assertEqual( [o.good for o in qs.extra(order_by=('-good',))], [True, False, False] ) self.assertQuerysetEqual( qs.extra(order_by=('-good', 'id')), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) # Despite having some extra aliases in the query, we can still omit # them in a values() query. dicts = qs.values('id', 'rank').order_by('id') self.assertEqual( [d['rank'] for d in dicts], [2, 1, 3] ) def test_ticket7256(self): # An empty values() call includes all aliases, including those from an # extra() sql = 'case when %s > 2 then 1 else 0 end' % connection.ops.quote_name('rank') qs = Ranking.objects.extra(select={'good': sql}) dicts = qs.values().order_by('id') for d in dicts: del d['id'] del d['author_id'] self.assertEqual( [sorted(d.items()) for d in dicts], [[('good', 0), ('rank', 2)], [('good', 0), ('rank', 1)], [('good', 1), ('rank', 3)]] ) def test_ticket7045(self): # Extra tables used to crash SQL construction on the second use. qs = Ranking.objects.extra(tables=['django_site']) qs.query.get_compiler(qs.db).as_sql() # test passes if this doesn't raise an exception. qs.query.get_compiler(qs.db).as_sql() def test_ticket9848(self): # Make sure that updates which only filter on sub-tables don't # inadvertently update the wrong records (bug #9848). author_start = Author.objects.get(name='a1') ranking_start = Ranking.objects.get(author__name='a1') # Make sure that the IDs from different tables don't happen to match. self.assertQuerysetEqual( Ranking.objects.filter(author__name='a1'), ['<Ranking: 3: a1>'] ) self.assertEqual( Ranking.objects.filter(author__name='a1').update(rank=4636), 1 ) r = Ranking.objects.get(author__name='a1') self.assertEqual(r.id, ranking_start.id) self.assertEqual(r.author.id, author_start.id) self.assertEqual(r.rank, 4636) r.rank = 3 r.save() self.assertQuerysetEqual( Ranking.objects.all(), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) def test_ticket5261(self): # Test different empty excludes. self.assertQuerysetEqual( Note.objects.exclude(Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.filter(~Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.filter(~Q() | ~Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.exclude(~Q() & ~Q()), ['<Note: n1>', '<Note: n2>'] ) def test_extra_select_literal_percent_s(self): # Allow %%s to escape select clauses self.assertEqual( Note.objects.extra(select={'foo': "'%%s'"})[0].foo, '%s' ) self.assertEqual( Note.objects.extra(select={'foo': "'%%s bar %%s'"})[0].foo, '%s bar %s' ) self.assertEqual( Note.objects.extra(select={'foo': "'bar %%s'"})[0].foo, 'bar %s' ) class SelectRelatedTests(TestCase): def test_tickets_3045_3288(self): # Once upon a time, select_related() with circular relations would loop # infinitely if you forgot to specify "depth". Now we set an arbitrary # default upper bound. self.assertQuerysetEqual(X.objects.all(), []) self.assertQuerysetEqual(X.objects.select_related(), []) class SubclassFKTests(TestCase): def test_ticket7778(self): # Model subclasses could not be deleted if a nullable foreign key # relates to a model that relates back. num_celebs = Celebrity.objects.count() tvc = TvChef.objects.create(name="Huey") self.assertEqual(Celebrity.objects.count(), num_celebs + 1) Fan.objects.create(fan_of=tvc) Fan.objects.create(fan_of=tvc) tvc.delete() # The parent object should have been deleted as well. self.assertEqual(Celebrity.objects.count(), num_celebs) class CustomPkTests(TestCase): def test_ticket7371(self): self.assertQuerysetEqual(Related.objects.order_by('custom'), []) class NullableRelOrderingTests(TestCase): def test_ticket10028(self): # Ordering by model related to nullable relations(!) should use outer # joins, so that all results are included. Plaything.objects.create(name="p1") self.assertQuerysetEqual( Plaything.objects.all(), ['<Plaything: p1>'] ) def test_join_already_in_query(self): # Ordering by model related to nullable relations should not change # the join type of already existing joins. Plaything.objects.create(name="p1") s = SingleObject.objects.create(name='s') r = RelatedObject.objects.create(single=s, f=1) Plaything.objects.create(name="p2", others=r) qs = Plaything.objects.all().filter(others__isnull=False).order_by('pk') self.assertNotIn('JOIN', str(qs.query)) qs = Plaything.objects.all().filter(others__f__isnull=False).order_by('pk') self.assertIn('INNER', str(qs.query)) qs = qs.order_by('others__single__name') # The ordering by others__single__pk will add one new join (to single) # and that join must be LEFT join. The already existing join to related # objects must be kept INNER. So, we have both an INNER and a LEFT join # in the query. self.assertEqual(str(qs.query).count('LEFT'), 1) self.assertEqual(str(qs.query).count('INNER'), 1) self.assertQuerysetEqual( qs, ['<Plaything: p2>'] ) class DisjunctiveFilterTests(TestCase): @classmethod def setUpTestData(cls): cls.n1 = Note.objects.create(note='n1', misc='foo', id=1) ExtraInfo.objects.create(info='e1', note=cls.n1) def test_ticket7872(self): # Another variation on the disjunctive filtering theme. # For the purposes of this regression test, it's important that there is no # Join object related to the LeafA we create. LeafA.objects.create(data='first') self.assertQuerysetEqual(LeafA.objects.all(), ['<LeafA: first>']) self.assertQuerysetEqual( LeafA.objects.filter(Q(data='first') | Q(join__b__data='second')), ['<LeafA: first>'] ) def test_ticket8283(self): # Checking that applying filters after a disjunction works correctly. self.assertQuerysetEqual( (ExtraInfo.objects.filter(note=self.n1) | ExtraInfo.objects.filter(info='e2')).filter(note=self.n1), ['<ExtraInfo: e1>'] ) self.assertQuerysetEqual( (ExtraInfo.objects.filter(info='e2') | ExtraInfo.objects.filter(note=self.n1)).filter(note=self.n1), ['<ExtraInfo: e1>'] ) class Queries6Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") t1 = Tag.objects.create(name='t1', category=generic) Tag.objects.create(name='t2', parent=t1, category=generic) t3 = Tag.objects.create(name='t3', parent=t1) t4 = Tag.objects.create(name='t4', parent=t3) Tag.objects.create(name='t5', parent=t3) n1 = Note.objects.create(note='n1', misc='foo', id=1) ann1 = Annotation.objects.create(name='a1', tag=t1) ann1.notes.add(n1) Annotation.objects.create(name='a2', tag=t4) def test_parallel_iterators(self): # Parallel iterators work. qs = Tag.objects.all() i1, i2 = iter(qs), iter(qs) self.assertEqual(repr(next(i1)), '<Tag: t1>') self.assertEqual(repr(next(i1)), '<Tag: t2>') self.assertEqual(repr(next(i2)), '<Tag: t1>') self.assertEqual(repr(next(i2)), '<Tag: t2>') self.assertEqual(repr(next(i2)), '<Tag: t3>') self.assertEqual(repr(next(i1)), '<Tag: t3>') qs = X.objects.all() self.assertFalse(qs) self.assertFalse(qs) def test_nested_queries_sql(self): # Nested queries should not evaluate the inner query as part of constructing the # SQL (so we should see a nested query here, indicated by two "SELECT" calls). qs = Annotation.objects.filter(notes__in=Note.objects.filter(note="xyzzy")) self.assertEqual( qs.query.get_compiler(qs.db).as_sql()[0].count('SELECT'), 2 ) def test_tickets_8921_9188(self): # Incorrect SQL was being generated for certain types of exclude() # queries that crossed multi-valued relations (#8921, #9188 and some # preemptively discovered cases). self.assertQuerysetEqual( PointerA.objects.filter(connection__pointerb__id=1), [] ) self.assertQuerysetEqual( PointerA.objects.exclude(connection__pointerb__id=1), [] ) self.assertQuerysetEqual( Tag.objects.exclude(children=None), ['<Tag: t1>', '<Tag: t3>'] ) # This example is tricky because the parent could be NULL, so only checking # parents with annotations omits some results (tag t1, in this case). self.assertQuerysetEqual( Tag.objects.exclude(parent__annotation__name="a1"), ['<Tag: t1>', '<Tag: t4>', '<Tag: t5>'] ) # The annotation->tag link is single values and tag->children links is # multi-valued. So we have to split the exclude filter in the middle # and then optimize the inner query without losing results. self.assertQuerysetEqual( Annotation.objects.exclude(tag__children__name="t2"), ['<Annotation: a2>'] ) # Nested queries are possible (although should be used with care, since # they have performance problems on backends like MySQL. self.assertQuerysetEqual( Annotation.objects.filter(notes__in=Note.objects.filter(note="n1")), ['<Annotation: a1>'] ) def test_ticket3739(self): # The all() method on querysets returns a copy of the queryset. q1 = Tag.objects.order_by('name') self.assertIsNot(q1, q1.all()) def test_ticket_11320(self): qs = Tag.objects.exclude(category=None).exclude(category__name='foo') self.assertEqual(str(qs.query).count(' INNER JOIN '), 1) def test_distinct_ordered_sliced_subquery_aggregation(self): self.assertEqual(Tag.objects.distinct().order_by('category__name')[:3].count(), 3) class RawQueriesTests(TestCase): def setUp(self): Note.objects.create(note='n1', misc='foo', id=1) def test_ticket14729(self): # Test representation of raw query with one or few parameters passed as list query = "SELECT * FROM queries_note WHERE note = %s" params = ['n1'] qs = Note.objects.raw(query, params=params) self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1>") query = "SELECT * FROM queries_note WHERE note = %s and misc = %s" params = ['n1', 'foo'] qs = Note.objects.raw(query, params=params) self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1 and misc = foo>") class GeneratorExpressionTests(TestCase): def test_ticket10432(self): # Using an empty generator expression as the rvalue for an "__in" # lookup is legal. self.assertQuerysetEqual( Note.objects.filter(pk__in=(x for x in ())), [] ) class ComparisonTests(TestCase): def setUp(self): self.n1 = Note.objects.create(note='n1', misc='foo', id=1) e1 = ExtraInfo.objects.create(info='e1', note=self.n1) self.a2 = Author.objects.create(name='a2', num=2002, extra=e1) def test_ticket8597(self): # Regression tests for case-insensitive comparisons Item.objects.create(name="a_b", created=datetime.datetime.now(), creator=self.a2, note=self.n1) Item.objects.create(name="x%y", created=datetime.datetime.now(), creator=self.a2, note=self.n1) self.assertQuerysetEqual( Item.objects.filter(name__iexact="A_b"), ['<Item: a_b>'] ) self.assertQuerysetEqual( Item.objects.filter(name__iexact="x%Y"), ['<Item: x%y>'] ) self.assertQuerysetEqual( Item.objects.filter(name__istartswith="A_b"), ['<Item: a_b>'] ) self.assertQuerysetEqual( Item.objects.filter(name__iendswith="A_b"), ['<Item: a_b>'] ) class ExistsSql(TestCase): def test_exists(self): with CaptureQueriesContext(connection) as captured_queries: self.assertFalse(Tag.objects.exists()) # Ok - so the exist query worked - but did it include too many columns? self.assertEqual(len(captured_queries), 1) qstr = captured_queries[0]['sql'] id, name = connection.ops.quote_name('id'), connection.ops.quote_name('name') self.assertNotIn(id, qstr) self.assertNotIn(name, qstr) def test_ticket_18414(self): Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) self.assertTrue(Article.objects.exists()) self.assertTrue(Article.objects.distinct().exists()) self.assertTrue(Article.objects.distinct()[1:3].exists()) self.assertFalse(Article.objects.distinct()[1:1].exists()) @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_18414_distinct_on(self): Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) self.assertTrue(Article.objects.distinct('name').exists()) self.assertTrue(Article.objects.distinct('name')[1:2].exists()) self.assertFalse(Article.objects.distinct('name')[2:3].exists()) class QuerysetOrderedTests(unittest.TestCase): """ Tests for the Queryset.ordered attribute. """ def test_no_default_or_explicit_ordering(self): self.assertIs(Annotation.objects.all().ordered, False) def test_cleared_default_ordering(self): self.assertIs(Tag.objects.all().ordered, True) self.assertIs(Tag.objects.all().order_by().ordered, False) def test_explicit_ordering(self): self.assertIs(Annotation.objects.all().order_by('id').ordered, True) def test_order_by_extra(self): self.assertIs(Annotation.objects.all().extra(order_by=['id']).ordered, True) def test_annotated_ordering(self): qs = Annotation.objects.annotate(num_notes=Count('notes')) self.assertIs(qs.ordered, False) self.assertIs(qs.order_by('num_notes').ordered, True) @skipUnlessDBFeature('allow_sliced_subqueries_with_in') class SubqueryTests(TestCase): @classmethod def setUpTestData(cls): NamedCategory.objects.create(id=1, name='first') NamedCategory.objects.create(id=2, name='second') NamedCategory.objects.create(id=3, name='third') NamedCategory.objects.create(id=4, name='fourth') def test_ordered_subselect(self): "Subselects honor any manual ordering" query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:]) self.assertEqual(set(query.values_list('id', flat=True)), {1, 2}) def test_slice_subquery_and_query(self): """ Slice a query that has a sliced subquery """ query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])[0:2] self.assertEqual({x.id for x in query}, {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:3])[1:3] self.assertEqual({x.id for x in query}, {3}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])[1:] self.assertEqual({x.id for x in query}, {2}) def test_related_sliced_subquery(self): """ Related objects constraints can safely contain sliced subqueries. refs #22434 """ generic = NamedCategory.objects.create(id=5, name="Generic") t1 = Tag.objects.create(name='t1', category=generic) t2 = Tag.objects.create(name='t2', category=generic) ManagedModel.objects.create(data='mm1', tag=t1, public=True) mm2 = ManagedModel.objects.create(data='mm2', tag=t2, public=True) query = ManagedModel.normal_manager.filter( tag__in=Tag.objects.order_by('-id')[:1] ) self.assertEqual({x.id for x in query}, {mm2.id}) def test_sliced_delete(self): "Delete queries can safely contain sliced subqueries" DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 2, 3}) DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 3}) DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {3}) def test_distinct_ordered_sliced_subquery(self): # Implicit values('id'). self.assertSequenceEqual( NamedCategory.objects.filter( id__in=NamedCategory.objects.distinct().order_by('name')[0:2], ).order_by('name').values_list('name', flat=True), ['first', 'fourth'] ) # Explicit values('id'). self.assertSequenceEqual( NamedCategory.objects.filter( id__in=NamedCategory.objects.distinct().order_by('-name').values('id')[0:2], ).order_by('name').values_list('name', flat=True), ['second', 'third'] ) # Annotated value. self.assertSequenceEqual( DumbCategory.objects.filter( id__in=DumbCategory.objects.annotate( double_id=F('id') * 2 ).order_by('id').distinct().values('double_id')[0:2], ).order_by('id').values_list('id', flat=True), [2, 4] ) class CloneTests(TestCase): def test_evaluated_queryset_as_argument(self): "#13227 -- If a queryset is already evaluated, it can still be used as a query arg" n = Note(note='Test1', misc='misc') n.save() e = ExtraInfo(info='good', note=n) e.save() n_list = Note.objects.all() # Evaluate the Note queryset, populating the query cache list(n_list) # Use the note queryset in a query, and evaluate # that query in a way that involves cloning. self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good') def test_no_model_options_cloning(self): """ Cloning a queryset does not get out of hand. While complete testing is impossible, this is a sanity check against invalid use of deepcopy. refs #16759. """ opts_class = type(Note._meta) note_deepcopy = getattr(opts_class, "__deepcopy__", None) opts_class.__deepcopy__ = lambda obj, memo: self.fail("Model options shouldn't be cloned.") try: Note.objects.filter(pk__lte=F('pk') + 1).all() finally: if note_deepcopy is None: delattr(opts_class, "__deepcopy__") else: opts_class.__deepcopy__ = note_deepcopy def test_no_fields_cloning(self): """ Cloning a queryset does not get out of hand. While complete testing is impossible, this is a sanity check against invalid use of deepcopy. refs #16759. """ opts_class = type(Note._meta.get_field("misc")) note_deepcopy = getattr(opts_class, "__deepcopy__", None) opts_class.__deepcopy__ = lambda obj, memo: self.fail("Model fields shouldn't be cloned") try: Note.objects.filter(note=F('misc')).all() finally: if note_deepcopy is None: delattr(opts_class, "__deepcopy__") else: opts_class.__deepcopy__ = note_deepcopy class EmptyQuerySetTests(TestCase): def test_emptyqueryset_values(self): # #14366 -- Calling .values() on an empty QuerySet and then cloning # that should not cause an error self.assertQuerysetEqual( Number.objects.none().values('num').order_by('num'), [] ) def test_values_subquery(self): self.assertQuerysetEqual( Number.objects.filter(pk__in=Number.objects.none().values("pk")), [] ) self.assertQuerysetEqual( Number.objects.filter(pk__in=Number.objects.none().values_list("pk")), [] ) def test_ticket_19151(self): # #19151 -- Calling .values() or .values_list() on an empty QuerySet # should return an empty QuerySet and not cause an error. q = Author.objects.none() self.assertQuerysetEqual(q.values(), []) self.assertQuerysetEqual(q.values_list(), []) class ValuesQuerysetTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=72) def test_flat_values_list(self): qs = Number.objects.values_list("num") qs = qs.values_list("num", flat=True) self.assertSequenceEqual(qs, [72]) def test_extra_values(self): # testing for ticket 14930 issues qs = Number.objects.extra(select=OrderedDict([('value_plus_x', 'num+%s'), ('value_minus_x', 'num-%s')]), select_params=(1, 2)) qs = qs.order_by('value_minus_x') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_twice(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1', 'value_minus_one': 'num-1'}) qs = qs.order_by('value_minus_one').order_by('value_plus_one') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_multiple(self): # Postgres doesn't allow constants in order by, so check for that. qs = Number.objects.extra(select={ 'value_plus_one': 'num+1', 'value_minus_one': 'num-1', 'constant_value': '1' }) qs = qs.order_by('value_plus_one', 'value_minus_one', 'constant_value') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_in_extra(self): # testing for ticket 14930 issues qs = Number.objects.extra( select={'value_plus_one': 'num+1', 'value_minus_one': 'num-1'}, order_by=['value_minus_one'], ) qs = qs.values('num') def test_extra_select_params_values_order_in_extra(self): # testing for 23259 issue qs = Number.objects.extra( select={'value_plus_x': 'num+%s'}, select_params=[1], order_by=['value_plus_x'], ) qs = qs.filter(num=72) qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_multiple_select_params_values_order_by(self): # testing for 23259 issue qs = Number.objects.extra(select=OrderedDict([('value_plus_x', 'num+%s'), ('value_minus_x', 'num-%s')]), select_params=(72, 72)) qs = qs.order_by('value_minus_x') qs = qs.filter(num=1) qs = qs.values('num') self.assertSequenceEqual(qs, []) def test_extra_values_list(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1'}) qs = qs.order_by('value_plus_one') qs = qs.values_list('num') self.assertSequenceEqual(qs, [(72,)]) def test_flat_extra_values_list(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1'}) qs = qs.order_by('value_plus_one') qs = qs.values_list('num', flat=True) self.assertSequenceEqual(qs, [72]) def test_field_error_values_list(self): # see #23443 msg = "Cannot resolve keyword %r into field. Join on 'name' not permitted." % 'foo' with self.assertRaisesMessage(FieldError, msg): Tag.objects.values_list('name__foo') def test_named_values_list_flat(self): msg = "'flat' and 'named' can't be used together." with self.assertRaisesMessage(TypeError, msg): Number.objects.values_list('num', flat=True, named=True) def test_named_values_list_bad_field_name(self): msg = "Type names and field names must be valid identifiers: '1'" with self.assertRaisesMessage(ValueError, msg): Number.objects.extra(select={'1': 'num+1'}).values_list('1', named=True).first() def test_named_values_list_with_fields(self): qs = Number.objects.extra(select={'num2': 'num+1'}).annotate(Count('id')) values = qs.values_list('num', 'num2', named=True).first() self.assertEqual(type(values).__name__, 'Row') self.assertEqual(values._fields, ('num', 'num2')) self.assertEqual(values.num, 72) self.assertEqual(values.num2, 73) def test_named_values_list_without_fields(self): qs = Number.objects.extra(select={'num2': 'num+1'}).annotate(Count('id')) values = qs.values_list(named=True).first() self.assertEqual(type(values).__name__, 'Row') self.assertEqual(values._fields, ('num2', 'id', 'num', 'id__count')) self.assertEqual(values.num, 72) self.assertEqual(values.num2, 73) self.assertEqual(values.id__count, 1) def test_named_values_list_expression_with_default_alias(self): expr = Count('id') values = Number.objects.annotate(id__count1=expr).values_list(expr, 'id__count1', named=True).first() self.assertEqual(values._fields, ('id__count2', 'id__count1')) def test_named_values_list_expression(self): expr = F('num') + 1 qs = Number.objects.annotate(combinedexpression1=expr).values_list(expr, 'combinedexpression1', named=True) values = qs.first() self.assertEqual(values._fields, ('combinedexpression2', 'combinedexpression1')) class QuerySetSupportsPythonIdioms(TestCase): @classmethod def setUpTestData(cls): some_date = datetime.datetime(2014, 5, 16, 12, 1) for i in range(1, 8): Article.objects.create( name="Article {}".format(i), created=some_date) def get_ordered_articles(self): return Article.objects.all().order_by('name') def test_can_get_items_using_index_and_slice_notation(self): self.assertEqual(self.get_ordered_articles()[0].name, 'Article 1') self.assertQuerysetEqual( self.get_ordered_articles()[1:3], ["<Article: Article 2>", "<Article: Article 3>"] ) def test_slicing_with_steps_can_be_used(self): self.assertQuerysetEqual( self.get_ordered_articles()[::2], [ "<Article: Article 1>", "<Article: Article 3>", "<Article: Article 5>", "<Article: Article 7>" ] ) def test_slicing_without_step_is_lazy(self): with self.assertNumQueries(0): self.get_ordered_articles()[0:5] def test_slicing_with_tests_is_not_lazy(self): with self.assertNumQueries(1): self.get_ordered_articles()[0:5:3] def test_slicing_can_slice_again_after_slicing(self): self.assertQuerysetEqual( self.get_ordered_articles()[0:5][0:2], ["<Article: Article 1>", "<Article: Article 2>"] ) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], ["<Article: Article 5>"]) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][5:], []) # Some more tests! self.assertQuerysetEqual( self.get_ordered_articles()[2:][0:2], ["<Article: Article 3>", "<Article: Article 4>"] ) self.assertQuerysetEqual( self.get_ordered_articles()[2:][:2], ["<Article: Article 3>", "<Article: Article 4>"] ) self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], ["<Article: Article 5>"]) # Using an offset without a limit is also possible. self.assertQuerysetEqual( self.get_ordered_articles()[5:], ["<Article: Article 6>", "<Article: Article 7>"] ) def test_slicing_cannot_filter_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."): Article.objects.all()[0:5].filter(id=1) def test_slicing_cannot_reorder_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot reorder a query once a slice has been taken."): Article.objects.all()[0:5].order_by('id') def test_slicing_cannot_combine_queries_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot combine queries once a slice has been taken."): Article.objects.all()[0:1] & Article.objects.all()[4:5] def test_slicing_negative_indexing_not_supported_for_single_element(self): """hint: inverting your ordering might do what you need""" with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): Article.objects.all()[-1] def test_slicing_negative_indexing_not_supported_for_range(self): """hint: inverting your ordering might do what you need""" with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): Article.objects.all()[0:-5] def test_can_get_number_of_items_in_queryset_using_standard_len(self): self.assertEqual(len(Article.objects.filter(name__exact='Article 1')), 1) def test_can_combine_queries_using_and_and_or_operators(self): s1 = Article.objects.filter(name__exact='Article 1') s2 = Article.objects.filter(name__exact='Article 2') self.assertQuerysetEqual( (s1 | s2).order_by('name'), ["<Article: Article 1>", "<Article: Article 2>"] ) self.assertQuerysetEqual(s1 & s2, []) class WeirdQuerysetSlicingTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=1) Number.objects.create(num=2) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) Article.objects.create(name='three', created=datetime.datetime.now()) Article.objects.create(name='four', created=datetime.datetime.now()) food = Food.objects.create(name='spam') Eaten.objects.create(meal='spam with eggs', food=food) def test_tickets_7698_10202(self): # People like to slice with '0' as the high-water mark. self.assertQuerysetEqual(Article.objects.all()[0:0], []) self.assertQuerysetEqual(Article.objects.all()[0:0][:10], []) self.assertEqual(Article.objects.all()[:0].count(), 0) with self.assertRaisesMessage(TypeError, 'Cannot reverse a query once a slice has been taken.'): Article.objects.all()[:0].latest('created') def test_empty_resultset_sql(self): # ticket #12192 self.assertNumQueries(0, lambda: list(Number.objects.all()[1:1])) def test_empty_sliced_subquery(self): self.assertEqual(Eaten.objects.filter(food__in=Food.objects.all()[0:0]).count(), 0) def test_empty_sliced_subquery_exclude(self): self.assertEqual(Eaten.objects.exclude(food__in=Food.objects.all()[0:0]).count(), 1) def test_zero_length_values_slicing(self): n = 42 with self.assertNumQueries(0): self.assertQuerysetEqual(Article.objects.values()[n:n], []) self.assertQuerysetEqual(Article.objects.values_list()[n:n], []) class EscapingTests(TestCase): def test_ticket_7302(self): # Reserved names are appropriately escaped ReservedName.objects.create(name='a', order=42) ReservedName.objects.create(name='b', order=37) self.assertQuerysetEqual( ReservedName.objects.all().order_by('order'), ['<ReservedName: b>', '<ReservedName: a>'] ) self.assertQuerysetEqual( ReservedName.objects.extra(select={'stuff': 'name'}, order_by=('order', 'stuff')), ['<ReservedName: b>', '<ReservedName: a>'] ) class ToFieldTests(TestCase): def test_in_query(self): apple = Food.objects.create(name="apple") pear = Food.objects.create(name="pear") lunch = Eaten.objects.create(food=apple, meal="lunch") dinner = Eaten.objects.create(food=pear, meal="dinner") self.assertEqual( set(Eaten.objects.filter(food__in=[apple, pear])), {lunch, dinner}, ) def test_in_subquery(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") self.assertEqual( set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple'))), {lunch} ) self.assertEqual( set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple').values('eaten__meal'))), set() ) self.assertEqual( set(Food.objects.filter(eaten__in=Eaten.objects.filter(meal='lunch'))), {apple} ) def test_nested_in_subquery(self): extra = ExtraInfo.objects.create() author = Author.objects.create(num=42, extra=extra) report = Report.objects.create(creator=author) comment = ReportComment.objects.create(report=report) comments = ReportComment.objects.filter( report__in=Report.objects.filter( creator__in=extra.author_set.all(), ), ) self.assertSequenceEqual(comments, [comment]) def test_reverse_in(self): apple = Food.objects.create(name="apple") pear = Food.objects.create(name="pear") lunch_apple = Eaten.objects.create(food=apple, meal="lunch") lunch_pear = Eaten.objects.create(food=pear, meal="dinner") self.assertEqual( set(Food.objects.filter(eaten__in=[lunch_apple, lunch_pear])), {apple, pear} ) def test_single_object(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") dinner = Eaten.objects.create(food=apple, meal="dinner") self.assertEqual( set(Eaten.objects.filter(food=apple)), {lunch, dinner} ) def test_single_object_reverse(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") self.assertEqual( set(Food.objects.filter(eaten=lunch)), {apple} ) def test_recursive_fk(self): node1 = Node.objects.create(num=42) node2 = Node.objects.create(num=1, parent=node1) self.assertEqual( list(Node.objects.filter(parent=node1)), [node2] ) def test_recursive_fk_reverse(self): node1 = Node.objects.create(num=42) node2 = Node.objects.create(num=1, parent=node1) self.assertEqual( list(Node.objects.filter(node=node2)), [node1] ) class IsNullTests(TestCase): def test_primary_key(self): custom = CustomPk.objects.create(name='pk') null = Related.objects.create() notnull = Related.objects.create(custom=custom) self.assertSequenceEqual(Related.objects.filter(custom__isnull=False), [notnull]) self.assertSequenceEqual(Related.objects.filter(custom__isnull=True), [null]) def test_to_field(self): apple = Food.objects.create(name="apple") Eaten.objects.create(food=apple, meal="lunch") Eaten.objects.create(meal="lunch") self.assertQuerysetEqual( Eaten.objects.filter(food__isnull=False), ['<Eaten: apple at lunch>'] ) self.assertQuerysetEqual( Eaten.objects.filter(food__isnull=True), ['<Eaten: None at lunch>'] ) class ConditionalTests(TestCase): """Tests whose execution depend on different environment conditions like Python version or DB backend features""" @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") t1 = Tag.objects.create(name='t1', category=generic) Tag.objects.create(name='t2', parent=t1, category=generic) t3 = Tag.objects.create(name='t3', parent=t1) Tag.objects.create(name='t4', parent=t3) Tag.objects.create(name='t5', parent=t3) def test_infinite_loop(self): # If you're not careful, it's possible to introduce infinite loops via # default ordering on foreign keys in a cycle. We detect that. with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): list(LoopX.objects.all()) # Force queryset evaluation with list() with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): list(LoopZ.objects.all()) # Force queryset evaluation with list() # Note that this doesn't cause an infinite loop, since the default # ordering on the Tag model is empty (and thus defaults to using "id" # for the related field). self.assertEqual(len(Tag.objects.order_by('parent')), 5) # ... but you can still order in a non-recursive fashion among linked # fields (the previous test failed because the default ordering was # recursive). self.assertQuerysetEqual( LoopX.objects.all().order_by('y__x__y__x__id'), [] ) # When grouping without specifying ordering, we add an explicit "ORDER BY NULL" # portion in MySQL to prevent unnecessary sorting. @skipUnlessDBFeature('requires_explicit_null_ordering_when_grouping') def test_null_ordering_added(self): query = Tag.objects.values_list('parent_id', flat=True).order_by().query query.group_by = ['parent_id'] sql = query.get_compiler(DEFAULT_DB_ALIAS).as_sql()[0] fragment = "ORDER BY " pos = sql.find(fragment) self.assertEqual(sql.find(fragment, pos + 1), -1) self.assertEqual(sql.find("NULL", pos + len(fragment)), pos + len(fragment)) def test_in_list_limit(self): # The "in" lookup works with lists of 1000 items or more. # The numbers amount is picked to force three different IN batches # for Oracle, yet to be less than 2100 parameter limit for MSSQL. numbers = list(range(2050)) max_query_params = connection.features.max_query_params if max_query_params is None or max_query_params >= len(numbers): Number.objects.bulk_create(Number(num=num) for num in numbers) for number in [1000, 1001, 2000, len(numbers)]: with self.subTest(number=number): self.assertEqual(Number.objects.filter(num__in=numbers[:number]).count(), number) class UnionTests(unittest.TestCase): """ Tests for the union of two querysets. Bug #12252. """ @classmethod def setUpTestData(cls): objectas = [] objectbs = [] objectcs = [] a_info = ['one', 'two', 'three'] for name in a_info: o = ObjectA(name=name) o.save() objectas.append(o) b_info = [('un', 1, objectas[0]), ('deux', 2, objectas[0]), ('trois', 3, objectas[2])] for name, number, objecta in b_info: o = ObjectB(name=name, num=number, objecta=objecta) o.save() objectbs.append(o) c_info = [('ein', objectas[2], objectbs[2]), ('zwei', objectas[1], objectbs[1])] for name, objecta, objectb in c_info: o = ObjectC(name=name, objecta=objecta, objectb=objectb) o.save() objectcs.append(o) def check_union(self, model, Q1, Q2): filter = model.objects.filter self.assertEqual(set(filter(Q1) | filter(Q2)), set(filter(Q1 | Q2))) self.assertEqual(set(filter(Q2) | filter(Q1)), set(filter(Q1 | Q2))) def test_A_AB(self): Q1 = Q(name='two') Q2 = Q(objectb__name='deux') self.check_union(ObjectA, Q1, Q2) def test_A_AB2(self): Q1 = Q(name='two') Q2 = Q(objectb__name='deux', objectb__num=2) self.check_union(ObjectA, Q1, Q2) def test_AB_ACB(self): Q1 = Q(objectb__name='deux') Q2 = Q(objectc__objectb__name='deux') self.check_union(ObjectA, Q1, Q2) def test_BAB_BAC(self): Q1 = Q(objecta__objectb__name='deux') Q2 = Q(objecta__objectc__name='ein') self.check_union(ObjectB, Q1, Q2) def test_BAB_BACB(self): Q1 = Q(objecta__objectb__name='deux') Q2 = Q(objecta__objectc__objectb__name='trois') self.check_union(ObjectB, Q1, Q2) def test_BA_BCA__BAB_BAC_BCA(self): Q1 = Q(objecta__name='one', objectc__objecta__name='two') Q2 = Q(objecta__objectc__name='ein', objectc__objecta__name='three', objecta__objectb__name='trois') self.check_union(ObjectB, Q1, Q2) class DefaultValuesInsertTest(TestCase): def test_no_extra_params(self): """ Can create an instance of a model with only the PK field (#17056)." """ DumbCategory.objects.create() class ExcludeTests(TestCase): @classmethod def setUpTestData(cls): f1 = Food.objects.create(name='apples') Food.objects.create(name='oranges') Eaten.objects.create(food=f1, meal='dinner') j1 = Job.objects.create(name='Manager') r1 = Responsibility.objects.create(description='Playing golf') j2 = Job.objects.create(name='Programmer') r2 = Responsibility.objects.create(description='Programming') JobResponsibilities.objects.create(job=j1, responsibility=r1) JobResponsibilities.objects.create(job=j2, responsibility=r2) def test_to_field(self): self.assertQuerysetEqual( Food.objects.exclude(eaten__meal='dinner'), ['<Food: oranges>']) self.assertQuerysetEqual( Job.objects.exclude(responsibilities__description='Playing golf'), ['<Job: Programmer>']) self.assertQuerysetEqual( Responsibility.objects.exclude(jobs__name='Manager'), ['<Responsibility: Programming>']) def test_ticket14511(self): alex = Person.objects.get_or_create(name='Alex')[0] jane = Person.objects.get_or_create(name='Jane')[0] oracle = Company.objects.get_or_create(name='Oracle')[0] google = Company.objects.get_or_create(name='Google')[0] microsoft = Company.objects.get_or_create(name='Microsoft')[0] intel = Company.objects.get_or_create(name='Intel')[0] def employ(employer, employee, title): Employment.objects.get_or_create(employee=employee, employer=employer, title=title) employ(oracle, alex, 'Engineer') employ(oracle, alex, 'Developer') employ(google, alex, 'Engineer') employ(google, alex, 'Manager') employ(microsoft, alex, 'Manager') employ(intel, alex, 'Manager') employ(microsoft, jane, 'Developer') employ(intel, jane, 'Manager') alex_tech_employers = alex.employers.filter( employment__title__in=('Engineer', 'Developer')).distinct().order_by('name') self.assertSequenceEqual(alex_tech_employers, [google, oracle]) alex_nontech_employers = alex.employers.exclude( employment__title__in=('Engineer', 'Developer')).distinct().order_by('name') self.assertSequenceEqual(alex_nontech_employers, [google, intel, microsoft]) class ExcludeTest17600(TestCase): """ Some regressiontests for ticket #17600. Some of these likely duplicate other existing tests. """ @classmethod def setUpTestData(cls): # Create a few Orders. cls.o1 = Order.objects.create(pk=1) cls.o2 = Order.objects.create(pk=2) cls.o3 = Order.objects.create(pk=3) # Create some OrderItems for the first order with homogeneous # status_id values cls.oi1 = OrderItem.objects.create(order=cls.o1, status=1) cls.oi2 = OrderItem.objects.create(order=cls.o1, status=1) cls.oi3 = OrderItem.objects.create(order=cls.o1, status=1) # Create some OrderItems for the second order with heterogeneous # status_id values cls.oi4 = OrderItem.objects.create(order=cls.o2, status=1) cls.oi5 = OrderItem.objects.create(order=cls.o2, status=2) cls.oi6 = OrderItem.objects.create(order=cls.o2, status=3) # Create some OrderItems for the second order with heterogeneous # status_id values cls.oi7 = OrderItem.objects.create(order=cls.o3, status=2) cls.oi8 = OrderItem.objects.create(order=cls.o3, status=3) cls.oi9 = OrderItem.objects.create(order=cls.o3, status=4) def test_exclude_plain(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(items__status=1), ['<Order: 3>']) def test_exclude_plain_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(items__status=1).distinct(), ['<Order: 3>']) def test_exclude_with_q_object_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(Q(items__status=1)).distinct(), ['<Order: 3>']) def test_exclude_with_q_object_no_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(Q(items__status=1)), ['<Order: 3>']) def test_exclude_with_q_is_equal_to_plain_exclude(self): """ Using exclude(condition) and exclude(Q(condition)) should yield the same QuerySet """ self.assertEqual( list(Order.objects.exclude(items__status=1).distinct()), list(Order.objects.exclude(Q(items__status=1)).distinct())) def test_exclude_with_q_is_equal_to_plain_exclude_variation(self): """ Using exclude(condition) and exclude(Q(condition)) should yield the same QuerySet """ self.assertEqual( list(Order.objects.exclude(items__status=1)), list(Order.objects.exclude(Q(items__status=1)).distinct())) @unittest.expectedFailure def test_only_orders_with_all_items_having_status_1(self): """ This should only return orders having ALL items set to status 1, or those items not having any orders at all. The correct way to write this query in SQL seems to be using two nested subqueries. """ self.assertQuerysetEqual( Order.objects.exclude(~Q(items__status=1)).distinct(), ['<Order: 1>']) class Exclude15786(TestCase): """Regression test for #15786""" def test_ticket15786(self): c1 = SimpleCategory.objects.create(name='c1') c2 = SimpleCategory.objects.create(name='c2') OneToOneCategory.objects.create(category=c1) OneToOneCategory.objects.create(category=c2) rel = CategoryRelationship.objects.create(first=c1, second=c2) self.assertEqual( CategoryRelationship.objects.exclude( first__onetoonecategory=F('second__onetoonecategory') ).get(), rel ) class NullInExcludeTest(TestCase): @classmethod def setUpTestData(cls): NullableName.objects.create(name='i1') NullableName.objects.create() def test_null_in_exclude_qs(self): none_val = '' if connection.features.interprets_empty_strings_as_nulls else None self.assertQuerysetEqual( NullableName.objects.exclude(name__in=[]), ['i1', none_val], attrgetter('name')) self.assertQuerysetEqual( NullableName.objects.exclude(name__in=['i1']), [none_val], attrgetter('name')) self.assertQuerysetEqual( NullableName.objects.exclude(name__in=['i3']), ['i1', none_val], attrgetter('name')) inner_qs = NullableName.objects.filter(name='i1').values_list('name') self.assertQuerysetEqual( NullableName.objects.exclude(name__in=inner_qs), [none_val], attrgetter('name')) # The inner queryset wasn't executed - it should be turned # into subquery above self.assertIs(inner_qs._result_cache, None) @unittest.expectedFailure def test_col_not_in_list_containing_null(self): """ The following case is not handled properly because SQL's COL NOT IN (list containing null) handling is too weird to abstract away. """ self.assertQuerysetEqual( NullableName.objects.exclude(name__in=[None]), ['i1'], attrgetter('name')) def test_double_exclude(self): self.assertEqual( list(NullableName.objects.filter(~~Q(name='i1'))), list(NullableName.objects.filter(Q(name='i1')))) self.assertNotIn( 'IS NOT NULL', str(NullableName.objects.filter(~~Q(name='i1')).query)) class EmptyStringsAsNullTest(TestCase): """ Filtering on non-null character fields works as expected. The reason for these tests is that Oracle treats '' as NULL, and this can cause problems in query construction. Refs #17957. """ @classmethod def setUpTestData(cls): cls.nc = NamedCategory.objects.create(name='') def test_direct_exclude(self): self.assertQuerysetEqual( NamedCategory.objects.exclude(name__in=['nonexistent']), [self.nc.pk], attrgetter('pk') ) def test_joined_exclude(self): self.assertQuerysetEqual( DumbCategory.objects.exclude(namedcategory__name__in=['nonexistent']), [self.nc.pk], attrgetter('pk') ) def test_21001(self): foo = NamedCategory.objects.create(name='foo') self.assertQuerysetEqual( NamedCategory.objects.exclude(name=''), [foo.pk], attrgetter('pk') ) class ProxyQueryCleanupTest(TestCase): def test_evaluated_proxy_count(self): """ Generating the query string doesn't alter the query's state in irreversible ways. Refs #18248. """ ProxyCategory.objects.create() qs = ProxyCategory.objects.all() self.assertEqual(qs.count(), 1) str(qs.query) self.assertEqual(qs.count(), 1) class WhereNodeTest(TestCase): class DummyNode: def as_sql(self, compiler, connection): return 'dummy', [] class MockCompiler: def compile(self, node): return node.as_sql(self, connection) def __call__(self, name): return connection.ops.quote_name(name) def test_empty_full_handling_conjunction(self): compiler = WhereNodeTest.MockCompiler() w = WhereNode(children=[NothingNode()]) with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[self.DummyNode(), self.DummyNode()]) self.assertEqual(w.as_sql(compiler, connection), ('(dummy AND dummy)', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', [])) w = WhereNode(children=[NothingNode(), self.DummyNode()]) with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) def test_empty_full_handling_disjunction(self): compiler = WhereNodeTest.MockCompiler() w = WhereNode(children=[NothingNode()], connector='OR') with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('(dummy OR dummy)', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy OR dummy)', [])) w = WhereNode(children=[NothingNode(), self.DummyNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('dummy', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy)', [])) def test_empty_nodes(self): compiler = WhereNodeTest.MockCompiler() empty_w = WhereNode() w = WhereNode(children=[empty_w, empty_w]) self.assertEqual(w.as_sql(compiler, connection), ('', [])) w.negate() with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.connector = 'OR' with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[empty_w, NothingNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[empty_w, NothingNode()], connector='AND') with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) class QuerySetExceptionTests(TestCase): def test_iter_exceptions(self): qs = ExtraInfo.objects.only('author') msg = "'ManyToOneRel' object has no attribute 'attname'" with self.assertRaisesMessage(AttributeError, msg): list(qs) def test_invalid_qs_list(self): # Test for #19895 - second iteration over invalid queryset # raises errors. qs = Article.objects.order_by('invalid_column') msg = "Cannot resolve keyword 'invalid_column' into field." with self.assertRaisesMessage(FieldError, msg): list(qs) with self.assertRaisesMessage(FieldError, msg): list(qs) def test_invalid_order_by(self): msg = "Invalid order_by arguments: ['*']" with self.assertRaisesMessage(FieldError, msg): list(Article.objects.order_by('*')) def test_invalid_queryset_model(self): msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".' with self.assertRaisesMessage(ValueError, msg): list(Author.objects.filter(extra=Article.objects.all())) class NullJoinPromotionOrTest(TestCase): @classmethod def setUpTestData(cls): cls.d1 = ModelD.objects.create(name='foo') d2 = ModelD.objects.create(name='bar') cls.a1 = ModelA.objects.create(name='a1', d=cls.d1) c = ModelC.objects.create(name='c') b = ModelB.objects.create(name='b', c=c) cls.a2 = ModelA.objects.create(name='a2', b=b, d=d2) def test_ticket_17886(self): # The first Q-object is generating the match, the rest of the filters # should not remove the match even if they do not match anything. The # problem here was that b__name generates a LOUTER JOIN, then # b__c__name generates join to c, which the ORM tried to promote but # failed as that join isn't nullable. q_obj = ( Q(d__name='foo') | Q(b__name='foo') | Q(b__c__name='foo') ) qset = ModelA.objects.filter(q_obj) self.assertEqual(list(qset), [self.a1]) # We generate one INNER JOIN to D. The join is direct and not nullable # so we can use INNER JOIN for it. However, we can NOT use INNER JOIN # for the b->c join, as a->b is nullable. self.assertEqual(str(qset.query).count('INNER JOIN'), 1) def test_isnull_filter_promotion(self): qs = ModelA.objects.filter(Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(~Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) qs = ModelA.objects.filter(~~Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) qs = ModelA.objects.filter(~Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(~~Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) def test_null_join_demotion(self): qs = ModelA.objects.filter(Q(b__name__isnull=False) & Q(b__name__isnull=True)) self.assertIn(' INNER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=True) & Q(b__name__isnull=False)) self.assertIn(' INNER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=False) | Q(b__name__isnull=True)) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=True) | Q(b__name__isnull=False)) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_ticket_21366(self): n = Note.objects.create(note='n', misc='m') e = ExtraInfo.objects.create(info='info', note=n) a = Author.objects.create(name='Author1', num=1, extra=e) Ranking.objects.create(rank=1, author=a) r1 = Report.objects.create(name='Foo', creator=a) r2 = Report.objects.create(name='Bar') Report.objects.create(name='Bar', creator=a) qs = Report.objects.filter( Q(creator__ranking__isnull=True) | Q(creator__ranking__rank=1, name='Foo') ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count(' JOIN '), 2) self.assertSequenceEqual(qs.order_by('name'), [r2, r1]) def test_ticket_21748(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') i3 = Identifier.objects.create(name='i3') Program.objects.create(identifier=i1) Channel.objects.create(identifier=i1) Program.objects.create(identifier=i2) self.assertSequenceEqual(Identifier.objects.filter(program=None, channel=None), [i3]) self.assertSequenceEqual(Identifier.objects.exclude(program=None, channel=None).order_by('name'), [i1, i2]) def test_ticket_21748_double_negated_and(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) Program.objects.create(identifier=i2) # Check the ~~Q() (or equivalently .exclude(~Q)) works like Q() for # join promotion. qs1_doubleneg = Identifier.objects.exclude(~Q(program__id=p1.id, channel__id=c1.id)).order_by('pk') qs1_filter = Identifier.objects.filter(program__id=p1.id, channel__id=c1.id).order_by('pk') self.assertQuerysetEqual(qs1_doubleneg, qs1_filter, lambda x: x) self.assertEqual(str(qs1_filter.query).count('JOIN'), str(qs1_doubleneg.query).count('JOIN')) self.assertEqual(2, str(qs1_doubleneg.query).count('INNER JOIN')) self.assertEqual(str(qs1_filter.query).count('INNER JOIN'), str(qs1_doubleneg.query).count('INNER JOIN')) def test_ticket_21748_double_negated_or(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) p2 = Program.objects.create(identifier=i2) # Test OR + doubleneg. The expected result is that channel is LOUTER # joined, program INNER joined qs1_filter = Identifier.objects.filter( Q(program__id=p2.id, channel__id=c1.id) | Q(program__id=p1.id) ).order_by('pk') qs1_doubleneg = Identifier.objects.exclude( ~Q(Q(program__id=p2.id, channel__id=c1.id) | Q(program__id=p1.id)) ).order_by('pk') self.assertQuerysetEqual(qs1_doubleneg, qs1_filter, lambda x: x) self.assertEqual(str(qs1_filter.query).count('JOIN'), str(qs1_doubleneg.query).count('JOIN')) self.assertEqual(1, str(qs1_doubleneg.query).count('INNER JOIN')) self.assertEqual(str(qs1_filter.query).count('INNER JOIN'), str(qs1_doubleneg.query).count('INNER JOIN')) def test_ticket_21748_complex_filter(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) p2 = Program.objects.create(identifier=i2) # Finally, a more complex case, one time in a way where each # NOT is pushed to lowest level in the boolean tree, and # another query where this isn't done. qs1 = Identifier.objects.filter( ~Q(~Q(program__id=p2.id, channel__id=c1.id) & Q(program__id=p1.id)) ).order_by('pk') qs2 = Identifier.objects.filter( Q(Q(program__id=p2.id, channel__id=c1.id) | ~Q(program__id=p1.id)) ).order_by('pk') self.assertQuerysetEqual(qs1, qs2, lambda x: x) self.assertEqual(str(qs1.query).count('JOIN'), str(qs2.query).count('JOIN')) self.assertEqual(0, str(qs1.query).count('INNER JOIN')) self.assertEqual(str(qs1.query).count('INNER JOIN'), str(qs2.query).count('INNER JOIN')) class ReverseJoinTrimmingTest(TestCase): def test_reverse_trimming(self): # We don't accidentally trim reverse joins - we can't know if there is # anything on the other side of the join, so trimming reverse joins # can't be done, ever. t = Tag.objects.create() qs = Tag.objects.filter(annotation__tag=t.pk) self.assertIn('INNER JOIN', str(qs.query)) self.assertEqual(list(qs), []) class JoinReuseTest(TestCase): """ The queries reuse joins sensibly (for example, direct joins are always reused). """ def test_fk_reuse(self): qs = Annotation.objects.filter(tag__name='foo').filter(tag__name='bar') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_select_related(self): qs = Annotation.objects.filter(tag__name='foo').select_related('tag') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_annotation(self): qs = Annotation.objects.filter(tag__name='foo').annotate(cnt=Count('tag__name')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_disjunction(self): qs = Annotation.objects.filter(Q(tag__name='foo') | Q(tag__name='bar')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_order_by(self): qs = Annotation.objects.filter(tag__name='foo').order_by('tag__name') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_revo2o_reuse(self): qs = Detail.objects.filter(member__name='foo').filter(member__name='foo') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_revfk_noreuse(self): qs = Author.objects.filter(report__name='r4').filter(report__name='r1') self.assertEqual(str(qs.query).count('JOIN'), 2) def test_inverted_q_across_relations(self): """ When a trimmable join is specified in the query (here school__), the ORM detects it and removes unnecessary joins. The set of reusable joins are updated after trimming the query so that other lookups don't consider that the outer query's filters are in effect for the subquery (#26551). """ springfield_elementary = School.objects.create() hogward = School.objects.create() Student.objects.create(school=springfield_elementary) hp = Student.objects.create(school=hogward) Classroom.objects.create(school=hogward, name='Potion') Classroom.objects.create(school=springfield_elementary, name='Main') qs = Student.objects.filter( ~(Q(school__classroom__name='Main') & Q(school__classroom__has_blackboard=None)) ) self.assertSequenceEqual(qs, [hp]) class DisjunctionPromotionTests(TestCase): def test_disjunction_promotion_select_related(self): fk1 = FK1.objects.create(f1='f1', f2='f2') basea = BaseA.objects.create(a=fk1) qs = BaseA.objects.filter(Q(a=fk1) | Q(b=2)) self.assertEqual(str(qs.query).count(' JOIN '), 0) qs = qs.select_related('a', 'b') self.assertEqual(str(qs.query).count(' INNER JOIN '), 0) self.assertEqual(str(qs.query).count(' LEFT OUTER JOIN '), 2) with self.assertNumQueries(1): self.assertSequenceEqual(qs, [basea]) self.assertEqual(qs[0].a, fk1) self.assertIs(qs[0].b, None) def test_disjunction_promotion1(self): # Pre-existing join, add two ORed filters to the same join, # all joins can be INNER JOINS. qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(Q(b__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) # Reverse the order of AND and OR filters. qs = BaseA.objects.filter(Q(b__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 2) def test_disjunction_promotion2(self): qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # Now we have two different joins in an ORed condition, these # must be OUTER joins. The pre-existing join should remain INNER. qs = qs.filter(Q(b__f1='foo') | Q(c__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) # Reverse case. qs = BaseA.objects.filter(Q(b__f1='foo') | Q(c__f2='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) def test_disjunction_promotion3(self): qs = BaseA.objects.filter(a__f2='bar') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # The ANDed a__f2 filter allows us to use keep using INNER JOIN # even inside the ORed case. If the join to a__ returns nothing, # the ANDed filter for a__f2 can't be true. qs = qs.filter(Q(a__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion3_demote(self): # This one needs demotion logic: the first filter causes a to be # outer joined, the second filter makes it inner join again. qs = BaseA.objects.filter( Q(a__f1='foo') | Q(b__f2='foo')).filter(a__f2='bar') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion4_demote(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) # Demote needed for the "a" join. It is marked as outer join by # above filter (even if it is trimmed away). qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion4(self): qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion5_demote(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) # Note that the above filters on a force the join to an # inner join even if it is trimmed. self.assertEqual(str(qs.query).count('JOIN'), 0) qs = qs.filter(Q(a__f1='foo') | Q(b__f1='foo')) # So, now the a__f1 join doesn't need promotion. self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # But b__f1 does. self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) qs = BaseA.objects.filter(Q(a__f1='foo') | Q(b__f1='foo')) # Now the join to a is created as LOUTER self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion6(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') & Q(b__f1='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') & Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) def test_disjunction_promotion7(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') | (Q(b__f1='foo') & Q(a__f1='bar'))) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) qs = BaseA.objects.filter( (Q(a__f1='foo') | Q(b__f1='foo')) & (Q(a__f1='bar') | Q(c__f1='foo')) ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) self.assertEqual(str(qs.query).count('INNER JOIN'), 0) qs = BaseA.objects.filter( (Q(a__f1='foo') | (Q(a__f1='bar')) & (Q(b__f1='bar') | Q(c__f1='foo'))) ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion_fexpression(self): qs = BaseA.objects.filter(Q(a__f1=F('b__f1')) | Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = BaseA.objects.filter(Q(a__f1=F('c__f1')) | Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) qs = BaseA.objects.filter(Q(a__f1=F('b__f1')) | Q(a__f2=F('b__f2')) | Q(c__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) qs = BaseA.objects.filter(Q(a__f1=F('c__f1')) | (Q(pk=1) & Q(pk=2))) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count('INNER JOIN'), 0) class ManyToManyExcludeTest(TestCase): def test_exclude_many_to_many(self): Identifier.objects.create(name='extra') program = Program.objects.create(identifier=Identifier.objects.create(name='program')) channel = Channel.objects.create(identifier=Identifier.objects.create(name='channel')) channel.programs.add(program) # channel contains 'program1', so all Identifiers except that one # should be returned self.assertQuerysetEqual( Identifier.objects.exclude(program__channel=channel).order_by('name'), ['<Identifier: channel>', '<Identifier: extra>'] ) self.assertQuerysetEqual( Identifier.objects.exclude(program__channel=None).order_by('name'), ['<Identifier: program>'] ) def test_ticket_12823(self): pg3 = Page.objects.create(text='pg3') pg2 = Page.objects.create(text='pg2') pg1 = Page.objects.create(text='pg1') pa1 = Paragraph.objects.create(text='pa1') pa1.page.set([pg1, pg2]) pa2 = Paragraph.objects.create(text='pa2') pa2.page.set([pg2, pg3]) pa3 = Paragraph.objects.create(text='pa3') ch1 = Chapter.objects.create(title='ch1', paragraph=pa1) ch2 = Chapter.objects.create(title='ch2', paragraph=pa2) ch3 = Chapter.objects.create(title='ch3', paragraph=pa3) b1 = Book.objects.create(title='b1', chapter=ch1) b2 = Book.objects.create(title='b2', chapter=ch2) b3 = Book.objects.create(title='b3', chapter=ch3) q = Book.objects.exclude(chapter__paragraph__page__text='pg1') self.assertNotIn('IS NOT NULL', str(q.query)) self.assertEqual(len(q), 2) self.assertNotIn(b1, q) self.assertIn(b2, q) self.assertIn(b3, q) class RelabelCloneTest(TestCase): def test_ticket_19964(self): my1 = MyObject.objects.create(data='foo') my1.parent = my1 my1.save() my2 = MyObject.objects.create(data='bar', parent=my1) parents = MyObject.objects.filter(parent=F('id')) children = MyObject.objects.filter(parent__in=parents).exclude(parent=F('id')) self.assertEqual(list(parents), [my1]) # Evaluating the children query (which has parents as part of it) does # not change results for the parents query. self.assertEqual(list(children), [my2]) self.assertEqual(list(parents), [my1]) class Ticket20101Tests(TestCase): def test_ticket_20101(self): """ Tests QuerySet ORed combining in exclude subquery case. """ t = Tag.objects.create(name='foo') a1 = Annotation.objects.create(tag=t, name='a1') a2 = Annotation.objects.create(tag=t, name='a2') a3 = Annotation.objects.create(tag=t, name='a3') n = Note.objects.create(note='foo', misc='bar') qs1 = Note.objects.exclude(annotation__in=[a1, a2]) qs2 = Note.objects.filter(annotation__in=[a3]) self.assertIn(n, qs1) self.assertNotIn(n, qs2) self.assertIn(n, (qs1 | qs2)) class EmptyStringPromotionTests(TestCase): def test_empty_string_promotion(self): qs = RelatedObject.objects.filter(single__name='') if connection.features.interprets_empty_strings_as_nulls: self.assertIn('LEFT OUTER JOIN', str(qs.query)) else: self.assertNotIn('LEFT OUTER JOIN', str(qs.query)) class ValuesSubqueryTests(TestCase): def test_values_in_subquery(self): # If a values() queryset is used, then the given values # will be used instead of forcing use of the relation's field. o1 = Order.objects.create(id=-2) o2 = Order.objects.create(id=-1) oi1 = OrderItem.objects.create(order=o1, status=0) oi1.status = oi1.pk oi1.save() OrderItem.objects.create(order=o2, status=0) # The query below should match o1 as it has related order_item # with id == status. self.assertSequenceEqual(Order.objects.filter(items__in=OrderItem.objects.values_list('status')), [o1]) class DoubleInSubqueryTests(TestCase): def test_double_subquery_in(self): lfa1 = LeafA.objects.create(data='foo') lfa2 = LeafA.objects.create(data='bar') lfb1 = LeafB.objects.create(data='lfb1') lfb2 = LeafB.objects.create(data='lfb2') Join.objects.create(a=lfa1, b=lfb1) Join.objects.create(a=lfa2, b=lfb2) leaf_as = LeafA.objects.filter(data='foo').values_list('pk', flat=True) joins = Join.objects.filter(a__in=leaf_as).values_list('b__id', flat=True) qs = LeafB.objects.filter(pk__in=joins) self.assertSequenceEqual(qs, [lfb1]) class Ticket18785Tests(TestCase): def test_ticket_18785(self): # Test join trimming from ticket18785 qs = Item.objects.exclude( note__isnull=False ).filter( name='something', creator__extra__isnull=True ).order_by() self.assertEqual(1, str(qs.query).count('INNER JOIN')) self.assertEqual(0, str(qs.query).count('OUTER JOIN')) class Ticket20788Tests(TestCase): def test_ticket_20788(self): Paragraph.objects.create() paragraph = Paragraph.objects.create() page = paragraph.page.create() chapter = Chapter.objects.create(paragraph=paragraph) Book.objects.create(chapter=chapter) paragraph2 = Paragraph.objects.create() Page.objects.create() chapter2 = Chapter.objects.create(paragraph=paragraph2) book2 = Book.objects.create(chapter=chapter2) sentences_not_in_pub = Book.objects.exclude(chapter__paragraph__page=page) self.assertSequenceEqual(sentences_not_in_pub, [book2]) class Ticket12807Tests(TestCase): def test_ticket_12807(self): p1 = Paragraph.objects.create() p2 = Paragraph.objects.create() # The ORed condition below should have no effect on the query - the # ~Q(pk__in=[]) will always be True. qs = Paragraph.objects.filter((Q(pk=p2.pk) | ~Q(pk__in=[])) & Q(pk=p1.pk)) self.assertSequenceEqual(qs, [p1]) class RelatedLookupTypeTests(TestCase): error = 'Cannot query "%s": Must be "%s" instance.' @classmethod def setUpTestData(cls): cls.oa = ObjectA.objects.create(name="oa") cls.poa = ProxyObjectA.objects.get(name="oa") cls.coa = ChildObjectA.objects.create(name="coa") cls.wrong_type = Order.objects.create(id=cls.oa.pk) cls.ob = ObjectB.objects.create(name="ob", objecta=cls.oa, num=1) ProxyObjectB.objects.create(name="pob", objecta=cls.oa, num=2) cls.pob = ProxyObjectB.objects.all() ObjectC.objects.create(childobjecta=cls.coa) def test_wrong_type_lookup(self): """ A ValueError is raised when the incorrect object type is passed to a query lookup. """ # Passing incorrect object type with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.get(objecta=self.wrong_type) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.wrong_type]) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta=self.wrong_type) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectB._meta.object_name)): ObjectA.objects.filter(objectb__in=[self.wrong_type, self.ob]) # Passing an object of the class on which query is done. with self.assertRaisesMessage(ValueError, self.error % (self.ob, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.poa, self.ob]) with self.assertRaisesMessage(ValueError, self.error % (self.ob, ChildObjectA._meta.object_name)): ObjectC.objects.exclude(childobjecta__in=[self.coa, self.ob]) def test_wrong_backward_lookup(self): """ A ValueError is raised when the incorrect object type is passed to a query lookup for backward relations. """ with self.assertRaisesMessage(ValueError, self.error % (self.oa, ObjectB._meta.object_name)): ObjectA.objects.filter(objectb__in=[self.oa, self.ob]) with self.assertRaisesMessage(ValueError, self.error % (self.oa, ObjectB._meta.object_name)): ObjectA.objects.exclude(objectb=self.oa) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectB._meta.object_name)): ObjectA.objects.get(objectb=self.wrong_type) def test_correct_lookup(self): """ When passing proxy model objects, child objects, or parent objects, lookups work fine. """ out_a = ['<ObjectA: oa>'] out_b = ['<ObjectB: ob>', '<ObjectB: pob>'] out_c = ['<ObjectC: >'] # proxy model objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta=self.poa).order_by('name'), out_b) self.assertQuerysetEqual(ObjectA.objects.filter(objectb__in=self.pob).order_by('pk'), out_a * 2) # child objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.coa]), []) self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.poa, self.coa]).order_by('name'), out_b) self.assertQuerysetEqual( ObjectB.objects.filter(objecta__in=iter([self.poa, self.coa])).order_by('name'), out_b ) # parent objects self.assertQuerysetEqual(ObjectC.objects.exclude(childobjecta=self.oa), out_c) # QuerySet related object type checking shouldn't issue queries # (the querysets aren't evaluated here, hence zero queries) (#23266). with self.assertNumQueries(0): ObjectB.objects.filter(objecta__in=ObjectA.objects.all()) def test_values_queryset_lookup(self): """ #23396 - Ensure ValueQuerySets are not checked for compatibility with the lookup field """ # Make sure the num and objecta field values match. ob = ObjectB.objects.get(name='ob') ob.num = ob.objecta.pk ob.save() pob = ObjectB.objects.get(name='pob') pob.num = pob.objecta.pk pob.save() self.assertQuerysetEqual(ObjectB.objects.filter( objecta__in=ObjectB.objects.all().values_list('num') ).order_by('pk'), ['<ObjectB: ob>', '<ObjectB: pob>']) class Ticket14056Tests(TestCase): def test_ticket_14056(self): s1 = SharedConnection.objects.create(data='s1') s2 = SharedConnection.objects.create(data='s2') s3 = SharedConnection.objects.create(data='s3') PointerA.objects.create(connection=s2) expected_ordering = ( [s1, s3, s2] if connection.features.nulls_order_largest else [s2, s1, s3] ) self.assertSequenceEqual(SharedConnection.objects.order_by('-pointera__connection', 'pk'), expected_ordering) class Ticket20955Tests(TestCase): def test_ticket_20955(self): jack = Staff.objects.create(name='jackstaff') jackstaff = StaffUser.objects.create(staff=jack) jill = Staff.objects.create(name='jillstaff') jillstaff = StaffUser.objects.create(staff=jill) task = Task.objects.create(creator=jackstaff, owner=jillstaff, title="task") task_get = Task.objects.get(pk=task.pk) # Load data so that assertNumQueries doesn't complain about the get # version's queries. task_get.creator.staffuser.staff task_get.owner.staffuser.staff qs = Task.objects.select_related( 'creator__staffuser__staff', 'owner__staffuser__staff') self.assertEqual(str(qs.query).count(' JOIN '), 6) task_select_related = qs.get(pk=task.pk) with self.assertNumQueries(0): self.assertEqual(task_select_related.creator.staffuser.staff, task_get.creator.staffuser.staff) self.assertEqual(task_select_related.owner.staffuser.staff, task_get.owner.staffuser.staff) class Ticket21203Tests(TestCase): def test_ticket_21203(self): p = Ticket21203Parent.objects.create(parent_bool=True) c = Ticket21203Child.objects.create(parent=p) qs = Ticket21203Child.objects.select_related('parent').defer('parent__created') self.assertSequenceEqual(qs, [c]) self.assertIs(qs[0].parent.parent_bool, True) class ValuesJoinPromotionTests(TestCase): def test_values_no_promotion_for_existing(self): qs = Node.objects.filter(parent__parent__isnull=False) self.assertIn(' INNER JOIN ', str(qs.query)) qs = qs.values('parent__parent__id') self.assertIn(' INNER JOIN ', str(qs.query)) # Make sure there is a left outer join without the filter. qs = Node.objects.values('parent__parent__id') self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_non_nullable_fk_not_promoted(self): qs = ObjectB.objects.values('objecta__name') self.assertIn(' INNER JOIN ', str(qs.query)) def test_ticket_21376(self): a = ObjectA.objects.create() ObjectC.objects.create(objecta=a) qs = ObjectC.objects.filter( Q(objecta=a) | Q(objectb__objecta=a), ) qs = qs.filter( Q(objectb=1) | Q(objecta=a), ) self.assertEqual(qs.count(), 1) tblname = connection.ops.quote_name(ObjectB._meta.db_table) self.assertIn(' LEFT OUTER JOIN %s' % tblname, str(qs.query)) class ForeignKeyToBaseExcludeTests(TestCase): def test_ticket_21787(self): sc1 = SpecialCategory.objects.create(special_name='sc1', name='sc1') sc2 = SpecialCategory.objects.create(special_name='sc2', name='sc2') sc3 = SpecialCategory.objects.create(special_name='sc3', name='sc3') c1 = CategoryItem.objects.create(category=sc1) CategoryItem.objects.create(category=sc2) self.assertSequenceEqual(SpecialCategory.objects.exclude(categoryitem__id=c1.pk).order_by('name'), [sc2, sc3]) self.assertSequenceEqual(SpecialCategory.objects.filter(categoryitem__id=c1.pk), [sc1]) class ReverseM2MCustomPkTests(TestCase): def test_ticket_21879(self): cpt1 = CustomPkTag.objects.create(id='cpt1', tag='cpt1') cp1 = CustomPk.objects.create(name='cp1', extra='extra') cp1.custompktag_set.add(cpt1) self.assertSequenceEqual(CustomPk.objects.filter(custompktag=cpt1), [cp1]) self.assertSequenceEqual(CustomPkTag.objects.filter(custom_pk=cp1), [cpt1]) class Ticket22429Tests(TestCase): def test_ticket_22429(self): sc1 = School.objects.create() st1 = Student.objects.create(school=sc1) sc2 = School.objects.create() st2 = Student.objects.create(school=sc2) cr = Classroom.objects.create(school=sc1) cr.students.add(st1) queryset = Student.objects.filter(~Q(classroom__school=F('school'))) self.assertSequenceEqual(queryset, [st2]) class Ticket23605Tests(TestCase): def test_ticket_23605(self): # Test filtering on a complicated q-object from ticket's report. # The query structure is such that we have multiple nested subqueries. # The original problem was that the inner queries weren't relabeled # correctly. # See also #24090. a1 = Ticket23605A.objects.create() a2 = Ticket23605A.objects.create() c1 = Ticket23605C.objects.create(field_c0=10000.0) Ticket23605B.objects.create( field_b0=10000.0, field_b1=True, modelc_fk=c1, modela_fk=a1) complex_q = Q(pk__in=Ticket23605A.objects.filter( Q( # True for a1 as field_b0 = 10000, field_c0=10000 # False for a2 as no ticket23605b found ticket23605b__field_b0__gte=1000000 / F("ticket23605b__modelc_fk__field_c0") ) & # True for a1 (field_b1=True) Q(ticket23605b__field_b1=True) & ~Q(ticket23605b__pk__in=Ticket23605B.objects.filter( ~( # Same filters as above commented filters, but # double-negated (one for Q() above, one for # parentheses). So, again a1 match, a2 not. Q(field_b1=True) & Q(field_b0__gte=1000000 / F("modelc_fk__field_c0")) ) ))).filter(ticket23605b__field_b1=True)) qs1 = Ticket23605A.objects.filter(complex_q) self.assertSequenceEqual(qs1, [a1]) qs2 = Ticket23605A.objects.exclude(complex_q) self.assertSequenceEqual(qs2, [a2]) class TestTicket24279(TestCase): def test_ticket_24278(self): School.objects.create() qs = School.objects.filter(Q(pk__in=()) | Q()) self.assertQuerysetEqual(qs, []) class TestInvalidValuesRelation(TestCase): def test_invalid_values(self): msg = "invalid literal for int() with base 10: 'abc'" with self.assertRaisesMessage(ValueError, msg): Annotation.objects.filter(tag='abc') with self.assertRaisesMessage(ValueError, msg): Annotation.objects.filter(tag__in=[123, 'abc']) class TestTicket24605(TestCase): def test_ticket_24605(self): """ Subquery table names should be quoted. """ i1 = Individual.objects.create(alive=True) RelatedIndividual.objects.create(related=i1) i2 = Individual.objects.create(alive=False) RelatedIndividual.objects.create(related=i2) i3 = Individual.objects.create(alive=True) i4 = Individual.objects.create(alive=False) self.assertSequenceEqual(Individual.objects.filter(Q(alive=False), Q(related_individual__isnull=True)), [i4]) self.assertSequenceEqual( Individual.objects.exclude(Q(alive=False), Q(related_individual__isnull=True)).order_by('pk'), [i1, i2, i3] ) class Ticket23622Tests(TestCase): @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_23622(self): """ Make sure __pk__in and __in work the same for related fields when using a distinct on subquery. """ a1 = Ticket23605A.objects.create() a2 = Ticket23605A.objects.create() c1 = Ticket23605C.objects.create(field_c0=0.0) Ticket23605B.objects.create( modela_fk=a1, field_b0=123, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=23, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=234, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=12, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=567, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=76, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=7, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=56, field_b1=True, modelc_fk=c1, ) qx = ( Q(ticket23605b__pk__in=Ticket23605B.objects.order_by('modela_fk', '-field_b1').distinct('modela_fk')) & Q(ticket23605b__field_b0__gte=300) ) qy = ( Q(ticket23605b__in=Ticket23605B.objects.order_by('modela_fk', '-field_b1').distinct('modela_fk')) & Q(ticket23605b__field_b0__gte=300) ) self.assertEqual( set(Ticket23605A.objects.filter(qx).values_list('pk', flat=True)), set(Ticket23605A.objects.filter(qy).values_list('pk', flat=True)) ) self.assertSequenceEqual(Ticket23605A.objects.filter(qx), [a2])
f1f22ac914881805a5d3b9d49d055df0c205418e38ea5875c84bf6d7e8695f84
""" Various complex queries that have been problematic in the past. """ import threading from django.db import models class DumbCategory(models.Model): pass class ProxyCategory(DumbCategory): class Meta: proxy = True class NamedCategory(DumbCategory): name = models.CharField(max_length=10) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey( 'self', models.SET_NULL, blank=True, null=True, related_name='children', ) category = models.ForeignKey(NamedCategory, models.SET_NULL, null=True, default=None) class Meta: ordering = ['name'] def __str__(self): return self.name class Note(models.Model): note = models.CharField(max_length=100) misc = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True) class Meta: ordering = ['note'] def __str__(self): return self.note def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Regression for #13227 -- having an attribute that # is unpicklable doesn't stop you from cloning queries # that use objects of that type as an argument. self.lock = threading.Lock() class Annotation(models.Model): name = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) notes = models.ManyToManyField(Note) def __str__(self): return self.name class ExtraInfo(models.Model): info = models.CharField(max_length=100) note = models.ForeignKey(Note, models.CASCADE, null=True) value = models.IntegerField(null=True) class Meta: ordering = ['info'] def __str__(self): return self.info class Author(models.Model): name = models.CharField(max_length=10) num = models.IntegerField(unique=True) extra = models.ForeignKey(ExtraInfo, models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=10) created = models.DateTimeField() modified = models.DateTimeField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) creator = models.ForeignKey(Author, models.CASCADE) note = models.ForeignKey(Note, models.CASCADE) class Meta: ordering = ['-note', 'name'] def __str__(self): return self.name class Report(models.Model): name = models.CharField(max_length=10) creator = models.ForeignKey(Author, models.SET_NULL, to_field='num', null=True) def __str__(self): return self.name class ReportComment(models.Model): report = models.ForeignKey(Report, models.CASCADE) class Ranking(models.Model): rank = models.IntegerField() author = models.ForeignKey(Author, models.CASCADE) class Meta: # A complex ordering specification. Should stress the system a bit. ordering = ('author__extra__note', 'author__name', 'rank') def __str__(self): return '%d: %s' % (self.rank, self.author.name) class Cover(models.Model): title = models.CharField(max_length=50) item = models.ForeignKey(Item, models.CASCADE) class Meta: ordering = ['item'] def __str__(self): return self.title class Number(models.Model): num = models.IntegerField() def __str__(self): return str(self.num) # Symmetrical m2m field with a normal field using the reverse accessor name # ("valid"). class Valid(models.Model): valid = models.CharField(max_length=10) parent = models.ManyToManyField('self') class Meta: ordering = ['valid'] # Some funky cross-linked models for testing a couple of infinite recursion # cases. class X(models.Model): y = models.ForeignKey('Y', models.CASCADE) class Y(models.Model): x1 = models.ForeignKey(X, models.CASCADE, related_name='y1') # Some models with a cycle in the default ordering. This would be bad if we # didn't catch the infinite loop. class LoopX(models.Model): y = models.ForeignKey('LoopY', models.CASCADE) class Meta: ordering = ['y'] class LoopY(models.Model): x = models.ForeignKey(LoopX, models.CASCADE) class Meta: ordering = ['x'] class LoopZ(models.Model): z = models.ForeignKey('self', models.CASCADE) class Meta: ordering = ['z'] # A model and custom default manager combination. class CustomManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(public=True, tag__name='t1') class ManagedModel(models.Model): data = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) public = models.BooleanField(default=True) objects = CustomManager() normal_manager = models.Manager() def __str__(self): return self.data # An inter-related setup with multiple paths from Child to Detail. class Detail(models.Model): data = models.CharField(max_length=10) class MemberManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related("details") class Member(models.Model): name = models.CharField(max_length=10) details = models.OneToOneField(Detail, models.CASCADE, primary_key=True) objects = MemberManager() class Child(models.Model): person = models.OneToOneField(Member, models.CASCADE, primary_key=True) parent = models.ForeignKey(Member, models.CASCADE, related_name="children") # Custom primary keys interfered with ordering in the past. class CustomPk(models.Model): name = models.CharField(max_length=10, primary_key=True) extra = models.CharField(max_length=10) class Meta: ordering = ['name', 'extra'] class Related(models.Model): custom = models.ForeignKey(CustomPk, models.CASCADE, null=True) class CustomPkTag(models.Model): id = models.CharField(max_length=20, primary_key=True) custom_pk = models.ManyToManyField(CustomPk) tag = models.CharField(max_length=20) # An inter-related setup with a model subclass that has a nullable # path to another model, and a return path from that model. class Celebrity(models.Model): name = models.CharField("Name", max_length=20) greatest_fan = models.ForeignKey("Fan", models.SET_NULL, null=True, unique=True) def __str__(self): return self.name class TvChef(Celebrity): pass class Fan(models.Model): fan_of = models.ForeignKey(Celebrity, models.CASCADE) # Multiple foreign keys class LeafA(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class LeafB(models.Model): data = models.CharField(max_length=10) class Join(models.Model): a = models.ForeignKey(LeafA, models.CASCADE) b = models.ForeignKey(LeafB, models.CASCADE) class ReservedName(models.Model): name = models.CharField(max_length=20) order = models.IntegerField() def __str__(self): return self.name # A simpler shared-foreign-key setup that can expose some problems. class SharedConnection(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class PointerA(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) class PointerB(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) # Multi-layer ordering class SingleObject(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ['name'] def __str__(self): return self.name class RelatedObject(models.Model): single = models.ForeignKey(SingleObject, models.SET_NULL, null=True) f = models.IntegerField(null=True) class Meta: ordering = ['single'] class Plaything(models.Model): name = models.CharField(max_length=10) others = models.ForeignKey(RelatedObject, models.SET_NULL, null=True) class Meta: ordering = ['others'] def __str__(self): return self.name class Article(models.Model): name = models.CharField(max_length=20) created = models.DateTimeField() def __str__(self): return self.name class Food(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class Eaten(models.Model): food = models.ForeignKey(Food, models.SET_NULL, to_field="name", null=True) meal = models.CharField(max_length=20) def __str__(self): return "%s at %s" % (self.food, self.meal) class Node(models.Model): num = models.IntegerField(unique=True) parent = models.ForeignKey("self", models.SET_NULL, to_field="num", null=True) def __str__(self): return "%s" % self.num # Bug #12252 class ObjectA(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name def __iter__(self): # Ticket #23721 assert False, 'type checking should happen without calling model __iter__' class ProxyObjectA(ObjectA): class Meta: proxy = True class ChildObjectA(ObjectA): pass class ObjectB(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.CASCADE) num = models.PositiveSmallIntegerField() def __str__(self): return self.name class ProxyObjectB(ObjectB): class Meta: proxy = True class ObjectC(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.SET_NULL, null=True) objectb = models.ForeignKey(ObjectB, models.SET_NULL, null=True) childobjecta = models.ForeignKey(ChildObjectA, models.SET_NULL, null=True, related_name='ca_pk') def __str__(self): return self.name class SimpleCategory(models.Model): name = models.CharField(max_length=15) def __str__(self): return self.name class SpecialCategory(SimpleCategory): special_name = models.CharField(max_length=15) def __str__(self): return self.name + " " + self.special_name class CategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE) def __str__(self): return "category item: " + str(self.category) class MixedCaseFieldCategoryItem(models.Model): CaTeGoRy = models.ForeignKey(SimpleCategory, models.CASCADE) class MixedCaseDbColumnCategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE, db_column='CaTeGoRy_Id') class OneToOneCategory(models.Model): new_name = models.CharField(max_length=15) category = models.OneToOneField(SimpleCategory, models.CASCADE) def __str__(self): return "one2one " + self.new_name class CategoryRelationship(models.Model): first = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='first_rel') second = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='second_rel') class CommonMixedCaseForeignKeys(models.Model): category = models.ForeignKey(CategoryItem, models.CASCADE) mixed_case_field_category = models.ForeignKey(MixedCaseFieldCategoryItem, models.CASCADE) mixed_case_db_column_category = models.ForeignKey(MixedCaseDbColumnCategoryItem, models.CASCADE) class NullableName(models.Model): name = models.CharField(max_length=20, null=True) class Meta: ordering = ['id'] class ModelD(models.Model): name = models.TextField() class ModelC(models.Model): name = models.TextField() class ModelB(models.Model): name = models.TextField() c = models.ForeignKey(ModelC, models.CASCADE) class ModelA(models.Model): name = models.TextField() b = models.ForeignKey(ModelB, models.SET_NULL, null=True) d = models.ForeignKey(ModelD, models.CASCADE) class Job(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class JobResponsibilities(models.Model): job = models.ForeignKey(Job, models.CASCADE, to_field='name') responsibility = models.ForeignKey('Responsibility', models.CASCADE, to_field='description') class Responsibility(models.Model): description = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField(Job, through=JobResponsibilities, related_name='responsibilities') def __str__(self): return self.description # Models for disjunction join promotion low level testing. class FK1(models.Model): f1 = models.TextField() f2 = models.TextField() class FK2(models.Model): f1 = models.TextField() f2 = models.TextField() class FK3(models.Model): f1 = models.TextField() f2 = models.TextField() class BaseA(models.Model): a = models.ForeignKey(FK1, models.SET_NULL, null=True) b = models.ForeignKey(FK2, models.SET_NULL, null=True) c = models.ForeignKey(FK3, models.SET_NULL, null=True) class Identifier(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Program(models.Model): identifier = models.OneToOneField(Identifier, models.CASCADE) class Channel(models.Model): programs = models.ManyToManyField(Program) identifier = models.OneToOneField(Identifier, models.CASCADE) class Book(models.Model): title = models.TextField() chapter = models.ForeignKey('Chapter', models.CASCADE) class Chapter(models.Model): title = models.TextField() paragraph = models.ForeignKey('Paragraph', models.CASCADE) class Paragraph(models.Model): text = models.TextField() page = models.ManyToManyField('Page') class Page(models.Model): text = models.TextField() class MyObject(models.Model): parent = models.ForeignKey('self', models.SET_NULL, null=True, blank=True, related_name='children') data = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) # Models for #17600 regressions class Order(models.Model): id = models.IntegerField(primary_key=True) class Meta: ordering = ('pk',) def __str__(self): return '%s' % self.pk class OrderItem(models.Model): order = models.ForeignKey(Order, models.CASCADE, related_name='items') status = models.IntegerField() class Meta: ordering = ('pk',) def __str__(self): return '%s' % self.pk class BaseUser(models.Model): pass class Task(models.Model): title = models.CharField(max_length=10) owner = models.ForeignKey(BaseUser, models.CASCADE, related_name='owner') creator = models.ForeignKey(BaseUser, models.CASCADE, related_name='creator') def __str__(self): return self.title class Staff(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class StaffUser(BaseUser): staff = models.OneToOneField(Staff, models.CASCADE, related_name='user') def __str__(self): return self.staff class Ticket21203Parent(models.Model): parentid = models.AutoField(primary_key=True) parent_bool = models.BooleanField(default=True) created = models.DateTimeField(auto_now=True) class Ticket21203Child(models.Model): childid = models.AutoField(primary_key=True) parent = models.ForeignKey(Ticket21203Parent, models.CASCADE) class Person(models.Model): name = models.CharField(max_length=128) class Company(models.Model): name = models.CharField(max_length=128) employees = models.ManyToManyField(Person, related_name='employers', through='Employment') def __str__(self): return self.name class Employment(models.Model): employer = models.ForeignKey(Company, models.CASCADE) employee = models.ForeignKey(Person, models.CASCADE) title = models.CharField(max_length=128) class School(models.Model): pass class Student(models.Model): school = models.ForeignKey(School, models.CASCADE) class Classroom(models.Model): name = models.CharField(max_length=20) has_blackboard = models.BooleanField(null=True) school = models.ForeignKey(School, models.CASCADE) students = models.ManyToManyField(Student, related_name='classroom') class Teacher(models.Model): schools = models.ManyToManyField(School) friends = models.ManyToManyField('self') class Ticket23605AParent(models.Model): pass class Ticket23605A(Ticket23605AParent): pass class Ticket23605B(models.Model): modela_fk = models.ForeignKey(Ticket23605A, models.CASCADE) modelc_fk = models.ForeignKey("Ticket23605C", models.CASCADE) field_b0 = models.IntegerField(null=True) field_b1 = models.BooleanField(default=False) class Ticket23605C(models.Model): field_c0 = models.FloatField() # db_table names have capital letters to ensure they are quoted in queries. class Individual(models.Model): alive = models.BooleanField() class Meta: db_table = 'Individual' class RelatedIndividual(models.Model): related = models.ForeignKey(Individual, models.CASCADE, related_name='related_individual') class Meta: db_table = 'RelatedIndividual'
e2c1f20631d2c4439ab1c0c70dce17ec447d6704ab923aeef14536d929822bac
from django.db.models import Exists, F, IntegerField, OuterRef, Value from django.db.utils import DatabaseError, NotSupportedError from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import Number, ReservedName @skipUnlessDBFeature('supports_select_union') class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i) for i in range(10)) def number_transform(self, value): return value.num def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerysetEqual(queryset, expected_numbers, self.number_transform, ordered) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.intersection(qs1).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.intersection(qs1).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) @skipUnlessDBFeature('supports_select_difference') def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.intersection(qs2)), 0) self.assertEqual(len(qs1.intersection(qs3)), 0) self.assertEqual(len(qs2.intersection(qs1)), 0) self.assertEqual(len(qs3.intersection(qs1)), 0) self.assertEqual(len(qs2.intersection(qs2)), 0) self.assertEqual(len(qs3.intersection(qs3)), 0) @skipUnlessDBFeature('supports_select_difference') def test_difference_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.difference(qs2)), 10) self.assertEqual(len(qs1.difference(qs3)), 10) self.assertEqual(len(qs2.difference(qs1)), 0) self.assertEqual(len(qs3.difference(qs1)), 0) self.assertEqual(len(qs2.difference(qs2)), 0) self.assertEqual(len(qs3.difference(qs3)), 0) @skipUnlessDBFeature('supports_select_difference') def test_difference_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() qs2 = ReservedName.objects.none() reserved_name = qs1.difference(qs2).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.difference(qs2).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) def test_union_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.union(qs2)), 10) self.assertEqual(len(qs2.union(qs1)), 10) self.assertEqual(len(qs1.union(qs3)), 10) self.assertEqual(len(qs3.union(qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, all=True)), 20) self.assertEqual(len(qs2.union(qs2)), 0) self.assertEqual(len(qs3.union(qs3)), 0) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by('-num'), [3, 2, 1, 0]) def test_union_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.union(qs1).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.union(qs1).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) def test_union_with_two_annotated_values_list(self): qs1 = Number.objects.filter(num=1).annotate( count=Value(0, IntegerField()), ).values_list('num', 'count') qs2 = Number.objects.filter(num=2).values('pk').annotate( count=F('num'), ).annotate( num=Value(1, IntegerField()), ).values_list('num', 'count') self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_values_list_on_annotated_and_unannotated(self): ReservedName.objects.create(name='rn1', order=1) qs1 = Number.objects.annotate( has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef('num'))) ).filter(has_reserved_name=True) qs2 = Number.objects.filter(num=9) self.assertCountEqual(qs1.union(qs2).values_list('num', flat=True), [1, 9]) def test_count_union(self): qs1 = Number.objects.filter(num__lte=1).values('num') qs2 = Number.objects.filter(num__gte=2, num__lte=3).values('num') self.assertEqual(qs1.union(qs2).count(), 4) def test_count_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertEqual(qs.union(qs).count(), 0) @skipUnlessDBFeature('supports_select_difference') def test_count_difference(self): qs1 = Number.objects.filter(num__lt=10) qs2 = Number.objects.filter(num__lt=9) self.assertEqual(qs1.difference(qs2).count(), 1) @skipUnlessDBFeature('supports_select_intersection') def test_count_intersection(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) self.assertEqual(qs1.intersection(qs2).count(), 1) @skipUnlessDBFeature('supports_slicing_ordering_in_compound') def test_ordering_subqueries(self): qs1 = Number.objects.order_by('num')[:2] qs2 = Number.objects.order_by('-num')[:2] self.assertNumbersEqual(qs1.union(qs2).order_by('-num')[:4], [9, 8, 1, 0]) @skipIfDBFeature('supports_slicing_ordering_in_compound') def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'LIMIT/OFFSET not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = 'ORDER BY not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by('id').union(qs2)) @skipIfDBFeature('supports_select_intersection') def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'intersection is not supported on this database backend' with self.assertRaisesMessage(NotSupportedError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name='99 little bugs', order=99) qs1 = Number.objects.filter(num=1).values_list('num', flat=True) qs2 = ReservedName.objects.values_list('order') self.assertEqual(list(qs1.union(qs2).order_by('num')), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = Number.objects.filter().annotate( annotation=Value(1, IntegerField()), ).values('annotation', num2=F('num')) qs2 = Number.objects.filter().values('id', 'num') # Should not raise list(qs1.union(qs2).order_by('annotation')) list(qs1.union(qs2).order_by('num2')) msg = 'ORDER BY term does not match any column in the result set' # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('id')) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('num')) # switched order, now 'exists' again: list(qs2.union(qs1).order_by('num'))
4c476e24be6eef81defbc7e5af751fc1e866b21a472ec3f0179dda3e8635bff7
import unittest from django.db import NotSupportedError, connection, transaction from django.db.models import Count from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import Tag @skipUnlessDBFeature('supports_explaining_query_execution') class ExplainTests(TestCase): def test_basic(self): querysets = [ Tag.objects.filter(name='test'), Tag.objects.filter(name='test').select_related('parent'), Tag.objects.filter(name='test').prefetch_related('children'), Tag.objects.filter(name='test').annotate(Count('children')), Tag.objects.filter(name='test').values_list('name'), Tag.objects.order_by().union(Tag.objects.order_by().filter(name='test')), Tag.objects.all().select_for_update().filter(name='test'), ] supported_formats = connection.features.supported_explain_formats all_formats = (None,) + tuple(supported_formats) + tuple(f.lower() for f in supported_formats) for idx, queryset in enumerate(querysets): for format in all_formats: with self.subTest(format=format, queryset=idx): if connection.vendor == 'mysql': # This does a query and caches the result. connection.features.needs_explain_extended with self.assertNumQueries(1), CaptureQueriesContext(connection) as captured_queries: result = queryset.explain(format=format) self.assertTrue(captured_queries[0]['sql'].startswith(connection.ops.explain_prefix)) self.assertIsInstance(result, str) self.assertTrue(result) @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = 'DOES NOT EXIST is not a recognized format.' if connection.features.supported_explain_formats: msg += ' Allowed formats: %s' % ', '.join(sorted(connection.features.supported_explain_formats)) with self.assertRaisesMessage(ValueError, msg): Tag.objects.all().explain(format='does not exist') @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific') def test_postgres_options(self): qs = Tag.objects.filter(name='test') test_options = [ {'COSTS': False, 'BUFFERS': True, 'ANALYZE': True}, {'costs': False, 'buffers': True, 'analyze': True}, {'verbose': True, 'timing': True, 'analyze': True}, {'verbose': False, 'timing': False, 'analyze': True}, ] if connection.pg_version >= 100000: test_options.append({'summary': True}) for options in test_options: with self.subTest(**options), transaction.atomic(): with CaptureQueriesContext(connection) as captured_queries: qs.explain(format='text', **options) self.assertEqual(len(captured_queries), 1) for name, value in options.items(): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific') def test_mysql_text_to_traditional(self): # Initialize the cached property, if needed, to prevent a query for # the MySQL version during the QuerySet evaluation. connection.features.needs_explain_extended with CaptureQueriesContext(connection) as captured_queries: Tag.objects.filter(name='test').explain(format='text') self.assertEqual(len(captured_queries), 1) self.assertIn('FORMAT=TRADITIONAL', captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL < 5.7 specific') def test_mysql_extended(self): # Inner skip to avoid module level query for MySQL version. if not connection.features.needs_explain_extended: raise unittest.SkipTest('MySQL < 5.7 specific') qs = Tag.objects.filter(name='test') with CaptureQueriesContext(connection) as captured_queries: qs.explain(format='json') self.assertEqual(len(captured_queries), 1) self.assertNotIn('EXTENDED', captured_queries[0]['sql']) with CaptureQueriesContext(connection) as captured_queries: qs.explain(format='text') self.assertEqual(len(captured_queries), 1) self.assertNotIn('EXTENDED', captured_queries[0]['sql']) @skipIfDBFeature('supports_explaining_query_execution') class ExplainUnsupportedTests(TestCase): def test_message(self): msg = 'This backend does not support explaining query execution.' with self.assertRaisesMessage(NotSupportedError, msg): Tag.objects.filter(name='test').explain()
fe59f38380f4bcf6249ed6c438c4f1cc1f334964c2780749cbb61d46f3b9a30f
""" Testing some internals of the template processing. These are *not* examples to be copied in user code. """ from django.template import Library, TemplateSyntaxError from django.template.base import ( FilterExpression, Parser, Token, TokenType, Variable, ) from django.template.defaultfilters import register as filter_library from django.test import SimpleTestCase class ParserTests(SimpleTestCase): def test_token_smart_split(self): """ #7027 -- _() syntax should work with spaces """ token = Token(TokenType.BLOCK, 'sometag _("Page not found") value|yesno:_("yes,no")') split = token.split_contents() self.assertEqual(split, ["sometag", '_("Page not found")', 'value|yesno:_("yes,no")']) def test_filter_parsing(self): c = {"article": {"section": "News"}} p = Parser("", builtins=[filter_library]) def fe_test(s, val): self.assertEqual(FilterExpression(s, p).resolve(c), val) fe_test("article.section", "News") fe_test("article.section|upper", "NEWS") fe_test('"News"', "News") fe_test("'News'", "News") fe_test(r'"Some \"Good\" News"', 'Some "Good" News') fe_test(r'"Some \"Good\" News"', 'Some "Good" News') fe_test(r"'Some \'Bad\' News'", "Some 'Bad' News") fe = FilterExpression(r'"Some \"Good\" News"', p) self.assertEqual(fe.filters, []) self.assertEqual(fe.var, 'Some "Good" News') # Filtered variables should reject access of attributes beginning with # underscores. msg = "Variables and attributes may not begin with underscores: 'article._hidden'" with self.assertRaisesMessage(TemplateSyntaxError, msg): FilterExpression("article._hidden|upper", p) def test_variable_parsing(self): c = {"article": {"section": "News"}} self.assertEqual(Variable("article.section").resolve(c), "News") self.assertEqual(Variable('"News"').resolve(c), "News") self.assertEqual(Variable("'News'").resolve(c), "News") # Translated strings are handled correctly. self.assertEqual(Variable("_(article.section)").resolve(c), "News") self.assertEqual(Variable('_("Good News")').resolve(c), "Good News") self.assertEqual(Variable("_('Better News')").resolve(c), "Better News") # Escaped quotes work correctly as well. self.assertEqual( Variable(r'"Some \"Good\" News"').resolve(c), 'Some "Good" News' ) self.assertEqual( Variable(r"'Some \'Better\' News'").resolve(c), "Some 'Better' News" ) # Variables should reject access of attributes beginning with # underscores. msg = "Variables and attributes may not begin with underscores: 'article._hidden'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Variable("article._hidden") # Variables should raise on non string type with self.assertRaisesMessage(TypeError, "Variable must be a string or number, got <class 'dict'>"): Variable({}) def test_filter_args_count(self): parser = Parser("") register = Library() @register.filter def no_arguments(value): pass @register.filter def one_argument(value, arg): pass @register.filter def one_opt_argument(value, arg=False): pass @register.filter def two_arguments(value, arg, arg2): pass @register.filter def two_one_opt_arg(value, arg, arg2=False): pass parser.add_library(register) for expr in ( '1|no_arguments:"1"', '1|two_arguments', '1|two_arguments:"1"', '1|two_one_opt_arg', ): with self.assertRaises(TemplateSyntaxError): FilterExpression(expr, parser) for expr in ( # Correct number of arguments '1|no_arguments', '1|one_argument:"1"', # One optional '1|one_opt_argument', '1|one_opt_argument:"1"', # Not supplying all '1|two_one_opt_arg:"1"', ): FilterExpression(expr, parser)
5fb98c2e6f4fa23df85823701f34cea0dbac7a47ae66fb00d3fa26f6bb081f47
from django.http import HttpRequest from django.template import ( Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist, ) from django.template.context import RenderContext from django.test import RequestFactory, SimpleTestCase class ContextTests(SimpleTestCase): def test_context(self): c = Context({"a": 1, "b": "xyzzy"}) self.assertEqual(c["a"], 1) self.assertEqual(c.push(), {}) c["a"] = 2 self.assertEqual(c["a"], 2) self.assertEqual(c.get("a"), 2) self.assertEqual(c.pop(), {"a": 2}) self.assertEqual(c["a"], 1) self.assertEqual(c.get("foo", 42), 42) def test_push_context_manager(self): c = Context({"a": 1}) with c.push(): c['a'] = 2 self.assertEqual(c['a'], 2) self.assertEqual(c['a'], 1) with c.push(a=3): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_update_context_manager(self): c = Context({"a": 1}) with c.update({}): c['a'] = 2 self.assertEqual(c['a'], 2) self.assertEqual(c['a'], 1) with c.update({'a': 3}): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_push_context_manager_with_context_object(self): c = Context({'a': 1}) with c.push(Context({'a': 3})): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_update_context_manager_with_context_object(self): c = Context({'a': 1}) with c.update(Context({'a': 3})): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_push_proper_layering(self): c = Context({'a': 1}) c.push(Context({'b': 2})) c.push(Context({'c': 3, 'd': {'z': '26'}})) self.assertEqual( c.dicts, [ {'False': False, 'None': None, 'True': True}, {'a': 1}, {'b': 2}, {'c': 3, 'd': {'z': '26'}}, ] ) def test_update_proper_layering(self): c = Context({'a': 1}) c.update(Context({'b': 2})) c.update(Context({'c': 3, 'd': {'z': '26'}})) self.assertEqual( c.dicts, [ {'False': False, 'None': None, 'True': True}, {'a': 1}, {'b': 2}, {'c': 3, 'd': {'z': '26'}}, ] ) def test_setdefault(self): c = Context() x = c.setdefault('x', 42) self.assertEqual(x, 42) self.assertEqual(c['x'], 42) x = c.setdefault('x', 100) self.assertEqual(x, 42) self.assertEqual(c['x'], 42) def test_resolve_on_context_method(self): """ #17778 -- Variable shouldn't resolve RequestContext methods """ empty_context = Context() with self.assertRaises(VariableDoesNotExist): Variable('no_such_variable').resolve(empty_context) with self.assertRaises(VariableDoesNotExist): Variable('new').resolve(empty_context) self.assertEqual( Variable('new').resolve(Context({'new': 'foo'})), 'foo', ) def test_render_context(self): test_context = RenderContext({'fruit': 'papaya'}) # push() limits access to the topmost dict test_context.push() test_context['vegetable'] = 'artichoke' self.assertEqual(list(test_context), ['vegetable']) self.assertNotIn('fruit', test_context) with self.assertRaises(KeyError): test_context['fruit'] self.assertIsNone(test_context.get('fruit')) def test_flatten_context(self): a = Context() a.update({'a': 2}) a.update({'b': 4}) a.update({'c': 8}) self.assertEqual(a.flatten(), { 'False': False, 'None': None, 'True': True, 'a': 2, 'b': 4, 'c': 8 }) def test_flatten_context_with_context(self): """ Context.push() with a Context argument should work. """ a = Context({'a': 2}) a.push(Context({'z': '8'})) self.assertEqual(a.flatten(), { 'False': False, 'None': None, 'True': True, 'a': 2, 'z': '8', }) def test_context_comparable(self): """ #21765 -- equality comparison should work """ test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} self.assertEqual(Context(test_data), Context(test_data)) a = Context() b = Context() self.assertEqual(a, b) # update only a a.update({'a': 1}) self.assertNotEqual(a, b) # update both to check regression a.update({'c': 3}) b.update({'c': 3}) self.assertNotEqual(a, b) # make contexts equals again b.update({'a': 1}) self.assertEqual(a, b) def test_copy_request_context_twice(self): """ #24273 -- Copy twice shouldn't raise an exception """ RequestContext(HttpRequest()).new().new() def test_set_upward(self): c = Context({'a': 1}) c.set_upward('a', 2) self.assertEqual(c.get('a'), 2) def test_set_upward_empty_context(self): empty_context = Context() empty_context.set_upward('a', 1) self.assertEqual(empty_context.get('a'), 1) def test_set_upward_with_push(self): """ The highest context which has the given key is used. """ c = Context({'a': 1}) c.push({'a': 2}) c.set_upward('a', 3) self.assertEqual(c.get('a'), 3) c.pop() self.assertEqual(c.get('a'), 1) def test_set_upward_with_push_no_match(self): """ The highest context is used if the given key isn't found. """ c = Context({'b': 1}) c.push({'b': 2}) c.set_upward('a', 2) self.assertEqual(len(c.dicts), 3) self.assertEqual(c.dicts[-1]['a'], 2) class RequestContextTests(SimpleTestCase): def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'child': '{{ var|default:"none" }}', }), ]) request = RequestFactory().get('/') ctx = RequestContext(request, {'var': 'parent'}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none') def test_stack_size(self): """ #7116 -- Optimize RequetsContext construction """ request = RequestFactory().get('/') ctx = RequestContext(request, {}) # The stack should now contain 3 items: # [builtins, supplied context, context processor, empty dict] self.assertEqual(len(ctx.dicts), 4) def test_context_comparable(self): # Create an engine without any context processors. test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future request = RequestFactory().get('/') self.assertEqual( RequestContext(request, dict_=test_data), RequestContext(request, dict_=test_data), ) def test_modify_context_and_render(self): template = Template('{{ foo }}') request = RequestFactory().get('/') context = RequestContext(request, {}) context['foo'] = 'foo' self.assertEqual(template.render(context), 'foo')
e1b8c9197a50fd1de4a92613304a653cc411ab172a2d8a27e55bf8fd4353fb32
from django import Xtemplate # NOQA
1af284532e01a141a5f7e40ab602df832dc1d0c7f4f3d72542bf043acbb10cb2
import sys from django.contrib.auth.models import Group from django.template import Context, Engine, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings from django.urls import NoReverseMatch from django.utils import translation class TemplateTests(SimpleTestCase): def test_string_origin(self): template = Engine().from_string('string template') self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertIsNone(template.origin.loader_name) self.assertEqual(template.source, 'string template') @override_settings(SETTINGS_MODULE=None) def test_url_reverse_no_settings_module(self): """ #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to be set. """ t = Engine(debug=True).from_string('{% url will_not_match %}') c = Context() with self.assertRaises(NoReverseMatch): t.render(c) def test_url_reverse_view_name(self): """ #19827 -- url tag should keep original strack trace when reraising exception. """ t = Engine().from_string('{% url will_not_match %}') c = Context() try: t.render(c) except NoReverseMatch: tb = sys.exc_info()[2] depth = 0 while tb.tb_next is not None: tb = tb.tb_next depth += 1 self.assertGreater(depth, 5, "The traceback context was lost when reraising the traceback.") def test_no_wrapped_exception(self): """ # 16770 -- The template system doesn't wrap exceptions, but annotates them. """ engine = Engine(debug=True) c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) debug = e.exception.template_debug self.assertEqual(debug['start'], 0) self.assertEqual(debug['end'], 14) def test_invalid_block_suggestion(self): """ Error messages should include the unexpected block name and be in all English. """ engine = Engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) with self.settings(USE_I18N=True), translation.override('de'): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") def test_unknown_block_tag(self): engine = Engine() msg = ( "Invalid block tag on line 1: 'foobar'. Did you forget to " "register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("lala{% foobar %}") def test_compile_filter_expression_error(self): """ 19819 -- Make sure the correct token is highlighted for FilterExpression errors. """ engine = Engine(debug=True) msg = "Could not parse the remainder: '@bar' from 'foo@bar'" with self.assertRaisesMessage(TemplateSyntaxError, msg) as e: engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}") debug = e.exception.template_debug self.assertEqual((debug['start'], debug['end']), (10, 23)) self.assertEqual((debug['during']), '{{ foo@bar }}') def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = Engine( debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') def test_compile_tag_error_27584(self): engine = Engine( app_dirs=True, debug=True, libraries={'tag_27584': 'template_tests.templatetags.tag_27584'}, ) t = engine.get_template('27584_parent.html') with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') def test_compile_tag_error_27956(self): """Errors in a child of {% extends %} are displayed correctly.""" engine = Engine( app_dirs=True, debug=True, libraries={'tag_27584': 'template_tests.templatetags.tag_27584'}, ) t = engine.get_template('27956_child.html') with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') def test_super_errors(self): """ #18169 -- NoReverseMatch should not be silence in block.super. """ engine = Engine(app_dirs=True) t = engine.get_template('included_content.html') with self.assertRaises(NoReverseMatch): t.render(Context()) def test_debug_tag_non_ascii(self): """ #23060 -- Test non-ASCII model representation in debug output. """ group = Group(name="清風") c1 = Context({"objs": [group]}) t1 = Engine().from_string('{% debug %}') self.assertIn("清風", t1.render(c1)) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = Engine() parent = engine.from_string('{% block content %}parent{% endblock %}') child = engine.from_string( '{% extends parent %}{% block content %}child{% endblock %}') self.assertEqual(child.render(Context({'parent': parent})), 'child') def test_node_origin(self): """ #25848 -- Set origin on Node so debugging tools can determine which template the node came from even if extending or including templates. """ template = Engine().from_string('content') for node in template.nodelist: self.assertEqual(node.origin, template.origin)
a8c9e834ab328567e2565b178f0414f8c0f48640cd8b7bf9dca5f0034963edcd
import logging from django.template import Engine, Variable, VariableDoesNotExist from django.test import SimpleTestCase class VariableResolveLoggingTests(SimpleTestCase): loglevel = logging.DEBUG def test_log_on_variable_does_not_exist_silent(self): class TestObject: class SilentDoesNotExist(Exception): silent_variable_failure = True @property def template_name(self): return "template_name" @property def template(self): return Engine().from_string('') @property def article(self): raise TestObject.SilentDoesNotExist("Attribute does not exist.") def __iter__(self): return iter(attr for attr in dir(TestObject) if attr[:2] != "__") def __getitem__(self, item): return self.__dict__[item] with self.assertLogs('django.template', self.loglevel) as cm: Variable('article').resolve(TestObject()) self.assertEqual(len(cm.records), 1) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Exception while resolving variable 'article' in template 'template_name'." ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertEqual(str(raised_exception), 'Attribute does not exist.') def test_log_on_variable_does_not_exist_not_silent(self): with self.assertLogs('django.template', self.loglevel) as cm: with self.assertRaises(VariableDoesNotExist): Variable('article.author').resolve({'article': {'section': 'News'}}) self.assertEqual(len(cm.records), 1) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Exception while resolving variable 'author' in template 'unknown'." ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertEqual( str(raised_exception), "Failed lookup for key [author] in {'section': 'News'}" ) def test_no_log_when_variable_exists(self): with self.assertRaisesMessage(AssertionError, 'no logs'): with self.assertLogs('django.template', self.loglevel): Variable('article.section').resolve({'article': {'section': 'News'}})
3178e27b8edb49b23b2bb75103da6258861ca4c5e1773bec2217f762db2309cd
from django.template import Library from django.template.base import Node from django.test import TestCase class FilterRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_filter(self): @self.library.filter def func(): return '' self.assertEqual(self.library.filters['func'], func) def test_filter_parens(self): @self.library.filter() def func(): return '' self.assertEqual(self.library.filters['func'], func) def test_filter_name_arg(self): @self.library.filter('name') def func(): return '' self.assertEqual(self.library.filters['name'], func) def test_filter_name_kwarg(self): @self.library.filter(name='name') def func(): return '' self.assertEqual(self.library.filters['name'], func) def test_filter_call(self): def func(): return '' self.library.filter('name', func) self.assertEqual(self.library.filters['name'], func) def test_filter_invalid(self): msg = "Unsupported arguments to Library.filter: (None, '')" with self.assertRaisesMessage(ValueError, msg): self.library.filter(None, '') class InclusionTagRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_inclusion_tag(self): @self.library.inclusion_tag('template.html') def func(): return '' self.assertIn('func', self.library.tags) def test_inclusion_tag_name(self): @self.library.inclusion_tag('template.html', name='name') def func(): return '' self.assertIn('name', self.library.tags) class SimpleTagRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_simple_tag(self): @self.library.simple_tag def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_parens(self): @self.library.simple_tag() def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_name_kwarg(self): @self.library.simple_tag(name='name') def func(): return '' self.assertIn('name', self.library.tags) def test_simple_tag_invalid(self): msg = "Invalid arguments provided to simple_tag" with self.assertRaisesMessage(ValueError, msg): self.library.simple_tag('invalid') class TagRegistrationTests(TestCase): def setUp(self): self.library = Library() def test_tag(self): @self.library.tag def func(parser, token): return Node() self.assertEqual(self.library.tags['func'], func) def test_tag_parens(self): @self.library.tag() def func(parser, token): return Node() self.assertEqual(self.library.tags['func'], func) def test_tag_name_arg(self): @self.library.tag('name') def func(parser, token): return Node() self.assertEqual(self.library.tags['name'], func) def test_tag_name_kwarg(self): @self.library.tag(name='name') def func(parser, token): return Node() self.assertEqual(self.library.tags['name'], func) def test_tag_call(self): def func(parser, token): return Node() self.library.tag('name', func) self.assertEqual(self.library.tags['name'], func) def test_tag_invalid(self): msg = "Unsupported arguments to Library.tag: (None, '')" with self.assertRaisesMessage(ValueError, msg): self.library.tag(None, '')
c237be58f464fc4146676ea78ad19a24681902f11400c34fa9b21b1d3bc974c4
import os.path import sys import tempfile import unittest from contextlib import contextmanager from django.template import TemplateDoesNotExist from django.template.engine import Engine from django.test import SimpleTestCase, override_settings from django.utils.functional import lazystr from .utils import TEMPLATE_DIR class CachedLoaderTests(SimpleTestCase): def setUp(self): self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], ) def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0]) cache = self.engine.template_loaders[0].get_template_cache self.assertEqual(cache['index.html'], template) # Run a second time from cache template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0]) def test_get_template_missing_debug_off(self): """ With template debugging disabled, the raw TemplateDoesNotExist class should be cached when a template is missing. See ticket #26306 and docstrings in the cached loader for details. """ self.engine.debug = False with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('prod-template-missing.html') e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html'] self.assertEqual(e, TemplateDoesNotExist) def test_get_template_missing_debug_on(self): """ With template debugging enabled, a TemplateDoesNotExist instance should be cached when a template is missing. """ self.engine.debug = True with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('debug-template-missing.html') e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html'] self.assertIsInstance(e, TemplateDoesNotExist) self.assertEqual(e.args[0], 'debug-template-missing.html') def test_cached_exception_no_traceback(self): """ When a TemplateDoesNotExist instance is cached, the cached instance should not contain the __traceback__, __context__, or __cause__ attributes that Python sets when raising exceptions. """ self.engine.debug = True with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('no-traceback-in-cache.html') e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html'] error_msg = "Cached TemplateDoesNotExist must not have been thrown." self.assertIsNone(e.__traceback__, error_msg) self.assertIsNone(e.__context__, error_msg) self.assertIsNone(e.__cause__, error_msg) def test_template_name_leading_dash_caching(self): """ #26536 -- A leading dash in a template name shouldn't be stripped from its cache key. """ self.assertEqual(self.engine.template_loaders[0].cache_key('-template.html', []), '-template.html') def test_template_name_lazy_string(self): """ #26603 -- A template name specified as a lazy string should be forced to text before computing its cache key. """ self.assertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html') class FileSystemLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(dirs=[TEMPLATE_DIR], loaders=['django.template.loaders.filesystem.Loader']) super().setUpClass() @contextmanager def set_dirs(self, dirs): original_dirs = self.engine.dirs self.engine.dirs = dirs try: yield finally: self.engine.dirs = original_dirs @contextmanager def source_checker(self, dirs): loader = self.engine.template_loaders[0] def check_sources(path, expected_sources): expected_sources = [os.path.abspath(s) for s in expected_sources] self.assertEqual( [origin.name for origin in loader.get_template_sources(path)], expected_sources, ) with self.set_dirs(dirs): yield check_sources def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) self.assertEqual(template.origin.loader_name, 'django.template.loaders.filesystem.Loader') def test_loaders_dirs(self): engine = Engine(loaders=[('django.template.loaders.filesystem.Loader', [TEMPLATE_DIR])]) template = engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) def test_loaders_dirs_empty(self): """An empty dirs list in loaders overrides top level dirs.""" engine = Engine(dirs=[TEMPLATE_DIR], loaders=[('django.template.loaders.filesystem.Loader', [])]) with self.assertRaises(TemplateDoesNotExist): engine.get_template('index.html') def test_directory_security(self): with self.source_checker(['/dir1', '/dir2']) as check_sources: check_sources('index.html', ['/dir1/index.html', '/dir2/index.html']) check_sources('/etc/passwd', []) check_sources('etc/passwd', ['/dir1/etc/passwd', '/dir2/etc/passwd']) check_sources('../etc/passwd', []) check_sources('../../../etc/passwd', []) check_sources('/dir1/index.html', ['/dir1/index.html']) check_sources('../dir2/index.html', ['/dir2/index.html']) check_sources('/dir1blah', []) check_sources('../dir1blah', []) def test_unicode_template_name(self): with self.source_checker(['/dir1', '/dir2']) as check_sources: # UTF-8 bytestrings are permitted. check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/dir1/Ångström', '/dir2/Ångström']) # Strings are permitted. check_sources('Ångström', ['/dir1/Ångström', '/dir2/Ångström']) def test_utf8_bytestring(self): """ Invalid UTF-8 encoding in bytestrings should raise a useful error """ engine = self.engine loader = engine.template_loaders[0] with self.assertRaises(UnicodeDecodeError): list(loader.get_template_sources(b'\xc3\xc3')) def test_unicode_dir_name(self): with self.source_checker([b'/Stra\xc3\x9fe']) as check_sources: check_sources('Ångström', ['/Straße/Ångström']) check_sources(b'\xc3\x85ngstr\xc3\xb6m', ['/Straße/Ångström']) @unittest.skipUnless( os.path.normcase('/TEST') == os.path.normpath('/test'), "This test only runs on case-sensitive file systems.", ) def test_case_sensitivity(self): with self.source_checker(['/dir1', '/DIR2']) as check_sources: check_sources('index.html', ['/dir1/index.html', '/DIR2/index.html']) check_sources('/DIR1/index.HTML', ['/DIR1/index.HTML']) def test_file_does_not_exist(self): with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('doesnotexist.html') @unittest.skipIf( sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().", ) def test_permissions_error(self): with tempfile.NamedTemporaryFile() as tmpfile: tmpdir = os.path.dirname(tmpfile.name) tmppath = os.path.join(tmpdir, tmpfile.name) os.chmod(tmppath, 0o0222) with self.set_dirs([tmpdir]): with self.assertRaisesMessage(IOError, 'Permission denied'): self.engine.get_template(tmpfile.name) def test_notafile_error(self): with self.assertRaises(IOError): self.engine.get_template('first') class AppDirectoriesLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine( loaders=['django.template.loaders.app_directories.Loader'], ) super().setUpClass() @override_settings(INSTALLED_APPS=['template_tests']) def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) @override_settings(INSTALLED_APPS=[]) def test_not_installed(self): with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('index.html') class LocmemLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine( loaders=[('django.template.loaders.locmem.Loader', { 'index.html': 'index', })], ) super().setUpClass() def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, 'index.html') self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0])
73236f3db8522efba849f066dd437aecd3b9483df466846ffe25938c55a5eeed
from django.template.base import Variable, VariableDoesNotExist from django.test import SimpleTestCase class VariableDoesNotExistTests(SimpleTestCase): def test_str(self): exc = VariableDoesNotExist(msg='Failed lookup in %r', params=({'foo': 'bar'},)) self.assertEqual(str(exc), "Failed lookup in {'foo': 'bar'}") class VariableTests(SimpleTestCase): def test_integer_literals(self): self.assertEqual(Variable('999999999999999999999999999').literal, 999999999999999999999999999) def test_nonliterals(self): """Variable names that aren't resolved as literals.""" var_names = [] for var in ('inf', 'infinity', 'iNFiniTy', 'nan'): var_names.extend((var, '-' + var, '+' + var)) for var in var_names: with self.subTest(var=var): self.assertIsNone(Variable(var).literal)
7ea17e03e14697506771cb5b1d929a0bbdb0875ee372f827cfb4482f9e35e26c
from unittest import TestCase from django.template import Context, Engine class CallableVariablesTests(TestCase): @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_callable(self): class Doodad: def __init__(self, value): self.num_calls = 0 self.value = value def __call__(self): self.num_calls += 1 return {"the_value": self.value} my_doodad = Doodad(42) c = Context({"my_doodad": my_doodad}) # We can't access ``my_doodad.value`` in the template, because # ``my_doodad.__call__`` will be invoked first, yielding a dictionary # without a key ``value``. t = self.engine.from_string('{{ my_doodad.value }}') self.assertEqual(t.render(c), '') # We can confirm that the doodad has been called self.assertEqual(my_doodad.num_calls, 1) # But we can access keys on the dict that's returned # by ``__call__``, instead. t = self.engine.from_string('{{ my_doodad.the_value }}') self.assertEqual(t.render(c), '42') self.assertEqual(my_doodad.num_calls, 2) def test_alters_data(self): class Doodad: alters_data = True def __init__(self, value): self.num_calls = 0 self.value = value def __call__(self): self.num_calls += 1 return {"the_value": self.value} my_doodad = Doodad(42) c = Context({"my_doodad": my_doodad}) # Since ``my_doodad.alters_data`` is True, the template system will not # try to call our doodad but will use string_if_invalid t = self.engine.from_string('{{ my_doodad.value }}') self.assertEqual(t.render(c), '') t = self.engine.from_string('{{ my_doodad.the_value }}') self.assertEqual(t.render(c), '') # Double-check that the object was really never called during the # template rendering. self.assertEqual(my_doodad.num_calls, 0) def test_do_not_call(self): class Doodad: do_not_call_in_templates = True def __init__(self, value): self.num_calls = 0 self.value = value def __call__(self): self.num_calls += 1 return {"the_value": self.value} my_doodad = Doodad(42) c = Context({"my_doodad": my_doodad}) # Since ``my_doodad.do_not_call_in_templates`` is True, the template # system will not try to call our doodad. We can access its attributes # as normal, and we don't have access to the dict that it returns when # called. t = self.engine.from_string('{{ my_doodad.value }}') self.assertEqual(t.render(c), '42') t = self.engine.from_string('{{ my_doodad.the_value }}') self.assertEqual(t.render(c), '') # Double-check that the object was really never called during the # template rendering. self.assertEqual(my_doodad.num_calls, 0) def test_do_not_call_and_alters_data(self): # If we combine ``alters_data`` and ``do_not_call_in_templates``, the # ``alters_data`` attribute will not make any difference in the # template system's behavior. class Doodad: do_not_call_in_templates = True alters_data = True def __init__(self, value): self.num_calls = 0 self.value = value def __call__(self): self.num_calls += 1 return {"the_value": self.value} my_doodad = Doodad(42) c = Context({"my_doodad": my_doodad}) t = self.engine.from_string('{{ my_doodad.value }}') self.assertEqual(t.render(c), '42') t = self.engine.from_string('{{ my_doodad.the_value }}') self.assertEqual(t.render(c), '') # Double-check that the object was really never called during the # template rendering. self.assertEqual(my_doodad.num_calls, 0)
df6a229348bbaaa1d51ae217ead8b9998d877a7b13a04a5b7db768ec9fc91725
import pickle import time from datetime import datetime from django.template import engines from django.template.response import ( ContentNotRenderedError, SimpleTemplateResponse, TemplateResponse, ) from django.test import ( RequestFactory, SimpleTestCase, modify_settings, override_settings, ) from django.test.utils import require_jinja2 from django.utils.deprecation import MiddlewareMixin from .utils import TEMPLATE_DIR def test_processor(request): return {'processors': 'yes'} test_processor_name = 'template_tests.test_response.test_processor' # A test middleware that installs a temporary URLConf class CustomURLConfMiddleware(MiddlewareMixin): def process_request(self, request): request.urlconf = 'template_tests.alternate_urls' class SimpleTemplateResponseTest(SimpleTestCase): def _response(self, template='foo', *args, **kwargs): template = engines['django'].from_string(template) return SimpleTemplateResponse(template, *args, **kwargs) def test_template_resolving(self): response = SimpleTemplateResponse('first/test.html') response.render() self.assertEqual(response.content, b'First template\n') templates = ['foo.html', 'second/test.html', 'first/test.html'] response = SimpleTemplateResponse(templates) response.render() self.assertEqual(response.content, b'Second template\n') response = self._response() response.render() self.assertEqual(response.content, b'foo') def test_explicit_baking(self): # explicit baking response = self._response() self.assertFalse(response.is_rendered) response.render() self.assertTrue(response.is_rendered) def test_render(self): # response is not re-rendered without the render call response = self._response().render() self.assertEqual(response.content, b'foo') # rebaking doesn't change the rendered content template = engines['django'].from_string('bar{{ baz }}') response.template_name = template response.render() self.assertEqual(response.content, b'foo') # but rendered content can be overridden by manually # setting content response.content = 'bar' self.assertEqual(response.content, b'bar') def test_iteration_unrendered(self): # unrendered response raises an exception on iteration response = self._response() self.assertFalse(response.is_rendered) def iteration(): for x in response: pass with self.assertRaises(ContentNotRenderedError): iteration() self.assertFalse(response.is_rendered) def test_iteration_rendered(self): # iteration works for rendered responses response = self._response().render() res = [x for x in response] self.assertEqual(res, [b'foo']) def test_content_access_unrendered(self): # unrendered response raises an exception when content is accessed response = self._response() self.assertFalse(response.is_rendered) with self.assertRaises(ContentNotRenderedError): response.content self.assertFalse(response.is_rendered) def test_content_access_rendered(self): # rendered response content can be accessed response = self._response().render() self.assertEqual(response.content, b'foo') def test_set_content(self): # content can be overridden response = self._response() self.assertFalse(response.is_rendered) response.content = 'spam' self.assertTrue(response.is_rendered) self.assertEqual(response.content, b'spam') response.content = 'baz' self.assertEqual(response.content, b'baz') def test_dict_context(self): response = self._response('{{ foo }}{{ processors }}', {'foo': 'bar'}) self.assertEqual(response.context_data, {'foo': 'bar'}) response.render() self.assertEqual(response.content, b'bar') def test_kwargs(self): response = self._response(content_type='application/json', status=504, charset='ascii') self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) self.assertEqual(response.charset, 'ascii') def test_args(self): response = SimpleTemplateResponse('', {}, 'application/json', 504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) @require_jinja2 def test_using(self): response = SimpleTemplateResponse('template_tests/using.html').render() self.assertEqual(response.content, b'DTL\n') response = SimpleTemplateResponse('template_tests/using.html', using='django').render() self.assertEqual(response.content, b'DTL\n') response = SimpleTemplateResponse('template_tests/using.html', using='jinja2').render() self.assertEqual(response.content, b'Jinja2\n') def test_post_callbacks(self): "Rendering a template response triggers the post-render callbacks" post = [] def post1(obj): post.append('post1') def post2(obj): post.append('post2') response = SimpleTemplateResponse('first/test.html', {}) response.add_post_render_callback(post1) response.add_post_render_callback(post2) # When the content is rendered, all the callbacks are invoked, too. response.render() self.assertEqual(response.content, b'First template\n') self.assertEqual(post, ['post1', 'post2']) def test_pickling(self): # Create a template response. The context is # known to be unpicklable (e.g., a function). response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) # But if we render the response, we can pickle it. response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.content, response.content) self.assertEqual(unpickled_response['content-type'], response['content-type']) self.assertEqual(unpickled_response.status_code, response.status_code) # ...and the unpickled response doesn't have the # template-related attributes, so it can't be re-rendered template_attrs = ('template_name', 'context_data', '_post_render_callbacks') for attr in template_attrs: self.assertFalse(hasattr(unpickled_response, attr)) # ...and requesting any of those attributes raises an exception for attr in template_attrs: with self.assertRaises(AttributeError): getattr(unpickled_response, attr) def test_repickling(self): response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) pickle.dumps(unpickled_response) def test_pickling_cookie(self): response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) response.cookies['key'] = 'value' response.render() pickled_response = pickle.dumps(response, pickle.HIGHEST_PROTOCOL) unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.cookies['key'].value, 'value') @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'OPTIONS': { 'context_processors': [test_processor_name], }, }]) class TemplateResponseTest(SimpleTestCase): def setUp(self): self.factory = RequestFactory() def _response(self, template='foo', *args, **kwargs): self._request = self.factory.get('/') template = engines['django'].from_string(template) return TemplateResponse(self._request, template, *args, **kwargs) def test_render(self): response = self._response('{{ foo }}{{ processors }}').render() self.assertEqual(response.content, b'yes') def test_render_with_requestcontext(self): response = self._response('{{ foo }}{{ processors }}', {'foo': 'bar'}).render() self.assertEqual(response.content, b'baryes') def test_context_processor_priority(self): # context processors should be overridden by passed-in context response = self._response('{{ foo }}{{ processors }}', {'processors': 'no'}).render() self.assertEqual(response.content, b'no') def test_kwargs(self): response = self._response(content_type='application/json', status=504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) def test_args(self): response = TemplateResponse(self.factory.get('/'), '', {}, 'application/json', 504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) @require_jinja2 def test_using(self): request = self.factory.get('/') response = TemplateResponse(request, 'template_tests/using.html').render() self.assertEqual(response.content, b'DTL\n') response = TemplateResponse(request, 'template_tests/using.html', using='django').render() self.assertEqual(response.content, b'DTL\n') response = TemplateResponse(request, 'template_tests/using.html', using='jinja2').render() self.assertEqual(response.content, b'Jinja2\n') def test_pickling(self): # Create a template response. The context is # known to be unpicklable (e.g., a function). response = TemplateResponse( self.factory.get('/'), 'first/test.html', { 'value': 123, 'fn': datetime.now, } ) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) # But if we render the response, we can pickle it. response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.content, response.content) self.assertEqual(unpickled_response['content-type'], response['content-type']) self.assertEqual(unpickled_response.status_code, response.status_code) # ...and the unpickled response doesn't have the # template-related attributes, so it can't be re-rendered template_attrs = ( 'template_name', 'context_data', '_post_render_callbacks', '_request', ) for attr in template_attrs: self.assertFalse(hasattr(unpickled_response, attr)) # ...and requesting any of those attributes raises an exception for attr in template_attrs: with self.assertRaises(AttributeError): getattr(unpickled_response, attr) def test_repickling(self): response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) pickle.dumps(unpickled_response) @modify_settings(MIDDLEWARE={'append': ['template_tests.test_response.CustomURLConfMiddleware']}) @override_settings(ROOT_URLCONF='template_tests.urls') class CustomURLConfTest(SimpleTestCase): def test_custom_urlconf(self): response = self.client.get('/template_response_view/') self.assertContains(response, 'This is where you can find the snark: /snark/') @modify_settings( MIDDLEWARE={ 'append': [ 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', ], }, ) @override_settings(CACHE_MIDDLEWARE_SECONDS=2.0, ROOT_URLCONF='template_tests.alternate_urls') class CacheMiddlewareTest(SimpleTestCase): def test_middleware_caching(self): response = self.client.get('/template_response_view/') self.assertEqual(response.status_code, 200) time.sleep(1.0) response2 = self.client.get('/template_response_view/') self.assertEqual(response2.status_code, 200) self.assertEqual(response.content, response2.content) time.sleep(2.0) # Let the cache expire and test again response2 = self.client.get('/template_response_view/') self.assertEqual(response2.status_code, 200) self.assertNotEqual(response.content, response2.content)
d21c8a7f75369afc02a11571f6bbd64cfc17a8b254c9c86fd9fbbc499d7ed2f6
import functools import os from django.template.engine import Engine from django.test.utils import override_settings from django.utils.safestring import mark_safe ROOT = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIR = os.path.join(ROOT, 'templates') def setup(templates, *args, **kwargs): """ Runs test method multiple times in the following order: debug cached string_if_invalid ----- ------ ----------------- False False False True False False INVALID False True INVALID True False True True """ # when testing deprecation warnings, it's useful to run just one test since # the message won't be displayed multiple times test_once = kwargs.get('test_once', False) for arg in args: templates.update(arg) # numerous tests make use of an inclusion tag # add this in here for simplicity templates["inclusion.html"] = "{{ result }}" loaders = [ ('django.template.loaders.cached.Loader', [ ('django.template.loaders.locmem.Loader', templates), ]), ] def decorator(func): # Make Engine.get_default() raise an exception to ensure that tests # are properly isolated from Django's global settings. @override_settings(TEMPLATES=None) @functools.wraps(func) def inner(self): # Set up custom template tag libraries if specified libraries = getattr(self, 'libraries', {}) self.engine = Engine( libraries=libraries, loaders=loaders, ) func(self) if test_once: return func(self) self.engine = Engine( libraries=libraries, loaders=loaders, string_if_invalid='INVALID', ) func(self) func(self) self.engine = Engine( debug=True, libraries=libraries, loaders=loaders, ) func(self) func(self) return inner return decorator # Helper objects class SomeException(Exception): silent_variable_failure = True class SomeOtherException(Exception): pass class ShouldNotExecuteException(Exception): pass class SomeClass: def __init__(self): self.otherclass = OtherClass() def method(self): return 'SomeClass.method' def method2(self, o): return o def method3(self): raise SomeException def method4(self): raise SomeOtherException def method5(self): raise TypeError def __getitem__(self, key): if key == 'silent_fail_key': raise SomeException elif key == 'noisy_fail_key': raise SomeOtherException raise KeyError @property def silent_fail_attribute(self): raise SomeException @property def noisy_fail_attribute(self): raise SomeOtherException @property def attribute_error_attribute(self): raise AttributeError @property def type_error_attribute(self): raise TypeError class OtherClass: def method(self): return 'OtherClass.method' class TestObj: def is_true(self): return True def is_false(self): return False def is_bad(self): raise ShouldNotExecuteException() class SilentGetItemClass: def __getitem__(self, key): raise SomeException class SilentAttrClass: def b(self): raise SomeException b = property(b) class UTF8Class: "Class whose __str__ returns non-ASCII data" def __str__(self): return 'ŠĐĆŽćžšđ' # These two classes are used to test auto-escaping of string output. class UnsafeClass: def __str__(self): return 'you & me' class SafeClass: def __str__(self): return mark_safe('you &gt; me')
5676e9deaecc42758dbca6e8c42f41da351fdf810ea751284f0703b2f0052453
from unittest import TestCase from django.template import Engine from .utils import TEMPLATE_DIR class OriginTestCase(TestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_origin_compares_equal(self): a = self.engine.get_template('index.html') b = self.engine.get_template('index.html') self.assertEqual(a.origin, b.origin) self.assertTrue(a.origin == b.origin) self.assertFalse(a.origin != b.origin) def test_origin_compares_not_equal(self): a = self.engine.get_template('first/test.html') b = self.engine.get_template('second/test.html') self.assertNotEqual(a.origin, b.origin) self.assertFalse(a.origin == b.origin) self.assertTrue(a.origin != b.origin)
d500634d6ec1a70b3255b67bcedf47e77f691b90d90c705a3f710990cb8b2730
from django.conf.urls import url from . import views urlpatterns = [ # View returning a template response url(r'^template_response_view/$', views.template_response_view), # A view that can be hard to find... url(r'^snark/', views.snark, name='snark'), ]
c816d0e01065ae83dd14b865b3b0d04e7743c51c6c46fbb9b2490db256111202
from django.conf.urls import include, url from . import views ns_patterns = [ # Test urls for testing reverse lookups url(r'^$', views.index, name='index'), url(r'^client/([0-9,]+)/$', views.client, name='client'), url(r'^client/(?P<id>[0-9]+)/(?P<action>[^/]+)/$', views.client_action, name='client_action'), url(r'^client/(?P<client_id>[0-9]+)/(?P<action>[^/]+)/$', views.client_action, name='client_action'), url(r'^named-client/([0-9]+)/$', views.client2, name="named.client"), ] urlpatterns = ns_patterns + [ # Unicode strings are permitted everywhere. url(r'^Юникод/(\w+)/$', views.client2, name="метка_оператора"), url(r'^Юникод/(?P<tag>\S+)/$', views.client2, name="метка_оператора_2"), # Test urls for namespaces and current_app url(r'ns1/', include((ns_patterns, 'app'), 'ns1')), url(r'ns2/', include((ns_patterns, 'app'))), ]
92b40f0d6a1e77b2c4def204855d1f51dc7b996fb517be50b8a0401f0b207c12
from django import template register = template.Library() @register.simple_tag() def annotated_tag_function(val: int): return val
3a7b3d1792543353ef523044e1748fc9ce3c069873d91388f4907e7aac066317
import unittest from django.template.smartif import IfParser class SmartIfTests(unittest.TestCase): def assertCalcEqual(self, expected, tokens): self.assertEqual(expected, IfParser(tokens).parse().eval({})) # We only test things here that are difficult to test elsewhere # Many other tests are found in the main tests for builtin template tags # Test parsing via the printed parse tree def test_not(self): var = IfParser(["not", False]).parse() self.assertEqual("(not (literal False))", repr(var)) self.assertTrue(var.eval({})) self.assertFalse(IfParser(["not", True]).parse().eval({})) def test_or(self): var = IfParser([True, "or", False]).parse() self.assertEqual("(or (literal True) (literal False))", repr(var)) self.assertTrue(var.eval({})) def test_in(self): list_ = [1, 2, 3] self.assertCalcEqual(True, [1, 'in', list_]) self.assertCalcEqual(False, [1, 'in', None]) self.assertCalcEqual(False, [None, 'in', list_]) def test_not_in(self): list_ = [1, 2, 3] self.assertCalcEqual(False, [1, 'not', 'in', list_]) self.assertCalcEqual(True, [4, 'not', 'in', list_]) self.assertCalcEqual(False, [1, 'not', 'in', None]) self.assertCalcEqual(True, [None, 'not', 'in', list_]) def test_precedence(self): # (False and False) or True == True <- we want this one, like Python # False and (False or True) == False self.assertCalcEqual(True, [False, 'and', False, 'or', True]) # True or (False and False) == True <- we want this one, like Python # (True or False) and False == False self.assertCalcEqual(True, [True, 'or', False, 'and', False]) # (1 or 1) == 2 -> False # 1 or (1 == 2) -> True <- we want this one self.assertCalcEqual(True, [1, 'or', 1, '==', 2]) self.assertCalcEqual(True, [True, '==', True, 'or', True, '==', False]) self.assertEqual("(or (and (== (literal 1) (literal 2)) (literal 3)) (literal 4))", repr(IfParser([1, '==', 2, 'and', 3, 'or', 4]).parse()))
6e0cb3b592a24dcb7ef5f85d9350ffc0192638489ef827f208f30c4934b443cf
# Fake views for testing url reverse lookup from django.http import HttpResponse from django.template.response import TemplateResponse def index(request): pass def client(request, id): pass def client_action(request, id, action): pass def client2(request, tag): pass def template_response_view(request): return TemplateResponse(request, 'response.html', {}) def snark(request): return HttpResponse('Found him!')
3cc32a1b58437aea7127d747edbd0efb5a7c73dec28f99c8a010de96fab87aeb
import os from django.core.exceptions import ImproperlyConfigured from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase, override_settings from .utils import ROOT, TEMPLATE_DIR OTHER_DIR = os.path.join(ROOT, 'other_templates') class RenderToStringTest(SimpleTestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): self.assertEqual( self.engine.render_to_string('test_context.html', {'obj': 'test'}), 'obj:test\n', ) class GetDefaultTests(SimpleTestCase): @override_settings(TEMPLATES=[]) def test_no_engines_configured(self): msg = 'No DjangoTemplates backend is configured.' with self.assertRaisesMessage(ImproperlyConfigured, msg): Engine.get_default() @override_settings(TEMPLATES=[{ 'NAME': 'default', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'file_charset': 'abc'}, }]) def test_single_engine_configured(self): self.assertEqual(Engine.get_default().file_charset, 'abc') @override_settings(TEMPLATES=[{ 'NAME': 'default', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'file_charset': 'abc'}, }, { 'NAME': 'other', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'file_charset': 'def'}, }]) def test_multiple_engines_configured(self): self.assertEqual(Engine.get_default().file_charset, 'abc') class LoaderTests(SimpleTestCase): def test_origin(self): engine = Engine(dirs=[TEMPLATE_DIR], debug=True) template = engine.get_template('index.html') self.assertEqual(template.origin.template_name, 'index.html') def test_loader_priority(self): """ #21460 -- The order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') def test_cached_loader_priority(self): """ The order of template loader works. Refs #21460. """ loaders = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
12bb8a43f867e42cde8a1d0d9ff8c223596c23299f6fe5190b76d4aabeed1a0a
from unittest import TestCase from django.template import Context, Engine from django.template.base import TextNode, VariableNode class NodelistTest(TestCase): @classmethod def setUpClass(cls): cls.engine = Engine() super().setUpClass() def test_for(self): template = self.engine.from_string('{% for i in 1 %}{{ a }}{% endfor %}') vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_if(self): template = self.engine.from_string('{% if x %}{{ a }}{% endif %}') vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_ifequal(self): template = self.engine.from_string('{% ifequal x y %}{{ a }}{% endifequal %}') vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_ifchanged(self): template = self.engine.from_string('{% ifchanged x %}{{ a }}{% endifchanged %}') vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) class TextNodeTest(TestCase): def test_textnode_repr(self): engine = Engine() for temptext, reprtext in [ ("Hello, world!", "<TextNode: 'Hello, world!'>"), ("One\ntwo.", "<TextNode: 'One\\ntwo.'>"), ]: template = engine.from_string(temptext) texts = template.nodelist.get_nodes_by_type(TextNode) self.assertEqual(repr(texts[0]), reprtext) class ErrorIndexTest(TestCase): """ Checks whether index of error is calculated correctly in template debugger in for loops. Refs ticket #5831 """ def test_correct_exception_index(self): tests = [ ('{% load bad_tag %}{% for i in range %}{% badsimpletag %}{% endfor %}', (38, 56)), ( '{% load bad_tag %}{% for i in range %}{% for j in range %}' '{% badsimpletag %}{% endfor %}{% endfor %}', (58, 76) ), ( '{% load bad_tag %}{% for i in range %}{% badsimpletag %}' '{% for j in range %}Hello{% endfor %}{% endfor %}', (38, 56) ), ( '{% load bad_tag %}{% for i in range %}{% for j in five %}' '{% badsimpletag %}{% endfor %}{% endfor %}', (38, 57) ), ('{% load bad_tag %}{% for j in five %}{% badsimpletag %}{% endfor %}', (18, 37)), ] context = Context({ 'range': range(5), 'five': 5, }) engine = Engine(debug=True, libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}) for source, expected_error_source_index in tests: template = engine.from_string(source) try: template.render(context) except (RuntimeError, TypeError) as e: debug = e.template_debug self.assertEqual((debug['start'], debug['end']), expected_error_source_index)
c6576a6f33549122966a81daf34991a12101ca60a4de9a538f89826de4c4051c
import os from django.template import Context, Engine, TemplateDoesNotExist from django.test import SimpleTestCase from .utils import ROOT RECURSIVE = os.path.join(ROOT, 'recursive_templates') class ExtendsBehaviorTests(SimpleTestCase): def test_normal_extend(self): engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')]) template = engine.get_template('one.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one') def test_extend_recursive(self): engine = Engine(dirs=[ os.path.join(RECURSIVE, 'fs'), os.path.join(RECURSIVE, 'fs2'), os.path.join(RECURSIVE, 'fs3'), ]) template = engine.get_template('recursive.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive') def test_extend_missing(self): engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')]) template = engine.get_template('extend-missing.html') with self.assertRaises(TemplateDoesNotExist) as e: template.render(Context({})) tried = e.exception.tried self.assertEqual(len(tried), 1) self.assertEqual(tried[0][0].template_name, 'missing.html') def test_recursive_multiple_loaders(self): engine = Engine( dirs=[os.path.join(RECURSIVE, 'fs')], loaders=[( 'django.template.loaders.locmem.Loader', { 'one.html': ( '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}' ), 'two.html': ( '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}' ), 'three.html': ( '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}' ), } ), 'django.template.loaders.filesystem.Loader'], ) template = engine.get_template('one.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three locmem-three two locmem-two one locmem-one') def test_extend_self_error(self): """ Catch if a template extends itself and no other matching templates are found. """ engine = Engine(dirs=[os.path.join(RECURSIVE, 'fs')]) template = engine.get_template('self.html') with self.assertRaises(TemplateDoesNotExist): template.render(Context({})) def test_extend_cached(self): engine = Engine( dirs=[ os.path.join(RECURSIVE, 'fs'), os.path.join(RECURSIVE, 'fs2'), os.path.join(RECURSIVE, 'fs3'), ], loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], ) template = engine.get_template('recursive.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive') cache = engine.template_loaders[0].get_template_cache self.assertEqual(len(cache), 3) expected_path = os.path.join('fs', 'recursive.html') self.assertTrue(cache['recursive.html'].origin.name.endswith(expected_path)) # Render another path that uses the same templates from the cache template = engine.get_template('other-recursive.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'fs3/recursive fs2/recursive fs/recursive') # Template objects should not be duplicated. self.assertEqual(len(cache), 4) expected_path = os.path.join('fs', 'other-recursive.html') self.assertTrue(cache['other-recursive.html'].origin.name.endswith(expected_path)) def test_unique_history_per_loader(self): """ Extending should continue even if two loaders return the same name for a template. """ engine = Engine( loaders=[ ['django.template.loaders.locmem.Loader', { 'base.html': '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}', }], ['django.template.loaders.locmem.Loader', { 'base.html': '{% block content %}loader2{% endblock %}', }], ] ) template = engine.get_template('base.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'loader2 loader1') def test_block_override_in_extended_included_template(self): """ ExtendsNode.find_template() initializes history with self.origin (#28071). """ engine = Engine( loaders=[ ['django.template.loaders.locmem.Loader', { 'base.html': "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}", 'included.html': "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}", }], ['django.template.loaders.locmem.Loader', { 'base.html': "{% block base %}1{% endblock %}{% include 'included.html' %}", 'included.html': "{% block included %}A{% endblock %}", }], ], ) template = engine.get_template('base.html') self.assertEqual(template.render(Context({})), '12AB')
787095e1b0c5ef3af146f6c8850a946de13bf23edde13effc4fde0758cdc0a91
import os from django.template import Context, Engine, TemplateSyntaxError from django.test import SimpleTestCase from .utils import ROOT RELATIVE = os.path.join(ROOT, 'relative_templates') class ExtendsRelativeBehaviorTests(SimpleTestCase): def test_normal_extend(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('one.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one') def test_dir1_extend(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/one.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one dir1 one') def test_dir1_extend1(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/one1.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one dir1 one') def test_dir1_extend2(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/one2.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one dir1 one') def test_dir1_extend3(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/one3.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one dir1 one') def test_dir2_extend(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/dir2/one.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one dir2 one') def test_extend_error(self): engine = Engine(dirs=[RELATIVE]) msg = ( "The relative path '\"./../two.html\"' points outside the file " "hierarchy that template 'error_extends.html' is in." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.render_to_string('error_extends.html') class IncludeRelativeBehaviorTests(SimpleTestCase): def test_normal_include(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/dir2/inc2.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'dir2 include') def test_dir2_include(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/dir2/inc1.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three') def test_include_error(self): engine = Engine(dirs=[RELATIVE]) msg = ( "The relative path '\"./../three.html\"' points outside the file " "hierarchy that template 'error_include.html' is in." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.render_to_string('error_include.html') class ExtendsMixedBehaviorTests(SimpleTestCase): def test_mixing1(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/two.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three two one dir2 one dir1 two') def test_mixing2(self): engine = Engine(dirs=[RELATIVE]) template = engine.get_template('dir1/three.html') output = template.render(Context({})) self.assertEqual(output.strip(), 'three dir1 three') def test_mixing_loop(self): engine = Engine(dirs=[RELATIVE]) msg = ( "The relative path '\"./dir2/../looped.html\"' was translated to " "template name \'dir1/looped.html\', the same template in which " "the tag appears." ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.render_to_string('dir1/looped.html')
a6cd668b93f65e0174d8fd5a8081b75e727ebb62a25a10c8e19cafc4bd5fd750
import os from django.template import Context, Engine, TemplateSyntaxError from django.template.base import Node from django.template.library import InvalidTemplateLibrary from django.test import SimpleTestCase from django.test.utils import extend_sys_path from .templatetags import custom, inclusion from .utils import ROOT LIBRARIES = { 'custom': 'template_tests.templatetags.custom', 'inclusion': 'template_tests.templatetags.inclusion', } class CustomFilterTests(SimpleTestCase): def test_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string("{% load custom %}{{ string|trim:5 }}") self.assertEqual( t.render(Context({"string": "abcdefghijklmnopqrstuvwxyz"})), "abcde" ) def test_decorated_filter(self): engine = Engine(libraries=LIBRARIES) t = engine.from_string('{% load custom %}{{ name|make_data_div }}') self.assertEqual(t.render(Context({'name': 'foo'})), '<div data-name="foo"></div>') class TagTestCase(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(app_dirs=True, libraries=LIBRARIES) super().setUpClass() def verify_tag(self, tag, name): self.assertEqual(tag.__name__, name) self.assertEqual(tag.__doc__, 'Expected %s __doc__' % name) self.assertEqual(tag.__dict__['anything'], 'Expected %s __dict__' % name) class SimpleTagTests(TagTestCase): def test_simple_tags(self): c = Context({'value': 42}) templates = [ ('{% load custom %}{% no_params %}', 'no_params - Expected result'), ('{% load custom %}{% one_param 37 %}', 'one_param - Expected result: 37'), ('{% load custom %}{% explicit_no_context 37 %}', 'explicit_no_context - Expected result: 37'), ('{% load custom %}{% no_params_with_context %}', 'no_params_with_context - Expected result (context value: 42)'), ('{% load custom %}{% params_and_context 37 %}', 'params_and_context - Expected result (context value: 42): 37'), ('{% load custom %}{% simple_two_params 37 42 %}', 'simple_two_params - Expected result: 37, 42'), ('{% load custom %}{% simple_keyword_only_param kwarg=37 %}', 'simple_keyword_only_param - Expected result: 37'), ('{% load custom %}{% simple_keyword_only_default %}', 'simple_keyword_only_default - Expected result: 42'), ('{% load custom %}{% simple_one_default 37 %}', 'simple_one_default - Expected result: 37, hi'), ('{% load custom %}{% simple_one_default 37 two="hello" %}', 'simple_one_default - Expected result: 37, hello'), ('{% load custom %}{% simple_one_default one=99 two="hello" %}', 'simple_one_default - Expected result: 99, hello'), ('{% load custom %}{% simple_one_default 37 42 %}', 'simple_one_default - Expected result: 37, 42'), ('{% load custom %}{% simple_unlimited_args 37 %}', 'simple_unlimited_args - Expected result: 37, hi'), ('{% load custom %}{% simple_unlimited_args 37 42 56 89 %}', 'simple_unlimited_args - Expected result: 37, 42, 56, 89'), ('{% load custom %}{% simple_only_unlimited_args %}', 'simple_only_unlimited_args - Expected result: '), ('{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}', 'simple_only_unlimited_args - Expected result: 37, 42, 56, 89'), ('{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}', 'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'), ] for entry in templates: t = self.engine.from_string(entry[0]) self.assertEqual(t.render(c), entry[1]) for entry in templates: t = self.engine.from_string("%s as var %%}Result: {{ var }}" % entry[0][0:-2]) self.assertEqual(t.render(c), "Result: %s" % entry[1]) def test_simple_tag_errors(self): errors = [ ("'simple_one_default' received unexpected keyword argument 'three'", '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}'), ("'simple_two_params' received too many positional arguments", '{% load custom %}{% simple_two_params 37 42 56 %}'), ("'simple_one_default' received too many positional arguments", '{% load custom %}{% simple_one_default 37 42 56 %}'), ("'simple_keyword_only_param' did not receive value(s) for the argument(s): 'kwarg'", '{% load custom %}{% simple_keyword_only_param %}'), ("'simple_unlimited_args_kwargs' received some positional argument(s) after some keyword argument(s)", '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'), ("'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'), ] for entry in errors: with self.assertRaisesMessage(TemplateSyntaxError, entry[0]): self.engine.from_string(entry[1]) for entry in errors: with self.assertRaisesMessage(TemplateSyntaxError, entry[0]): self.engine.from_string("%s as var %%}" % entry[1][0:-2]) def test_simple_tag_escaping_autoescape_off(self): c = Context({'name': "Jack & Jill"}, autoescape=False) t = self.engine.from_string("{% load custom %}{% escape_naive %}") self.assertEqual(t.render(c), "Hello Jack & Jill!") def test_simple_tag_naive_escaping(self): c = Context({'name': "Jack & Jill"}) t = self.engine.from_string("{% load custom %}{% escape_naive %}") self.assertEqual(t.render(c), "Hello Jack &amp; Jill!") def test_simple_tag_explicit_escaping(self): # Check we don't double escape c = Context({'name': "Jack & Jill"}) t = self.engine.from_string("{% load custom %}{% escape_explicit %}") self.assertEqual(t.render(c), "Hello Jack &amp; Jill!") def test_simple_tag_format_html_escaping(self): # Check we don't double escape c = Context({'name': "Jack & Jill"}) t = self.engine.from_string("{% load custom %}{% escape_format_html %}") self.assertEqual(t.render(c), "Hello Jack &amp; Jill!") def test_simple_tag_registration(self): # The decorators preserve the decorated function's docstring, name, # and attributes. self.verify_tag(custom.no_params, 'no_params') self.verify_tag(custom.one_param, 'one_param') self.verify_tag(custom.explicit_no_context, 'explicit_no_context') self.verify_tag(custom.no_params_with_context, 'no_params_with_context') self.verify_tag(custom.params_and_context, 'params_and_context') self.verify_tag(custom.simple_unlimited_args_kwargs, 'simple_unlimited_args_kwargs') self.verify_tag(custom.simple_tag_without_context_parameter, 'simple_tag_without_context_parameter') def test_simple_tag_missing_context(self): # The 'context' parameter must be present when takes_context is True msg = ( "'simple_tag_without_context_parameter' is decorated with " "takes_context=True so it must have a first argument of 'context'" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.from_string('{% load custom %}{% simple_tag_without_context_parameter 123 %}') class InclusionTagTests(TagTestCase): def test_inclusion_tags(self): c = Context({'value': 42}) templates = [ ('{% load inclusion %}{% inclusion_no_params %}', 'inclusion_no_params - Expected result\n'), ('{% load inclusion %}{% inclusion_one_param 37 %}', 'inclusion_one_param - Expected result: 37\n'), ('{% load inclusion %}{% inclusion_explicit_no_context 37 %}', 'inclusion_explicit_no_context - Expected result: 37\n'), ('{% load inclusion %}{% inclusion_no_params_with_context %}', 'inclusion_no_params_with_context - Expected result (context value: 42)\n'), ('{% load inclusion %}{% inclusion_params_and_context 37 %}', 'inclusion_params_and_context - Expected result (context value: 42): 37\n'), ('{% load inclusion %}{% inclusion_two_params 37 42 %}', 'inclusion_two_params - Expected result: 37, 42\n'), ( '{% load inclusion %}{% inclusion_one_default 37 %}', 'inclusion_one_default - Expected result: 37, hi\n' ), ('{% load inclusion %}{% inclusion_one_default 37 two="hello" %}', 'inclusion_one_default - Expected result: 37, hello\n'), ('{% load inclusion %}{% inclusion_one_default one=99 two="hello" %}', 'inclusion_one_default - Expected result: 99, hello\n'), ('{% load inclusion %}{% inclusion_one_default 37 42 %}', 'inclusion_one_default - Expected result: 37, 42\n'), ('{% load inclusion %}{% inclusion_unlimited_args 37 %}', 'inclusion_unlimited_args - Expected result: 37, hi\n'), ('{% load inclusion %}{% inclusion_unlimited_args 37 42 56 89 %}', 'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n'), ('{% load inclusion %}{% inclusion_only_unlimited_args %}', 'inclusion_only_unlimited_args - Expected result: \n'), ('{% load inclusion %}{% inclusion_only_unlimited_args 37 42 56 89 %}', 'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n'), ('{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}', 'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n'), ] for entry in templates: t = self.engine.from_string(entry[0]) self.assertEqual(t.render(c), entry[1]) def test_inclusion_tag_errors(self): errors = [ ("'inclusion_one_default' received unexpected keyword argument 'three'", '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}'), ("'inclusion_two_params' received too many positional arguments", '{% load inclusion %}{% inclusion_two_params 37 42 56 %}'), ("'inclusion_one_default' received too many positional arguments", '{% load inclusion %}{% inclusion_one_default 37 42 56 %}'), ("'inclusion_one_default' did not receive value(s) for the argument(s): 'one'", '{% load inclusion %}{% inclusion_one_default %}'), ("'inclusion_unlimited_args' did not receive value(s) for the argument(s): 'one'", '{% load inclusion %}{% inclusion_unlimited_args %}'), ( "'inclusion_unlimited_args_kwargs' received some positional argument(s) " "after some keyword argument(s)", '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="boiled" 56 four=1|add:3 %}', ), ("'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'", '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'), ] for entry in errors: with self.assertRaisesMessage(TemplateSyntaxError, entry[0]): self.engine.from_string(entry[1]) def test_include_tag_missing_context(self): # The 'context' parameter must be present when takes_context is True msg = ( "'inclusion_tag_without_context_parameter' is decorated with " "takes_context=True so it must have a first argument of 'context'" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): self.engine.from_string('{% load inclusion %}{% inclusion_tag_without_context_parameter 123 %}') def test_inclusion_tags_from_template(self): c = Context({'value': 42}) templates = [ ('{% load inclusion %}{% inclusion_no_params_from_template %}', 'inclusion_no_params_from_template - Expected result\n'), ('{% load inclusion %}{% inclusion_one_param_from_template 37 %}', 'inclusion_one_param_from_template - Expected result: 37\n'), ('{% load inclusion %}{% inclusion_explicit_no_context_from_template 37 %}', 'inclusion_explicit_no_context_from_template - Expected result: 37\n'), ('{% load inclusion %}{% inclusion_no_params_with_context_from_template %}', 'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n'), ('{% load inclusion %}{% inclusion_params_and_context_from_template 37 %}', 'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n'), ('{% load inclusion %}{% inclusion_two_params_from_template 37 42 %}', 'inclusion_two_params_from_template - Expected result: 37, 42\n'), ('{% load inclusion %}{% inclusion_one_default_from_template 37 %}', 'inclusion_one_default_from_template - Expected result: 37, hi\n'), ('{% load inclusion %}{% inclusion_one_default_from_template 37 42 %}', 'inclusion_one_default_from_template - Expected result: 37, 42\n'), ('{% load inclusion %}{% inclusion_unlimited_args_from_template 37 %}', 'inclusion_unlimited_args_from_template - Expected result: 37, hi\n'), ('{% load inclusion %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}', 'inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'), ('{% load inclusion %}{% inclusion_only_unlimited_args_from_template %}', 'inclusion_only_unlimited_args_from_template - Expected result: \n'), ('{% load inclusion %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}', 'inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'), ] for entry in templates: t = self.engine.from_string(entry[0]) self.assertEqual(t.render(c), entry[1]) def test_inclusion_tag_registration(self): # The decorators preserve the decorated function's docstring, name, # and attributes. self.verify_tag(inclusion.inclusion_no_params, 'inclusion_no_params') self.verify_tag(inclusion.inclusion_one_param, 'inclusion_one_param') self.verify_tag(inclusion.inclusion_explicit_no_context, 'inclusion_explicit_no_context') self.verify_tag(inclusion.inclusion_no_params_with_context, 'inclusion_no_params_with_context') self.verify_tag(inclusion.inclusion_params_and_context, 'inclusion_params_and_context') self.verify_tag(inclusion.inclusion_two_params, 'inclusion_two_params') self.verify_tag(inclusion.inclusion_one_default, 'inclusion_one_default') self.verify_tag(inclusion.inclusion_unlimited_args, 'inclusion_unlimited_args') self.verify_tag(inclusion.inclusion_only_unlimited_args, 'inclusion_only_unlimited_args') self.verify_tag(inclusion.inclusion_tag_without_context_parameter, 'inclusion_tag_without_context_parameter') self.verify_tag(inclusion.inclusion_tag_use_l10n, 'inclusion_tag_use_l10n') self.verify_tag(inclusion.inclusion_unlimited_args_kwargs, 'inclusion_unlimited_args_kwargs') def test_15070_use_l10n(self): """ Inclusion tag passes down `use_l10n` of context to the Context of the included/rendered template as well. """ c = Context({}) t = self.engine.from_string('{% load inclusion %}{% inclusion_tag_use_l10n %}') self.assertEqual(t.render(c).strip(), 'None') c.use_l10n = True self.assertEqual(t.render(c).strip(), 'True') def test_no_render_side_effect(self): """ #23441 -- InclusionNode shouldn't modify its nodelist at render time. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) template = engine.from_string('{% load inclusion %}{% inclusion_no_params %}') count = template.nodelist.get_nodes_by_type(Node) template.render(Context({})) self.assertEqual(template.nodelist.get_nodes_by_type(Node), count) def test_render_context_is_cleared(self): """ #24555 -- InclusionNode should push and pop the render_context stack when rendering. Otherwise, leftover values such as blocks from extending can interfere with subsequent rendering. """ engine = Engine(app_dirs=True, libraries=LIBRARIES) template = engine.from_string('{% load inclusion %}{% inclusion_extends1 %}{% inclusion_extends2 %}') self.assertEqual(template.render(Context({})).strip(), 'one\ntwo') class TemplateTagLoadingTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.egg_dir = os.path.join(ROOT, 'eggs') super().setUpClass() def test_load_error(self): msg = ( "Invalid template library specified. ImportError raised when " "trying to load 'template_tests.broken_tag': cannot import name " "'Xtemplate'" ) with self.assertRaisesMessage(InvalidTemplateLibrary, msg): Engine(libraries={'broken_tag': 'template_tests.broken_tag'}) def test_load_error_egg(self): egg_name = '%s/tagsegg.egg' % self.egg_dir msg = ( "Invalid template library specified. ImportError raised when " "trying to load 'tagsegg.templatetags.broken_egg': cannot " "import name 'Xtemplate'" ) with extend_sys_path(egg_name): with self.assertRaisesMessage(InvalidTemplateLibrary, msg): Engine(libraries={'broken_egg': 'tagsegg.templatetags.broken_egg'}) def test_load_working_egg(self): ttext = "{% load working_egg %}" egg_name = '%s/tagsegg.egg' % self.egg_dir with extend_sys_path(egg_name): engine = Engine(libraries={ 'working_egg': 'tagsegg.templatetags.working_egg', }) engine.from_string(ttext) def test_load_annotated_function(self): Engine(libraries={ 'annotated_tag_function': 'template_tests.annotated_tag_function', })
09e15cc8edb9f5ceb07cb5c054eaaad462f576b62b92dbc56db785ddb3aee5ac
from unittest import skipUnless from django.db import connection from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.test import TestCase, TransactionTestCase from .models import Article, ArticleTranslation, IndexTogetherSingleList class SchemaIndexesTests(TestCase): """ Test index handling by the db.backends.schema infrastructure. """ def test_index_name_hash(self): """ Index names should be deterministic. """ with connection.schema_editor() as editor: index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=("c1",), suffix="123", ) self.assertEqual(index_name, "indexes_article_c1_a52bd80b123") def test_index_name(self): """ Index names on the built-in database backends:: * Are truncated as needed. * Include all the column names. * Include a deterministic hash. """ long_name = 'l%sng' % ('o' * 100) with connection.schema_editor() as editor: index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=('c1', 'c2', long_name), suffix='ix', ) expected = { 'mysql': 'indexes_article_c1_c2_looooooooooooooooooo_255179b2ix', 'oracle': 'indexes_a_c1_c2_loo_255179b2ix', 'postgresql': 'indexes_article_c1_c2_loooooooooooooooooo_255179b2ix', 'sqlite': 'indexes_article_c1_c2_l%sng_255179b2ix' % ('o' * 100), } if connection.vendor not in expected: self.skipTest('This test is only supported on the built-in database backends.') self.assertEqual(index_name, expected[connection.vendor]) def test_index_together(self): editor = connection.schema_editor() index_sql = [str(statement) for statement in editor._model_indexes_sql(Article)] self.assertEqual(len(index_sql), 1) # Ensure the index name is properly quoted self.assertIn( connection.ops.quote_name( editor._create_index_name(Article._meta.db_table, ['headline', 'pub_date'], suffix='_idx') ), index_sql[0] ) def test_index_together_single_list(self): # Test for using index_together with a single list (#22172) index_sql = connection.schema_editor()._model_indexes_sql(IndexTogetherSingleList) self.assertEqual(len(index_sql), 1) @skipUnless(connection.vendor == 'postgresql', "This is a postgresql-specific issue") def test_postgresql_text_indexes(self): """Test creation of PostgreSQL-specific text indexes (#12234)""" from .models import IndexedArticle index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(IndexedArticle)] self.assertEqual(len(index_sql), 5) self.assertIn('("headline" varchar_pattern_ops)', index_sql[1]) self.assertIn('("body" text_pattern_ops)', index_sql[3]) # unique=True and db_index=True should only create the varchar-specific # index (#19441). self.assertIn('("slug" varchar_pattern_ops)', index_sql[4]) @skipUnless(connection.vendor == 'postgresql', "This is a postgresql-specific issue") def test_postgresql_virtual_relation_indexes(self): """Test indexes are not created for related objects""" index_sql = connection.schema_editor()._model_indexes_sql(Article) self.assertEqual(len(index_sql), 1) @skipUnless(connection.vendor == 'mysql', 'MySQL tests') class SchemaIndexesMySQLTests(TransactionTestCase): available_apps = ['indexes'] def test_no_index_for_foreignkey(self): """ MySQL on InnoDB already creates indexes automatically for foreign keys. (#14180). An index should be created if db_constraint=False (#26171). """ storage = connection.introspection.get_storage_engine( connection.cursor(), ArticleTranslation._meta.db_table ) if storage != "InnoDB": self.skip("This test only applies to the InnoDB storage engine") index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(ArticleTranslation)] self.assertEqual(index_sql, [ 'CREATE INDEX `indexes_articletranslation_article_no_constraint_id_d6c0806b` ' 'ON `indexes_articletranslation` (`article_no_constraint_id`)' ]) # The index also shouldn't be created if the ForeignKey is added after # the model was created. field_created = False try: with connection.schema_editor() as editor: new_field = ForeignKey(Article, CASCADE) new_field.set_attributes_from_name('new_foreign_key') editor.add_field(ArticleTranslation, new_field) field_created = True self.assertEqual([str(statement) for statement in editor.deferred_sql], [ 'ALTER TABLE `indexes_articletranslation` ' 'ADD CONSTRAINT `indexes_articletrans_new_foreign_key_id_d27a9146_fk_indexes_a` ' 'FOREIGN KEY (`new_foreign_key_id`) REFERENCES `indexes_article` (`id`)' ]) finally: if field_created: with connection.schema_editor() as editor: editor.remove_field(ArticleTranslation, new_field)
1c4e72f982b282d518a41714f90bbdc7606c9e35c9db5fbf5a3f5496b2e98380
from django.db import connection, models class CurrentTranslation(models.ForeignObject): """ Creates virtual relation to the translation with model cache enabled. """ # Avoid validation requires_unique_target = False def __init__(self, to, on_delete, from_fields, to_fields, **kwargs): # Disable reverse relation kwargs['related_name'] = '+' # Set unique to enable model cache. kwargs['unique'] = True super().__init__(to, on_delete, from_fields, to_fields, **kwargs) class ArticleTranslation(models.Model): article = models.ForeignKey('indexes.Article', models.CASCADE) article_no_constraint = models.ForeignKey('indexes.Article', models.CASCADE, db_constraint=False, related_name='+') language = models.CharField(max_length=10, unique=True) content = models.TextField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() # Add virtual relation to the ArticleTranslation model. translation = CurrentTranslation(ArticleTranslation, models.CASCADE, ['id'], ['article']) class Meta: index_together = [ ["headline", "pub_date"], ] # Model for index_together being used only with single list class IndexTogetherSingleList(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: index_together = ["headline", "pub_date"] # Indexing a TextField on Oracle or MySQL results in index creation error. if connection.vendor == 'postgresql': class IndexedArticle(models.Model): headline = models.CharField(max_length=100, db_index=True) body = models.TextField(db_index=True) slug = models.CharField(max_length=40, unique=True)
3a60519acfbbaeab863d19b7d3bad5a85b58e8e986cec88d678894d110349a5e
""" Tests for Django's bundled context processors. """ from django.test import SimpleTestCase, TestCase, override_settings @override_settings( ROOT_URLCONF='context_processors.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', ], }, }], ) class RequestContextProcessorTests(SimpleTestCase): """ Tests for the ``django.template.context_processors.request`` processor. """ def test_request_attributes(self): """ The request object is available in the template and that its attributes can't be overridden by GET and POST parameters (#3828). """ url = '/request_attrs/' # We should have the request object in the template. response = self.client.get(url) self.assertContains(response, 'Have request') # Test is_secure. response = self.client.get(url) self.assertContains(response, 'Not secure') response = self.client.get(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') response = self.client.post(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') # Test path. response = self.client.get(url) self.assertContains(response, url) response = self.client.get(url, {'path': '/blah/'}) self.assertContains(response, url) response = self.client.post(url, {'path': '/blah/'}) self.assertContains(response, url) @override_settings( DEBUG=True, INTERNAL_IPS=['127.0.0.1'], ROOT_URLCONF='context_processors.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', ], }, }], ) class DebugContextProcessorTests(TestCase): """ Tests for the ``django.template.context_processors.debug`` processor. """ multi_db = True def test_debug(self): url = '/debug/' # We should have the debug flag in the template. response = self.client.get(url) self.assertContains(response, 'Have debug') # And now we should not with override_settings(DEBUG=False): response = self.client.get(url) self.assertNotContains(response, 'Have debug') def test_sql_queries(self): """ Test whether sql_queries represents the actual amount of queries executed. (#23364) """ url = '/debug/' response = self.client.get(url) self.assertContains(response, 'First query list: 0') self.assertContains(response, 'Second query list: 1') # Check we have not actually memoized connection.queries self.assertContains(response, 'Third query list: 2') # Check queries for DB connection 'other' self.assertContains(response, 'Fourth query list: 3')
a6b506158e7ac1c4b50737058d8385be2546318909b993caf3871709cb4ec14d
from django.db import models class DebugObject(models.Model): pass
47a8987ee40e17b4adc22cb9e1918092d772a7433b5c7d40239cd20477ace8cd
from django.conf.urls import url from . import views urlpatterns = [ url(r'^request_attrs/$', views.request_processor), url(r'^debug/$', views.debug_processor), ]
031d6e85f12cd9e405c810f097586caadcaa81463527a822693beff5523fe3df
from django.shortcuts import render from .models import DebugObject def request_processor(request): return render(request, 'context_processors/request_attrs.html') def debug_processor(request): context = { 'debug_objects': DebugObject.objects, 'other_debug_objects': DebugObject.objects.using('other'), } return render(request, 'context_processors/debug.html', context)
0767fff1fcf184a7618d18d426da0cf6aecece4ada642cd96532d40c612c6a57
from datetime import datetime from operator import attrgetter from django.test import TestCase from .models import ( CustomMembership, Employee, Event, Friendship, Group, Ingredient, Invitation, Membership, Person, PersonSelfRefM2M, Recipe, RecipeIngredient, Relationship, ) class M2mThroughTests(TestCase): @classmethod def setUpTestData(cls): cls.bob = Person.objects.create(name='Bob') cls.jim = Person.objects.create(name='Jim') cls.jane = Person.objects.create(name='Jane') cls.rock = Group.objects.create(name='Rock') cls.roll = Group.objects.create(name='Roll') def test_retrieve_intermediate_items(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) expected = ['Jane', 'Jim'] self.assertQuerysetEqual( self.rock.members.all(), expected, attrgetter("name") ) def test_get_on_intermediate_model(self): Membership.objects.create(person=self.jane, group=self.rock) queryset = Membership.objects.get(person=self.jane, group=self.rock) self.assertEqual( repr(queryset), '<Membership: Jane is a member of Rock>' ) def test_filter_on_intermediate_model(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) queryset = Membership.objects.filter(group=self.rock) expected = [ '<Membership: Jim is a member of Rock>', '<Membership: Jane is a member of Rock>', ] self.assertQuerysetEqual( queryset, expected ) def test_cannot_use_add_on_m2m_with_intermediary_model(self): msg = 'Cannot use add() on a ManyToManyField which specifies an intermediary model' with self.assertRaisesMessage(AttributeError, msg): self.rock.members.add(self.bob) self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_cannot_use_create_on_m2m_with_intermediary_model(self): msg = 'Cannot use create() on a ManyToManyField which specifies an intermediary model' with self.assertRaisesMessage(AttributeError, msg): self.rock.members.create(name='Annie') self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_cannot_use_remove_on_m2m_with_intermediary_model(self): Membership.objects.create(person=self.jim, group=self.rock) msg = 'Cannot use remove() on a ManyToManyField which specifies an intermediary model' with self.assertRaisesMessage(AttributeError, msg): self.rock.members.remove(self.jim) self.assertQuerysetEqual( self.rock.members.all(), ['Jim'], attrgetter("name") ) def test_cannot_use_setattr_on_m2m_with_intermediary_model(self): msg = 'Cannot set values on a ManyToManyField which specifies an intermediary model' members = list(Person.objects.filter(name__in=['Bob', 'Jim'])) with self.assertRaisesMessage(AttributeError, msg): self.rock.members.set(members) self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_clear_removes_all_the_m2m_relationships(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) self.rock.members.clear() self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_retrieve_reverse_intermediate_items(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.roll) expected = ['Rock', 'Roll'] self.assertQuerysetEqual( self.jim.group_set.all(), expected, attrgetter("name") ) def test_cannot_use_add_on_reverse_m2m_with_intermediary_model(self): msg = 'Cannot use add() on a ManyToManyField which specifies an intermediary model' with self.assertRaisesMessage(AttributeError, msg): self.bob.group_set.add(self.bob) self.assertQuerysetEqual( self.bob.group_set.all(), [] ) def test_cannot_use_create_on_reverse_m2m_with_intermediary_model(self): msg = 'Cannot use create() on a ManyToManyField which specifies an intermediary model' with self.assertRaisesMessage(AttributeError, msg): self.bob.group_set.create(name='Funk') self.assertQuerysetEqual( self.bob.group_set.all(), [] ) def test_cannot_use_remove_on_reverse_m2m_with_intermediary_model(self): Membership.objects.create(person=self.bob, group=self.rock) msg = 'Cannot use remove() on a ManyToManyField which specifies an intermediary model' with self.assertRaisesMessage(AttributeError, msg): self.bob.group_set.remove(self.rock) self.assertQuerysetEqual( self.bob.group_set.all(), ['Rock'], attrgetter('name') ) def test_cannot_use_setattr_on_reverse_m2m_with_intermediary_model(self): msg = 'Cannot set values on a ManyToManyField which specifies an intermediary model' members = list(Group.objects.filter(name__in=['Rock', 'Roll'])) with self.assertRaisesMessage(AttributeError, msg): self.bob.group_set.set(members) self.assertQuerysetEqual( self.bob.group_set.all(), [] ) def test_clear_on_reverse_removes_all_the_m2m_relationships(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.roll) self.jim.group_set.clear() self.assertQuerysetEqual( self.jim.group_set.all(), [] ) def test_query_model_by_attribute_name_of_related_model(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll) self.assertQuerysetEqual( Group.objects.filter(members__name='Bob'), ['Roll'], attrgetter("name") ) def test_order_by_relational_field_through_model(self): CustomMembership.objects.create(person=self.jim, group=self.rock) CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jane, group=self.roll) CustomMembership.objects.create(person=self.jim, group=self.roll) self.assertSequenceEqual( self.rock.custom_members.order_by('custom_person_related_name'), [self.jim, self.bob] ) self.assertSequenceEqual( self.roll.custom_members.order_by('custom_person_related_name'), [self.jane, self.jim] ) def test_query_first_model_by_intermediate_model_attribute(self): Membership.objects.create( person=self.jane, group=self.roll, invite_reason="She was just awesome." ) Membership.objects.create( person=self.jim, group=self.roll, invite_reason="He is good." ) Membership.objects.create(person=self.bob, group=self.roll) qs = Group.objects.filter( membership__invite_reason="She was just awesome." ) self.assertQuerysetEqual( qs, ['Roll'], attrgetter("name") ) def test_query_second_model_by_intermediate_model_attribute(self): Membership.objects.create( person=self.jane, group=self.roll, invite_reason="She was just awesome." ) Membership.objects.create( person=self.jim, group=self.roll, invite_reason="He is good." ) Membership.objects.create(person=self.bob, group=self.roll) qs = Person.objects.filter( membership__invite_reason="She was just awesome." ) self.assertQuerysetEqual( qs, ['Jane'], attrgetter("name") ) def test_query_model_by_related_model_name(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll) self.assertQuerysetEqual( Person.objects.filter(group__name="Rock"), ['Jane', 'Jim'], attrgetter("name") ) def test_query_model_by_custom_related_name(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( Person.objects.filter(custom__name="Rock"), ['Bob', 'Jim'], attrgetter("name") ) def test_query_model_by_intermediate_can_return_non_unique_queryset(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create( person=self.jane, group=self.rock, date_joined=datetime(2006, 1, 1) ) Membership.objects.create( person=self.bob, group=self.roll, date_joined=datetime(2004, 1, 1)) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create( person=self.jane, group=self.roll, date_joined=datetime(2004, 1, 1)) qs = Person.objects.filter( membership__date_joined__gt=datetime(2004, 1, 1) ) self.assertQuerysetEqual( qs, ['Jane', 'Jim', 'Jim'], attrgetter("name") ) def test_custom_related_name_forward_empty_qs(self): self.assertQuerysetEqual( self.rock.custom_members.all(), [] ) def test_custom_related_name_reverse_empty_qs(self): self.assertQuerysetEqual( self.bob.custom.all(), [] ) def test_custom_related_name_forward_non_empty_qs(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( self.rock.custom_members.all(), ['Bob', 'Jim'], attrgetter("name") ) def test_custom_related_name_reverse_non_empty_qs(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( self.bob.custom.all(), ['Rock'], attrgetter("name") ) def test_custom_related_name_doesnt_conflict_with_fky_related_name(self): CustomMembership.objects.create(person=self.bob, group=self.rock) self.assertQuerysetEqual( self.bob.custom_person_related_name.all(), ['<CustomMembership: Bob is a member of Rock>'] ) def test_through_fields(self): """ Relations with intermediary tables with multiple FKs to the M2M's ``to`` model are possible. """ event = Event.objects.create(title='Rockwhale 2014') Invitation.objects.create(event=event, inviter=self.bob, invitee=self.jim) Invitation.objects.create(event=event, inviter=self.bob, invitee=self.jane) self.assertQuerysetEqual( event.invitees.all(), ['Jane', 'Jim'], attrgetter('name') ) class M2mThroughReferentialTests(TestCase): def test_self_referential_empty_qs(self): tony = PersonSelfRefM2M.objects.create(name="Tony") self.assertQuerysetEqual( tony.friends.all(), [] ) def test_self_referential_non_symmetrical_first_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) def test_self_referential_non_symmetrical_second_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) self.assertQuerysetEqual( chris.friends.all(), [] ) def test_self_referential_non_symmetrical_clear_first_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) chris.friends.clear() self.assertQuerysetEqual( chris.friends.all(), [] ) # Since this isn't a symmetrical relation, Tony's friend link still exists. self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) def test_self_referential_symmetrical(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) Friendship.objects.create( first=chris, second=tony, date_friended=datetime.now() ) self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) self.assertQuerysetEqual( chris.friends.all(), ['Tony'], attrgetter("name") ) def test_through_fields_self_referential(self): john = Employee.objects.create(name='john') peter = Employee.objects.create(name='peter') mary = Employee.objects.create(name='mary') harry = Employee.objects.create(name='harry') Relationship.objects.create(source=john, target=peter, another=None) Relationship.objects.create(source=john, target=mary, another=None) Relationship.objects.create(source=john, target=harry, another=peter) self.assertQuerysetEqual( john.subordinates.all(), ['peter', 'mary', 'harry'], attrgetter('name') ) class M2mThroughToFieldsTests(TestCase): @classmethod def setUpTestData(cls): cls.pea = Ingredient.objects.create(iname='pea') cls.potato = Ingredient.objects.create(iname='potato') cls.tomato = Ingredient.objects.create(iname='tomato') cls.curry = Recipe.objects.create(rname='curry') RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.potato) RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.pea) RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.tomato) def test_retrieval(self): # Forward retrieval self.assertSequenceEqual(self.curry.ingredients.all(), [self.pea, self.potato, self.tomato]) # Backward retrieval self.assertEqual(self.tomato.recipes.get(), self.curry) def test_choices(self): field = Recipe._meta.get_field('ingredients') self.assertEqual( [choice[0] for choice in field.get_choices(include_blank=False)], ['pea', 'potato', 'tomato'] )
0c6ddbe3da0c48c45f5ea72ddd0f9b1984769fd14d64d19d73c7c50c68dec94a
from datetime import datetime from django.db import models # M2M described on one of the models class Person(models.Model): name = models.CharField(max_length=128) class Meta: ordering = ('name',) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') custom_members = models.ManyToManyField(Person, through='CustomMembership', related_name="custom") nodefaultsnonulls = models.ManyToManyField( Person, through='TestNoDefaultsOrNulls', related_name="testnodefaultsnonulls", ) class Meta: ordering = ('name',) def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) date_joined = models.DateTimeField(default=datetime.now) invite_reason = models.CharField(max_length=64, null=True) class Meta: ordering = ('date_joined', 'invite_reason', 'group') def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class CustomMembership(models.Model): person = models.ForeignKey( Person, models.CASCADE, db_column="custom_person_column", related_name="custom_person_related_name", ) group = models.ForeignKey(Group, models.CASCADE) weird_fk = models.ForeignKey(Membership, models.SET_NULL, null=True) date_joined = models.DateTimeField(default=datetime.now) def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class Meta: db_table = "test_table" ordering = ["date_joined"] class TestNoDefaultsOrNulls(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) nodefaultnonull = models.CharField(max_length=5) class PersonSelfRefM2M(models.Model): name = models.CharField(max_length=5) friends = models.ManyToManyField('self', through="Friendship", symmetrical=False) def __str__(self): return self.name class Friendship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="rel_to_set") date_friended = models.DateTimeField() # Custom through link fields class Event(models.Model): title = models.CharField(max_length=50) invitees = models.ManyToManyField( Person, through='Invitation', through_fields=('event', 'invitee'), related_name='events_invited', ) def __str__(self): return self.title class Invitation(models.Model): event = models.ForeignKey(Event, models.CASCADE, related_name='invitations') # field order is deliberately inverted. the target field is "invitee". inviter = models.ForeignKey(Person, models.CASCADE, related_name='invitations_sent') invitee = models.ForeignKey(Person, models.CASCADE, related_name='invitations') class Employee(models.Model): name = models.CharField(max_length=5) subordinates = models.ManyToManyField( 'self', through="Relationship", through_fields=('source', 'target'), symmetrical=False, ) class Meta: ordering = ('pk',) def __str__(self): return self.name class Relationship(models.Model): # field order is deliberately inverted. another = models.ForeignKey(Employee, models.SET_NULL, related_name="rel_another_set", null=True) target = models.ForeignKey(Employee, models.CASCADE, related_name="rel_target_set") source = models.ForeignKey(Employee, models.CASCADE, related_name="rel_source_set") class Ingredient(models.Model): iname = models.CharField(max_length=20, unique=True) class Meta: ordering = ('iname',) class Recipe(models.Model): rname = models.CharField(max_length=20, unique=True) ingredients = models.ManyToManyField( Ingredient, through='RecipeIngredient', related_name='recipes', ) class Meta: ordering = ('rname',) class RecipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, models.CASCADE, to_field='iname') recipe = models.ForeignKey(Recipe, models.CASCADE, to_field='rname')
b9371557e767182a66eb1fc9f61bfafbda89c8237f6d97c1a4a0765c4c56b40e
import datetime import re from datetime import date from decimal import Decimal from django import forms from django.core.exceptions import ImproperlyConfigured from django.db import models from django.forms.models import ( BaseModelFormSet, _get_foreign_key, inlineformset_factory, modelformset_factory, ) from django.http import QueryDict from django.test import TestCase, skipUnlessDBFeature from .models import ( AlternateBook, Author, AuthorMeeting, BetterAuthor, Book, BookWithCustomPK, BookWithOptionalAltEditor, ClassyMexicanRestaurant, CustomPrimaryKey, Location, Membership, MexicanRestaurant, Owner, OwnerProfile, Person, Place, Player, Poem, Poet, Post, Price, Product, Repository, Restaurant, Revision, Team, ) class DeletionTests(TestCase): def test_deletion(self): PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.pk), 'form-0-name': 'test', 'form-0-DELETE': 'on', } formset = PoetFormSet(data, queryset=Poet.objects.all()) formset.save(commit=False) self.assertEqual(Poet.objects.count(), 1) formset.save() self.assertTrue(formset.is_valid()) self.assertEqual(Poet.objects.count(), 0) def test_add_form_deletion_when_invalid(self): """ Make sure that an add form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') # One existing untouched and two new unvalid forms data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.id), 'form-0-name': 'test', 'form-1-id': '', 'form-1-name': 'x' * 1000, # Too long 'form-2-id': str(poet.id), # Violate unique constraint 'form-2-name': 'test2', } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertIs(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data in new forms aren't actually valid. data['form-0-DELETE'] = 'on' data['form-1-DELETE'] = 'on' data['form-2-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertIs(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_change_form_deletion_when_invalid(self): """ Make sure that a change form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.id), 'form-0-name': 'x' * 1000, } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertIs(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data isn't actually valid. data['form-0-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertIs(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_outdated_deletion(self): poet = Poet.objects.create(name='test') poem = Poem.objects.create(name='Brevity is the soul of wit', poet=poet) PoemFormSet = inlineformset_factory(Poet, Poem, fields="__all__", can_delete=True) # Simulate deletion of an object that doesn't exist in the database data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-0-id': str(poem.pk), 'form-0-name': 'foo', 'form-1-id': str(poem.pk + 1), # doesn't exist 'form-1-name': 'bar', 'form-1-DELETE': 'on', } formset = PoemFormSet(data, instance=poet, prefix="form") # The formset is valid even though poem.pk + 1 doesn't exist, # because it's marked for deletion anyway self.assertTrue(formset.is_valid()) formset.save() # Make sure the save went through correctly self.assertEqual(Poem.objects.get(pk=poem.pk).name, "foo") self.assertEqual(poet.poem_set.count(), 1) self.assertFalse(Poem.objects.filter(pk=poem.pk + 1).exists()) class ModelFormsetTest(TestCase): def test_modelformset_factory_without_fields(self): """ Regression for #19733 """ message = ( "Calling modelformset_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelformset_factory(Author) def test_simple_save(self): qs = Author.objects.all() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100">' '<input type="hidden" name="form-0-id" id="id_form-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100">' '<input type="hidden" name="form-1-id" id="id_form-1-id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label>' ' <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">' '<input type="hidden" name="form-2-id" id="id_form-2-id"></p>' ) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Charles Baudelaire', 'form-1-name': 'Arthur Rimbaud', 'form-2-name': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) author1, author2 = saved self.assertEqual(author1, Author.objects.get(name='Charles Baudelaire')) self.assertEqual(author2, Author.objects.get(name='Arthur Rimbaud')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1]) # Gah! We forgot Paul Verlaine. Let's create a formset to edit the # existing authors with an extra form to add him. We *could* pass in a # queryset to restrict the Author objects we edit, but in this case # we'll use it to display them in alphabetical order by name. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=1, can_delete=False) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id"></p>' % author2.id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id"></p>' % author1.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label>' '<input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">' '<input type="hidden" name="form-2-id" id="id_form-2-id"></p>' ) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '2', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-name': 'Paul Verlaine', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # Only changed or new objects are returned from formset.save() saved = formset.save() self.assertEqual(len(saved), 1) author3 = saved[0] self.assertEqual(author3, Author.objects.get(name='Paul Verlaine')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # This probably shouldn't happen, but it will. If an add form was # marked for deletion, make sure we don't save that form. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=1, can_delete=True) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" ' 'value="Arthur Rimbaud" maxlength="100"></p>' '<p><label for="id_form-0-DELETE">Delete:</label>' '<input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id"></p>' % author2.id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" ' 'value="Charles Baudelaire" maxlength="100"></p>' '<p><label for="id_form-1-DELETE">Delete:</label>' '<input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id"></p>' % author1.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label>' '<input id="id_form-2-name" type="text" name="form-2-name" ' 'value="Paul Verlaine" maxlength="100"></p>' '<p><label for="id_form-2-DELETE">Delete:</label>' '<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE">' '<input type="hidden" name="form-2-id" value="%d" id="id_form-2-id"></p>' % author3.id ) self.assertHTMLEqual( formset.forms[3].as_p(), '<p><label for="id_form-3-name">Name:</label>' '<input id="id_form-3-name" type="text" name="form-3-name" maxlength="100"></p>' '<p><label for="id_form-3-DELETE">Delete:</label>' '<input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE">' '<input type="hidden" name="form-3-id" id="id_form-3-id"></p>' ) data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': 'Walt Whitman', 'form-3-DELETE': 'on', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # No objects were changed or saved so nothing will come back. self.assertEqual(formset.save(), []) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # Let's edit a record to ensure save only returns that one record. data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Walt Whitman', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': '', 'form-3-DELETE': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # One record has changed. saved = formset.save() self.assertEqual(len(saved), 1) self.assertEqual(saved[0], Author.objects.get(name='Walt Whitman')) def test_commit_false(self): # Test the behavior of commit=False and save_m2m author1 = Author.objects.create(name='Charles Baudelaire') author2 = Author.objects.create(name='Paul Verlaine') author3 = Author.objects.create(name='Walt Whitman') meeting = AuthorMeeting.objects.create(created=date.today()) meeting.authors.set(Author.objects.all()) # create an Author instance to add to the meeting. author4 = Author.objects.create(name='John Steinbeck') AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, fields="__all__", extra=1, can_delete=True) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(meeting.id), 'form-0-name': '2nd Tuesday of the Week Meeting', 'form-0-authors': [author2.id, author1.id, author3.id, author4.id], 'form-1-name': '', 'form-1-authors': '', 'form-1-DELETE': '', } formset = AuthorMeetingFormSet(data=data, queryset=AuthorMeeting.objects.all()) self.assertTrue(formset.is_valid()) instances = formset.save(commit=False) for instance in instances: instance.created = date.today() instance.save() formset.save_m2m() self.assertQuerysetEqual(instances[0].authors.all(), [ '<Author: Charles Baudelaire>', '<Author: John Steinbeck>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_max_num(self): # Test the behavior of max_num with model formsets. It should allow # all existing related objects/inlines for a given object to be # displayed, but not allow the creation of new inlines beyond max_num. Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Paul Verlaine') Author.objects.create(name='Walt Whitman') qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=None, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 6) self.assertEqual(len(formset.extra_forms), 3) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertEqual(len(formset.extra_forms), 1) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertEqual(len(formset.extra_forms), 0) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=None) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_min_num(self): # Test the behavior of min_num with model formsets. It should be # added to extra. qs = Author.objects.none() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=0) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 0) AuthorFormSet = modelformset_factory(Author, fields="__all__", min_num=1, extra=0) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 1) AuthorFormSet = modelformset_factory(Author, fields="__all__", min_num=1, extra=1) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 2) def test_min_num_with_existing(self): # Test the behavior of min_num with existing objects. Author.objects.create(name='Charles Baudelaire') qs = Author.objects.all() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=0, min_num=1) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 1) def test_custom_save_method(self): class PoetForm(forms.ModelForm): def save(self, commit=True): # change the name to "Vladimir Mayakovsky" just to be a jerk. author = super().save(commit=False) author.name = "Vladimir Mayakovsky" if commit: author.save() return author PoetFormSet = modelformset_factory(Poet, fields="__all__", form=PoetForm) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Walt Whitman', 'form-1-name': 'Charles Baudelaire', 'form-2-name': '', } qs = Poet.objects.all() formset = PoetFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) poets = formset.save() self.assertEqual(len(poets), 2) poet1, poet2 = poets self.assertEqual(poet1.name, 'Vladimir Mayakovsky') self.assertEqual(poet2.name, 'Vladimir Mayakovsky') def test_custom_form(self): """ model_formset_factory() respects fields and exclude parameters of a custom form. """ class PostForm1(forms.ModelForm): class Meta: model = Post fields = ('title', 'posted') class PostForm2(forms.ModelForm): class Meta: model = Post exclude = ('subtitle',) PostFormSet = modelformset_factory(Post, form=PostForm1) formset = PostFormSet() self.assertNotIn("subtitle", formset.forms[0].fields) PostFormSet = modelformset_factory(Post, form=PostForm2) formset = PostFormSet() self.assertNotIn("subtitle", formset.forms[0].fields) def test_custom_queryset_init(self): """ A queryset can be overridden in the formset's __init__() method. """ Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Paul Verlaine') class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Author.objects.filter(name__startswith='Charles') AuthorFormSet = modelformset_factory(Author, fields='__all__', formset=BaseAuthorFormSet) formset = AuthorFormSet() self.assertEqual(len(formset.get_queryset()), 1) def test_model_inheritance(self): BetterAuthorFormSet = modelformset_factory(BetterAuthor, fields="__all__") formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100"></p>' '<p><label for="id_form-0-write_speed">Write speed:</label>' '<input type="number" name="form-0-write_speed" id="id_form-0-write_speed">' '<input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr"></p>' ) data = { 'form-TOTAL_FORMS': '1', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': '', 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) author1, = saved self.assertEqual(author1, BetterAuthor.objects.get(name='Ernest Hemingway')) hemingway_id = BetterAuthor.objects.get(name="Ernest Hemingway").pk formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100"></p>' '<p><label for="id_form-0-write_speed">Write speed:</label>' '<input type="number" name="form-0-write_speed" value="10" id="id_form-0-write_speed">' '<input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr"></p>' % hemingway_id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100"></p>' '<p><label for="id_form-1-write_speed">Write speed:</label>' '<input type="number" name="form-1-write_speed" id="id_form-1-write_speed">' '<input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr"></p>' ) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': hemingway_id, 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', 'form-1-author_ptr': '', 'form-1-name': '', 'form-1-write_speed': '', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) self.assertEqual(formset.save(), []) def test_inline_formsets(self): # We can also create a formset that is tied to a parent model. This is # how the admin system's edit inline functionality works. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=3, fields="__all__") author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" ' 'name="book_set-0-title" maxlength="100"><input type="hidden" name="book_set-0-author" value="%d" ' 'id="id_book_set-0-author"><input type="hidden" name="book_set-0-id" id="id_book_set-0-id">' '</p>' % author.id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>' % author.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>' % author.id ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': '', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1, Book.objects.get(title='Les Fleurs du Mal')) self.assertQuerysetEqual(author.book_set.all(), ['<Book: Les Fleurs du Mal>']) # Now that we've added a book to Charles Baudelaire, let's try adding # another one. This time though, an edit form will be available for # every existing book. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") author = Author.objects.get(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label>' '<input id="id_book_set-0-title" type="text" name="book_set-0-title" ' 'value="Les Fleurs du Mal" maxlength="100">' '<input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author">' '<input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id"></p>' % ( author.id, book1.id, ) ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>' % author.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>' % author.id ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book2, = saved self.assertEqual(book2, Book.objects.get(title='Les Paradis Artificiels')) # As you can see, 'Les Paradis Artificiels' is now a book belonging to # Charles Baudelaire. self.assertQuerysetEqual(author.book_set.order_by('title'), [ '<Book: Les Fleurs du Mal>', '<Book: Les Paradis Artificiels>', ]) def test_inline_formsets_save_as_new(self): # The save_as_new parameter lets you re-associate the data to a new # instance. This is used in the admin for save_as functionality. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") Author.objects.create(name='Charles Baudelaire') # An immutable QueryDict simulates request.POST. data = QueryDict(mutable=True) data.update({ 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': '1', 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-id': '2', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', }) data._mutable = False formset = AuthorBooksFormSet(data, instance=Author(), save_as_new=True) self.assertTrue(formset.is_valid()) self.assertIs(data._mutable, False) new_author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(data, instance=new_author, save_as_new=True) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.title, 'Les Paradis Artificiels') # Test using a custom prefix on an inline formset. formset = AuthorBooksFormSet(prefix="test") self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_test-0-title">Title:</label>' '<input id="id_test-0-title" type="text" name="test-0-title" maxlength="100">' '<input type="hidden" name="test-0-author" id="id_test-0-author">' '<input type="hidden" name="test-0-id" id="id_test-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_test-1-title">Title:</label>' '<input id="id_test-1-title" type="text" name="test-1-title" maxlength="100">' '<input type="hidden" name="test-1-author" id="id_test-1-author">' '<input type="hidden" name="test-1-id" id="id_test-1-id"></p>' ) def test_inline_formsets_with_custom_pk(self): # Test inline formsets where the inline-edited object has a custom # primary key that is not the fk to the parent object. self.maxDiff = 1024 AuthorBooksFormSet2 = inlineformset_factory( Author, BookWithCustomPK, can_delete=False, extra=1, fields="__all__" ) author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet2(instance=author) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_bookwithcustompk_set-0-my_pk">My pk:</label>' '<input id="id_bookwithcustompk_set-0-my_pk" type="number" ' 'name="bookwithcustompk_set-0-my_pk" step="1"></p>' '<p><label for="id_bookwithcustompk_set-0-title">Title:</label>' '<input id="id_bookwithcustompk_set-0-title" type="text" ' 'name="bookwithcustompk_set-0-title" maxlength="100">' '<input type="hidden" name="bookwithcustompk_set-0-author" ' 'value="1" id="id_bookwithcustompk_set-0-author"></p>' ) data = { 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithcustompk_set-0-my_pk': '77777', 'bookwithcustompk_set-0-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet2(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.pk, 77777) book1 = author.bookwithcustompk_set.get() self.assertEqual(book1.title, 'Les Fleurs du Mal') def test_inline_formsets_with_multi_table_inheritance(self): # Test inline formsets where the inline-edited object uses multi-table # inheritance, thus has a non AutoField yet auto-created primary key. AuthorBooksFormSet3 = inlineformset_factory(Author, AlternateBook, can_delete=False, extra=1, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet3(instance=author) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_alternatebook_set-0-title">Title:</label>' '<input id="id_alternatebook_set-0-title" type="text" ' 'name="alternatebook_set-0-title" maxlength="100"></p>' '<p><label for="id_alternatebook_set-0-notes">Notes:</label>' '<input id="id_alternatebook_set-0-notes" type="text" ' 'name="alternatebook_set-0-notes" maxlength="100">' '<input type="hidden" name="alternatebook_set-0-author" value="1" ' 'id="id_alternatebook_set-0-author">' '<input type="hidden" name="alternatebook_set-0-book_ptr" ' 'id="id_alternatebook_set-0-book_ptr"></p>' ) data = { 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms 'alternatebook_set-0-title': 'Flowers of Evil', 'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal' } formset = AuthorBooksFormSet3(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.title, 'Flowers of Evil') self.assertEqual(book1.notes, 'English translation of Les Fleurs du Mal') @skipUnlessDBFeature('supports_partially_nullable_unique_constraints') def test_inline_formsets_with_nullable_unique_together(self): # Test inline formsets where the inline-edited object has a # unique_together constraint with a nullable member AuthorBooksFormSet4 = inlineformset_factory( Author, BookWithOptionalAltEditor, can_delete=False, extra=2, fields="__all__" ) author = Author.objects.create(pk=1, name='Charles Baudelaire') data = { 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithoptionalalteditor_set-0-author': '1', 'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal', 'bookwithoptionalalteditor_set-1-author': '1', 'bookwithoptionalalteditor_set-1-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet4(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.author_id, 1) self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.author_id, 1) self.assertEqual(book2.title, 'Les Fleurs du Mal') def test_inline_formsets_with_custom_save_method(self): AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil') class PoemForm(forms.ModelForm): def save(self, commit=True): # change the name to "Brooklyn Bridge" just to be a jerk. poem = super().save(commit=False) poem.name = "Brooklyn Bridge" if commit: poem.save() return poem PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm, fields="__all__") data = { 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data 'poem_set-MAX_NUM_FORMS': '', # the max number of forms 'poem_set-0-name': 'The Cloud in Trousers', 'poem_set-1-name': 'I', 'poem_set-2-name': '', } poet = Poet.objects.create(name='Vladimir Mayakovsky') formset = PoemFormSet(data=data, instance=poet) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) poem1, poem2 = saved self.assertEqual(poem1.name, 'Brooklyn Bridge') self.assertEqual(poem2.name, 'Brooklyn Bridge') # We can provide a custom queryset to our InlineFormSet: custom_qs = Book.objects.order_by('-title') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertEqual(len(formset.forms), 5) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label>' '<input id="id_book_set-0-title" type="text" name="book_set-0-title" ' 'value="Les Paradis Artificiels" maxlength="100">' '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">' '<input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" ' 'value="Les Fleurs du Mal" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" ' 'value="Flowers of Evil" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id"></p>' ) self.assertHTMLEqual( formset.forms[3].as_p(), '<p><label for="id_book_set-3-title">Title:</label>' '<input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100">' '<input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author">' '<input type="hidden" name="book_set-3-id" id="id_book_set-3-id"></p>' ) self.assertHTMLEqual( formset.forms[4].as_p(), '<p><label for="id_book_set-4-title">Title:</label>' '<input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100">' '<input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author">' '<input type="hidden" name="book_set-4-id" id="id_book_set-4-id"></p>' ) data = { 'book_set-TOTAL_FORMS': '5', # the number of forms rendered 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Paradis Artificiels', 'book_set-1-id': str(book2.id), 'book_set-1-title': 'Les Fleurs du Mal', 'book_set-2-id': str(book3.id), 'book_set-2-title': 'Flowers of Evil', 'book_set-3-title': 'Revue des deux mondes', 'book_set-4-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) custom_qs = Book.objects.filter(title__startswith='F') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label>' '<input id="id_book_set-0-title" type="text" name="book_set-0-title" ' 'value="Flowers of Evil" maxlength="100">' '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">' '<input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>' ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book3.id), 'book_set-0-title': 'Flowers of Evil', 'book_set-1-title': 'Revue des deux mondes', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) def test_inline_formsets_with_custom_save_method_related_instance(self): """ The ModelForm.save() method should be able to access the related object if it exists in the database (#24395). """ class PoemForm2(forms.ModelForm): def save(self, commit=True): poem = super().save(commit=False) poem.name = "%s by %s" % (poem.name, poem.poet.name) if commit: poem.save() return poem PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm2, fields="__all__") data = { 'poem_set-TOTAL_FORMS': '1', 'poem_set-INITIAL_FORMS': '0', 'poem_set-MAX_NUM_FORMS': '', 'poem_set-0-name': 'Le Lac', } poet = Poet() formset = PoemFormSet(data=data, instance=poet) self.assertTrue(formset.is_valid()) # The Poet instance is saved after the formset instantiation. This # happens in admin's changeform_view() when adding a new object and # some inlines in the same request. poet.name = 'Lamartine' poet.save() poem = formset.save()[0] self.assertEqual(poem.name, 'Le Lac by Lamartine') def test_inline_formsets_with_wrong_fk_name(self): """ Regression for #23451 """ message = "fk_name 'title' is not a ForeignKey to 'model_formsets.Author'." with self.assertRaisesMessage(ValueError, message): inlineformset_factory(Author, Book, fields="__all__", fk_name='title') def test_custom_pk(self): # We need to ensure that it is displayed CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey, fields="__all__") formset = CustomPrimaryKeyFormSet() self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" ' 'name="form-0-my_pk" maxlength="10"></p>' '<p><label for="id_form-0-some_field">Some field:</label>' '<input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100"></p>' ) # Custom primary keys with ForeignKey, OneToOneField and AutoField ############ place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Owner, extra=2, can_delete=False, fields="__all__") formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label>' '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100">' '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">' '<input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label>' '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">' '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">' '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>' ) data = { 'owner_set-TOTAL_FORMS': '2', 'owner_set-INITIAL_FORMS': '0', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': '', 'owner_set-0-name': 'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner1, = saved self.assertEqual(owner1.name, 'Joe Perry') self.assertEqual(owner1.place.name, 'Giordanos') formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label>' '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100">' '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">' '<input type="hidden" name="owner_set-0-auto_id" value="%d" id="id_owner_set-0-auto_id"></p>' % owner1.auto_id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label>' '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">' '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">' '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_owner_set-2-name">Name:</label>' '<input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100">' '<input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place">' '<input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id"></p>' ) data = { 'owner_set-TOTAL_FORMS': '3', 'owner_set-INITIAL_FORMS': '1', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': str(owner1.auto_id), 'owner_set-0-name': 'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': 'Jack Berry', 'owner_set-2-auto_id': '', 'owner_set-2-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner2, = saved self.assertEqual(owner2.name, 'Jack Berry') self.assertEqual(owner2.place.name, 'Giordanos') # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose. FormSet = modelformset_factory(OwnerProfile, fields="__all__") formset = FormSet() self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-owner">Owner:</label>' '<select name="form-0-owner" id="id_form-0-owner">' '<option value="" selected>---------</option>' '<option value="%d">Joe Perry at Giordanos</option>' '<option value="%d">Jack Berry at Giordanos</option>' '</select></p>' '<p><label for="id_form-0-age">Age:</label>' '<input type="number" name="form-0-age" id="id_form-0-age" min="0"></p>' % (owner1.auto_id, owner2.auto_id) ) owner1 = Owner.objects.get(name='Joe Perry') FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False, fields="__all__") self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label>' '<input type="number" name="ownerprofile-0-age" id="id_ownerprofile-0-age" min="0">' '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>' % owner1.auto_id ) data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '0', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': '', 'ownerprofile-0-age': '54', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner1) self.assertEqual(profile1.age, 54) formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label>' '<input type="number" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" min="0">' '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>' % owner1.auto_id ) data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '1', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': str(owner1.auto_id), 'ownerprofile-0-age': '55', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner1) self.assertEqual(profile1.age, 55) def test_unique_true_enforces_max_num_one(self): # ForeignKey with unique=True should enforce max_num=1 place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Location, can_delete=False, fields="__all__") self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_location_set-0-lat">Lat:</label>' '<input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100"></p>' '<p><label for="id_location_set-0-lon">Lon:</label> ' '<input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100">' '<input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place">' '<input type="hidden" name="location_set-0-id" id="id_location_set-0-id"></p>' ) def test_foreign_keys_in_parents(self): self.assertEqual(type(_get_foreign_key(Restaurant, Owner)), models.ForeignKey) self.assertEqual(type(_get_foreign_key(MexicanRestaurant, Owner)), models.ForeignKey) def test_unique_validation(self): FormSet = modelformset_factory(Product, fields="__all__", extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) product1, = saved self.assertEqual(product1.slug, 'car-red') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'slug': ['Product with this Slug already exists.']}]) def test_modelformset_validate_max_flag(self): # If validate_max is set and max_num is less than TOTAL_FORMS in the # data, then throw an exception. 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 = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '2', # should be ignored 'form-0-price': '12.00', 'form-0-quantity': '1', 'form-1-price': '24.00', 'form-1-quantity': '2', } FormSet = modelformset_factory(Price, fields="__all__", extra=1, max_num=1, validate_max=True) formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or fewer forms.']) # Now test the same thing without the validate_max flag to ensure # default behavior is unchanged FormSet = modelformset_factory(Price, fields="__all__", extra=1, max_num=1) formset = FormSet(data) self.assertTrue(formset.is_valid()) def test_unique_together_validation(self): FormSet = modelformset_factory(Price, fields="__all__", extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) price1, = saved self.assertEqual(price1.price, Decimal('12.00')) self.assertEqual(price1.quantity, 1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': ['Price with this Price and Quantity already exists.']}]) def test_unique_together_with_inlineformset_factory(self): # Also see bug #8882. repository = Repository.objects.create(name='Test Repo') FormSet = inlineformset_factory(Repository, Revision, extra=1, fields="__all__") data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) revision1, = saved self.assertEqual(revision1.repository, repository) self.assertEqual(revision1.revision, '146239817507f148d448db38840db7c3cbf47c76') # attempt to save the same revision against the same repo. data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': ['Revision with this Repository and Revision already exists.']}]) # unique_together with inlineformset_factory with overridden form fields # Also see #9494 FormSet = inlineformset_factory(Repository, Revision, fields=('revision',), extra=1) data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) def test_callable_defaults(self): # Use of callable defaults (see bug #7975). person = Person.objects.create(name='Ringo') FormSet = inlineformset_factory(Person, Membership, can_delete=False, extra=1, fields="__all__") formset = FormSet(instance=person) # Django will render a hidden field for model fields that have a callable # default. This is required to ensure the value is tested for change correctly # when determine what extra forms have changed to save. self.assertEqual(len(formset.forms), 1) # this formset only has one form form = formset.forms[0] now = form.fields['date_joined'].initial() result = form.as_p() result = re.sub(r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?', '__DATETIME__', result) self.assertHTMLEqual( result, '<p><label for="id_membership_set-0-date_joined">Date joined:</label>' '<input type="text" name="membership_set-0-date_joined" ' 'value="__DATETIME__" id="id_membership_set-0-date_joined">' '<input type="hidden" name="initial-membership_set-0-date_joined" value="__DATETIME__" ' 'id="initial-membership_set-0-id_membership_set-0-date_joined"></p>' '<p><label for="id_membership_set-0-karma">Karma:</label>' '<input type="number" name="membership_set-0-karma" id="id_membership_set-0-karma">' '<input type="hidden" name="membership_set-0-person" value="%d" id="id_membership_set-0-person">' '<input type="hidden" name="membership_set-0-id" id="id_membership_set-0-id"></p>' % person.id) # test for validation with callable defaults. Validations rely on hidden fields data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) # now test for when the data changes one_day_later = now + datetime.timedelta(days=1) filled_data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': one_day_later.strftime('%Y-%m-%d %H:%M:%S'), 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'membership_set-0-karma': '', } formset = FormSet(filled_data, instance=person) self.assertFalse(formset.is_valid()) # now test with split datetime fields class MembershipForm(forms.ModelForm): date_joined = forms.SplitDateTimeField(initial=now) class Meta: model = Membership fields = "__all__" def __init__(self, **kwargs): super().__init__(**kwargs) self.fields['date_joined'].widget = forms.SplitDateTimeWidget() FormSet = inlineformset_factory( Person, Membership, form=MembershipForm, can_delete=False, extra=1, fields="__all__", ) data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined_0': now.strftime('%Y-%m-%d'), 'membership_set-0-date_joined_1': now.strftime('%H:%M:%S'), 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) def test_inlineformset_factory_with_null_fk(self): # inlineformset_factory tests with fk having null=True. see #9462. # create some data that will exhibit the issue team = Team.objects.create(name="Red Vipers") Player(name="Timmy").save() Player(name="Bobby", team=team).save() PlayerInlineFormSet = inlineformset_factory(Team, Player, fields="__all__") formset = PlayerInlineFormSet() self.assertQuerysetEqual(formset.get_queryset(), []) formset = PlayerInlineFormSet(instance=team) players = formset.get_queryset() self.assertEqual(len(players), 1) player1, = players self.assertEqual(player1.team, team) self.assertEqual(player1.name, 'Bobby') def test_model_formset_with_custom_pk(self): # a formset for a Model that has a custom primary key that still needs to be # added to the formset automatically FormSet = modelformset_factory(ClassyMexicanRestaurant, fields=["tacos_are_yummy"]) self.assertEqual(sorted(FormSet().forms[0].fields), ['tacos_are_yummy', 'the_restaurant']) def test_model_formset_with_initial_model_instance(self): # has_changed should compare model instance and primary key # see #18898 FormSet = modelformset_factory(Poem, fields='__all__') john_milton = Poet(name="John Milton") john_milton.save() data = { 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-name': '', 'form-0-poet': str(john_milton.id), } formset = FormSet(initial=[{'poet': john_milton}], data=data) self.assertFalse(formset.extra_forms[0].has_changed()) def test_model_formset_with_initial_queryset(self): # has_changed should work with queryset and list of pk's # see #18898 FormSet = modelformset_factory(AuthorMeeting, fields='__all__') Author.objects.create(pk=1, name='Charles Baudelaire') data = { 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-name': '', 'form-0-created': '', 'form-0-authors': list(Author.objects.values_list('id', flat=True)), } formset = FormSet(initial=[{'authors': Author.objects.all()}], data=data) self.assertFalse(formset.extra_forms[0].has_changed()) def test_prevent_duplicates_from_with_the_same_formset(self): FormSet = modelformset_factory(Product, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'red_car', 'form-1-slug': 'red_car', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for slug.']) FormSet = modelformset_factory(Price, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-price': '25', 'form-0-quantity': '7', 'form-1-price': '25', 'form-1-quantity': '7', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for price and quantity, which must be unique.'] ) # Only the price field is specified, this should skip any unique checks since # the unique_together is not fulfilled. This will fail with a KeyError if broken. FormSet = modelformset_factory(Price, fields=("price",), extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '24', 'form-1-price': '24', } formset = FormSet(data) self.assertTrue(formset.is_valid()) FormSet = inlineformset_factory(Author, Book, extra=0, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') Book.objects.create(pk=3, author=author, title='Flowers of Evil') book_ids = author.book_set.order_by('id').values_list('id', flat=True) data = { 'book_set-TOTAL_FORMS': '2', 'book_set-INITIAL_FORMS': '2', 'book_set-MAX_NUM_FORMS': '', 'book_set-0-title': 'The 2008 Election', 'book_set-0-author': str(author.id), 'book_set-0-id': str(book_ids[0]), 'book_set-1-title': 'The 2008 Election', 'book_set-1-author': str(author.id), 'book_set-1-id': str(book_ids[1]), } formset = FormSet(data=data, instance=author) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for title.']) self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}]) FormSet = modelformset_factory(Post, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'blah', 'form-0-slug': 'Morning', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-01-01' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for title which must be unique for the date in posted.'] ) self.assertEqual( formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}] ) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for slug which must be unique for the year in posted.'] ) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'rawr', 'form-0-posted': '2008-08-01', 'form-1-title': 'blah', 'form-1-slug': 'Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for subtitle which must be unique for the month in posted.'] ) def test_prevent_change_outer_model_and_create_invalid_data(self): author = Author.objects.create(name='Charles') other_author = Author.objects.create(name='Walt') AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-MAX_NUM_FORMS': '', 'form-0-id': str(author.id), 'form-0-name': 'Charles', 'form-1-id': str(other_author.id), # A model not in the formset's queryset. 'form-1-name': 'Changed name', } # This formset is only for Walt Whitman and shouldn't accept data for # other_author. formset = AuthorFormSet(data=data, queryset=Author.objects.filter(id__in=(author.id,))) self.assertTrue(formset.is_valid()) formset.save() # The name of other_author shouldn't be changed and new models aren't # created. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Charles>', '<Author: Walt>']) def test_validation_without_id(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-name': 'Charles', } formset = AuthorFormSet(data) self.assertEqual( formset.errors, [{'id': ['This field is required.']}], ) def test_validation_with_child_model_without_id(self): BetterAuthorFormSet = modelformset_factory(BetterAuthor, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-name': 'Charles', 'form-0-write_speed': '10', } formset = BetterAuthorFormSet(data) self.assertEqual( formset.errors, [{'author_ptr': ['This field is required.']}], ) def test_validation_with_invalid_id(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-id': 'abc', 'form-0-name': 'Charles', } formset = AuthorFormSet(data) self.assertEqual( formset.errors, [{'id': ['Select a valid choice. That choice is not one of the available choices.']}], ) def test_validation_with_nonexistent_id(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-id': '12345', 'form-0-name': 'Charles', } formset = AuthorFormSet(data) self.assertEqual( formset.errors, [{'id': ['Select a valid choice. That choice is not one of the available choices.']}], ) class TestModelFormsetOverridesTroughFormMeta(TestCase): def test_modelformset_factory_widgets(self): widgets = { 'name': forms.TextInput(attrs={'class': 'poet'}) } PoetFormSet = modelformset_factory(Poet, fields="__all__", widgets=widgets) form = PoetFormSet.form() self.assertHTMLEqual( "%s" % form['name'], '<input id="id_name" maxlength="100" type="text" class="poet" name="name" required>' ) def test_inlineformset_factory_widgets(self): widgets = { 'title': forms.TextInput(attrs={'class': 'book'}) } BookFormSet = inlineformset_factory(Author, Book, widgets=widgets, fields="__all__") form = BookFormSet.form() self.assertHTMLEqual( "%s" % form['title'], '<input class="book" id="id_title" maxlength="100" name="title" type="text" required>' ) def test_modelformset_factory_labels_overrides(self): BookFormSet = modelformset_factory(Book, fields="__all__", labels={ 'title': 'Name' }) form = BookFormSet.form() self.assertHTMLEqual(form['title'].label_tag(), '<label for="id_title">Name:</label>') def test_inlineformset_factory_labels_overrides(self): BookFormSet = inlineformset_factory(Author, Book, fields="__all__", labels={ 'title': 'Name' }) form = BookFormSet.form() self.assertHTMLEqual(form['title'].label_tag(), '<label for="id_title">Name:</label>') def test_modelformset_factory_help_text_overrides(self): BookFormSet = modelformset_factory(Book, fields="__all__", help_texts={ 'title': 'Choose carefully.' }) form = BookFormSet.form() self.assertEqual(form['title'].help_text, 'Choose carefully.') def test_inlineformset_factory_help_text_overrides(self): BookFormSet = inlineformset_factory(Author, Book, fields="__all__", help_texts={ 'title': 'Choose carefully.' }) form = BookFormSet.form() self.assertEqual(form['title'].help_text, 'Choose carefully.') def test_modelformset_factory_error_messages_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = modelformset_factory(Book, fields="__all__", error_messages={ 'title': { 'max_length': 'Title too long!!' } }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) form.full_clean() self.assertEqual(form.errors, {'title': ['Title too long!!']}) def test_inlineformset_factory_error_messages_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = inlineformset_factory(Author, Book, fields="__all__", error_messages={ 'title': { 'max_length': 'Title too long!!' } }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) form.full_clean() self.assertEqual(form.errors, {'title': ['Title too long!!']}) def test_modelformset_factory_field_class_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = modelformset_factory(Book, fields="__all__", field_classes={ 'title': forms.SlugField, }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) self.assertIs(Book._meta.get_field('title').__class__, models.CharField) self.assertIsInstance(form.fields['title'], forms.SlugField) def test_inlineformset_factory_field_class_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = inlineformset_factory(Author, Book, fields="__all__", field_classes={ 'title': forms.SlugField, }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) self.assertIs(Book._meta.get_field('title').__class__, models.CharField) self.assertIsInstance(form.fields['title'], forms.SlugField)
63afdf2fc6dc50a0b8b02aa0521f2b61da6eb103b00d168505e3a113cd93f1b5
import datetime import uuid from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name',) def __str__(self): return self.name class BetterAuthor(Author): write_speed = models.IntegerField() class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100) class Meta: unique_together = ( ('author', 'title'), ) ordering = ['id'] def __str__(self): return self.title def clean(self): # Ensure author is always accessible in clean method assert self.author.name is not None class BookWithCustomPK(models.Model): my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100) def __str__(self): return '%s: %s' % (self.my_pk, self.title) class Editor(models.Model): name = models.CharField(max_length=100) class BookWithOptionalAltEditor(models.Model): author = models.ForeignKey(Author, models.CASCADE) # Optional secondary author alt_editor = models.ForeignKey(Editor, models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=100) class Meta: unique_together = ( ('author', 'title', 'alt_editor'), ) def __str__(self): return self.title class AlternateBook(Book): notes = models.CharField(max_length=100) def __str__(self): return '%s - %s' % (self.title, self.notes) class AuthorMeeting(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) created = models.DateField(editable=False) def __str__(self): return self.name class CustomPrimaryKey(models.Model): my_pk = models.CharField(max_length=10, primary_key=True) some_field = models.CharField(max_length=100) # models for inheritance tests. class Place(models.Model): name = models.CharField(max_length=50) city = models.CharField(max_length=50) def __str__(self): return self.name class Owner(models.Model): auto_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) place = models.ForeignKey(Place, models.CASCADE) def __str__(self): return "%s at %s" % (self.name, self.place) class Location(models.Model): place = models.ForeignKey(Place, models.CASCADE, unique=True) # this is purely for testing the data doesn't matter here :) lat = models.CharField(max_length=100) lon = models.CharField(max_length=100) class OwnerProfile(models.Model): owner = models.OneToOneField(Owner, models.CASCADE, primary_key=True) age = models.PositiveIntegerField() def __str__(self): return "%s is %d" % (self.owner.name, self.age) class Restaurant(Place): serves_pizza = models.BooleanField(default=False) def __str__(self): return self.name class Product(models.Model): slug = models.SlugField(unique=True) def __str__(self): return self.slug class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() def __str__(self): return "%s for %s" % (self.quantity, self.price) class Meta: unique_together = (('price', 'quantity'),) class MexicanRestaurant(Restaurant): serves_tacos = models.BooleanField(default=False) class ClassyMexicanRestaurant(MexicanRestaurant): the_restaurant = models.OneToOneField(MexicanRestaurant, models.CASCADE, parent_link=True, primary_key=True) tacos_are_yummy = models.BooleanField(default=False) # models for testing unique_together validation when a fk is involved and # using inlineformset_factory. class Repository(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Revision(models.Model): repository = models.ForeignKey(Repository, models.CASCADE) revision = models.CharField(max_length=40) class Meta: unique_together = (("repository", "revision"),) def __str__(self): return "%s (%s)" % (self.revision, str(self.repository)) # models for testing callable defaults (see bug #7975). If you define a model # with a callable default value, you cannot rely on the initial value in a # form. class Person(models.Model): name = models.CharField(max_length=128) class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) date_joined = models.DateTimeField(default=datetime.datetime.now) karma = models.IntegerField() # models for testing a null=True fk to a parent class Team(models.Model): name = models.CharField(max_length=100) class Player(models.Model): team = models.ForeignKey(Team, models.SET_NULL, null=True) name = models.CharField(max_length=100) def __str__(self): return self.name # Models for testing custom ModelForm save methods in formsets and inline formsets class Poet(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Poem(models.Model): poet = models.ForeignKey(Poet, models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def __str__(self): return self.name # Models for testing UUID primary keys class UUIDPKParent(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class UUIDPKChild(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) parent = models.ForeignKey(UUIDPKParent, models.CASCADE) class ChildWithEditablePK(models.Model): name = models.CharField(max_length=255, primary_key=True) parent = models.ForeignKey(UUIDPKParent, models.CASCADE) class AutoPKChildOfUUIDPKParent(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(UUIDPKParent, models.CASCADE) class AutoPKParent(models.Model): name = models.CharField(max_length=255) class UUIDPKChildOfAutoPKParent(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) parent = models.ForeignKey(AutoPKParent, models.CASCADE) class ParentWithUUIDAlternateKey(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) class ChildRelatedViaAK(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(ParentWithUUIDAlternateKey, models.CASCADE, to_field='uuid')
9f011188d6470fec200c814fee851b9ebac100cd2f4551adf762eec578fe00ca
from django.forms.models import inlineformset_factory from django.test import TestCase from .models import ( AutoPKChildOfUUIDPKParent, AutoPKParent, ChildRelatedViaAK, ChildWithEditablePK, ParentWithUUIDAlternateKey, UUIDPKChild, UUIDPKChildOfAutoPKParent, UUIDPKParent, ) class InlineFormsetTests(TestCase): def test_inlineformset_factory_nulls_default_pks(self): """ #24377 - If we're adding a new object, a parent's auto-generated pk from the model field default should be ignored as it's regenerated on the save request. Tests the case where both the parent and child have a UUID primary key. """ FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields='__all__') formset = FormSet() self.assertIsNone(formset.forms[0].fields['parent'].initial) def test_inlineformset_factory_ignores_default_pks_on_submit(self): """ #24377 - Inlines with a model field default should ignore that default value to avoid triggering validation on empty forms. """ FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields='__all__') formset = FormSet({ 'uuidpkchild_set-TOTAL_FORMS': 3, 'uuidpkchild_set-INITIAL_FORMS': 0, 'uuidpkchild_set-MAX_NUM_FORMS': '', 'uuidpkchild_set-0-name': 'Foo', 'uuidpkchild_set-1-name': '', 'uuidpkchild_set-2-name': '', }) self.assertTrue(formset.is_valid()) def test_inlineformset_factory_nulls_default_pks_uuid_parent_auto_child(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID primary key and a child object with an AutoField primary key. """ FormSet = inlineformset_factory(UUIDPKParent, AutoPKChildOfUUIDPKParent, fields='__all__') formset = FormSet() self.assertIsNone(formset.forms[0].fields['parent'].initial) def test_inlineformset_factory_nulls_default_pks_auto_parent_uuid_child(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with an AutoField primary key and a child object with a UUID primary key. """ FormSet = inlineformset_factory(AutoPKParent, UUIDPKChildOfAutoPKParent, fields='__all__') formset = FormSet() self.assertIsNone(formset.forms[0].fields['parent'].initial) def test_inlineformset_factory_nulls_default_pks_child_editable_pk(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID primary key and a child object with an editable natural key for a primary key. """ FormSet = inlineformset_factory(UUIDPKParent, ChildWithEditablePK, fields='__all__') formset = FormSet() self.assertIsNone(formset.forms[0].fields['parent'].initial) def test_inlineformset_factory_nulls_default_pks_alternate_key_relation(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID alternate key and a child object that relates to that alternate key. """ FormSet = inlineformset_factory(ParentWithUUIDAlternateKey, ChildRelatedViaAK, fields='__all__') formset = FormSet() self.assertIsNone(formset.forms[0].fields['parent'].initial)
2258cc2cd5b22d8bb4d024abea401a0b22a72a3188e81a8b2a627397572ec0ee
from django.test import TestCase from .models import Parent class MutuallyReferentialTests(TestCase): def test_mutually_referential(self): # Create a Parent q = Parent(name='Elizabeth') q.save() # Create some children c = q.child_set.create(name='Charles') q.child_set.create(name='Edward') # Set the best child # No assertion require here; if basic assignment and # deletion works, the test passes. q.bestchild = c q.save() q.delete()
0ddc8cf6c5abd69711fa69841fd66a0a40b51f3e8f3d86a3e266cc89a5932dab
""" Mutually referential many-to-one relationships Strings can be used instead of model literals to set up "lazy" relations. """ from django.db import models class Parent(models.Model): name = models.CharField(max_length=100) # Use a simple string for forward declarations. bestchild = models.ForeignKey("Child", models.SET_NULL, null=True, related_name="favored_by") class Child(models.Model): name = models.CharField(max_length=100) # You can also explicitly specify the related app. parent = models.ForeignKey("mutually_referential.Parent", models.CASCADE)
eb46a0e93f911fd017d1d79ba9560f7907d2fe83235cd7ace9af6fc71bc3a244
import datetime from copy import deepcopy from django.core.exceptions import FieldError, MultipleObjectsReturned from django.db import models, transaction from django.db.utils import IntegrityError from django.test import TestCase from django.utils.translation import gettext_lazy from .models import ( Article, Category, Child, City, District, First, Parent, Record, Relation, Reporter, School, Student, Third, ToFieldChild, ) class ManyToOneTests(TestCase): def setUp(self): # Create a few Reporters. self.r = Reporter(first_name='John', last_name='Smith', email='[email protected]') self.r.save() self.r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]') self.r2.save() # Create an Article. self.a = Article(headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=self.r) self.a.save() def test_get(self): # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) self.assertEqual((r.first_name, self.r.last_name), ('John', 'Smith')) def test_create(self): # You can also instantiate an Article by passing the Reporter's ID # instead of a Reporter object. a3 = Article(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) a3.save() self.assertEqual(a3.reporter.id, self.r.id) # Similarly, the reporter ID can be a string. a4 = Article(headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id)) a4.save() self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>") def test_add(self): # Create an Article via the Reporter object. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.assertEqual(repr(new_article), "<Article: John's second story>") self.assertEqual(new_article.reporter.id, self.r.id) # Create a new article, and add it to the article set. new_article2 = Article(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) msg = "<Article: Paul's story> instance isn't saved. Use bulk=False or save the object first." with self.assertRaisesMessage(ValueError, msg): self.r.article_set.add(new_article2) self.r.article_set.add(new_article2, bulk=False) self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>"] ) # Add the same article to a different article set - check that it moves. self.r2.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r2.id) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Adding an object of the wrong type raises TypeError. with transaction.atomic(): with self.assertRaisesMessage(TypeError, "'Article' instance expected, got <Reporter:"): self.r.article_set.add(self.r2) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) def test_set(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Assign the article to the reporter. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again. self.r2.article_set.set([new_article, new_article2]) self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual( self.r2.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>"] ) # Funny case - because the ForeignKey cannot be null, # existing members of the set must remain. self.r.article_set.set([new_article]) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) def test_reverse_assignment_deprecation(self): msg = ( "Direct assignment to the reverse side of a related set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.r2.article_set = [] def test_assign(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Assign the article to the reporter directly using the descriptor. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again using set() method. self.r2.article_set.set([new_article, new_article2]) self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual( self.r2.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>"] ) # Because the ForeignKey cannot be null, existing members of the set # must remain. self.r.article_set.set([new_article]) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Reporter cannot be null - there should not be a clear or remove method self.assertFalse(hasattr(self.r2.article_set, 'remove')) self.assertFalse(hasattr(self.r2.article_set, 'clear')) def test_selects(self): self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Reporter objects have access to their related Article objects. self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='This'), ["<Article: This is a test>"]) self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r2.article_set.count(), 1) # Get articles by id self.assertQuerysetEqual(Article.objects.filter(id__exact=self.a.id), ["<Article: This is a test>"]) self.assertQuerysetEqual(Article.objects.filter(pk=self.a.id), ["<Article: This is a test>"]) # Query on an article property self.assertQuerysetEqual(Article.objects.filter(headline__startswith='This'), ["<Article: This is a test>"]) # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want. There's no limit. # Find all Articles for any Reporter whose first name is "John". self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John'), ["<Article: John's second story>", "<Article: This is a test>"] ) # Implied __exact also works self.assertQuerysetEqual( Article.objects.filter(reporter__first_name='John'), ["<Article: John's second story>", "<Article: This is a test>"] ) # Query twice over the related field. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith'), ["<Article: John's second story>", "<Article: This is a test>"] ) # The underlying query only makes one join when a related table is referenced twice. queryset = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') self.assertNumQueries(1, list, queryset) self.assertEqual(queryset.query.get_compiler(queryset.db).as_sql()[0].count('INNER JOIN'), 1) # The automatically joined table has a predictable name. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John').extra( where=["many_to_one_reporter.last_name='Smith'"]), ["<Article: John's second story>", "<Article: This is a test>"] ) # ... and should work fine with the string that comes out of forms.Form.cleaned_data self.assertQuerysetEqual( (Article.objects .filter(reporter__first_name__exact='John') .extra(where=["many_to_one_reporter.last_name='%s'" % 'Smith'])), ["<Article: John's second story>", "<Article: This is a test>"] ) # Find all Articles for a Reporter. # Use direct ID check, pk check, and object comparison self.assertQuerysetEqual( Article.objects.filter(reporter__id__exact=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__pk=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) # You can also use a queryset instead of a literal list of instances. # The queryset must be reduced to a list of values using values(), # then converted into a query self.assertQuerysetEqual( Article.objects.filter( reporter__in=Reporter.objects.filter(first_name='John').values('pk').query ).distinct(), [ "<Article: John's second story>", "<Article: This is a test>", ]) def test_reverse_selects(self): a3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) john_smith = ["<Reporter: John Smith>"] # Reporters can be queried self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(pk=self.r.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(first_name__startswith='John'), john_smith) # Reporters can query in opposite direction of ForeignKey definition self.assertQuerysetEqual(Reporter.objects.filter(article__id__exact=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__pk=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a, a3]).distinct(), john_smith) self.assertQuerysetEqual( Reporter.objects.filter(article__headline__startswith='T'), ["<Reporter: John Smith>", "<Reporter: John Smith>"], ordered=False ) self.assertQuerysetEqual(Reporter.objects.filter(article__headline__startswith='T').distinct(), john_smith) # Counting in the opposite direction works in conjunction with distinct() self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').count(), 2) self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').distinct().count(), 1) # Queries can go round in circles. self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John'), [ "<Reporter: John Smith>", "<Reporter: John Smith>", "<Reporter: John Smith>", ], ordered=False ) self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct(), john_smith ) self.assertQuerysetEqual(Reporter.objects.filter(article__reporter__exact=self.r).distinct(), john_smith) # Implied __exact also works. self.assertQuerysetEqual(Reporter.objects.filter(article__reporter=self.r).distinct(), john_smith) # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) d = {'reporter__first_name': 'John', 'reporter__last_name': 'Smith'} qs = Article.objects.filter( reporter=self.r, ).distinct().order_by().values('reporter__first_name', 'reporter__last_name') self.assertEqual([d], list(qs)) def test_select_related(self): # Article.objects.select_related().dates() works properly when there # are multiple Articles with the same date but different foreign-key # objects (Reporters). r1 = Reporter.objects.create(first_name='Mike', last_name='Royko', email='[email protected]') r2 = Reporter.objects.create(first_name='John', last_name='Kass', email='[email protected]') Article.objects.create(headline='First', pub_date=datetime.date(1980, 4, 23), reporter=r1) Article.objects.create(headline='Second', pub_date=datetime.date(1980, 4, 23), reporter=r2) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'day')), [datetime.date(1980, 4, 23), datetime.date(2005, 7, 27)] ) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'month')), [datetime.date(1980, 4, 1), datetime.date(2005, 7, 1)] ) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'year')), [datetime.date(1980, 1, 1), datetime.date(2005, 1, 1)] ) def test_delete(self): self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) Article.objects.create(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) # If you delete a reporter, his articles will be deleted. self.assertQuerysetEqual( Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Paul's story>", "<Article: Third article>", "<Article: This is a test>", ] ) self.assertQuerysetEqual( Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>", "<Reporter: Paul Jones>"] ) self.r2.delete() self.assertQuerysetEqual( Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Third article>", "<Article: This is a test>", ] ) self.assertQuerysetEqual(Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>"]) # You can delete using a JOIN in the query. Reporter.objects.filter(article__headline__startswith='This').delete() self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Article.objects.all(), []) def test_explicit_fk(self): # Create a new Article with get_or_create using an explicit value # for a ForeignKey. a2, created = Article.objects.get_or_create( headline="John's second test", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r.id, ) self.assertTrue(created) self.assertEqual(a2.reporter.id, self.r.id) # You can specify filters containing the explicit FK value. self.assertQuerysetEqual( Article.objects.filter(reporter_id__exact=self.r.id), ["<Article: John's second test>", "<Article: This is a test>"] ) # Create an Article by Paul for the same date. a3 = Article.objects.create( headline="Paul's commentary", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r2.id, ) self.assertEqual(a3.reporter.id, self.r2.id) # Get should respect explicit foreign keys as well. msg = 'get() returned more than one Article -- it returned 2!' with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(reporter_id=self.r.id) self.assertEqual( repr(a3), repr(Article.objects.get(reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7))) ) def test_deepcopy_and_circular_references(self): # Regression for #12876 -- Model methods that include queries that # recursive don't cause recursion depth problems under deepcopy. self.r.cached_query = Article.objects.filter(reporter=self.r) self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>") def test_manager_class_caching(self): r1 = Reporter.objects.create(first_name='Mike') r2 = Reporter.objects.create(first_name='John') # Same twice self.assertIs(r1.article_set.__class__, r1.article_set.__class__) # Same as each other self.assertIs(r1.article_set.__class__, r2.article_set.__class__) def test_create_relation_with_gettext_lazy(self): reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='[email protected]') lazy = gettext_lazy('test') reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10)) notlazy = str(lazy) article = reporter.article_set.get() self.assertEqual(article.headline, notlazy) def test_values_list_exception(self): expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s" reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % reporter_fields): Article.objects.values_list('reporter__notafield') article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield') def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertIs(c.parent, p) # But if we kill the cache, we get a new object. del c._state.fields_cache['parent'] self.assertIsNot(c.parent, p) # Assigning a new object results in that object getting cached immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertIs(c.parent, p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertIsNone(p.bestchild) # bestchild should still be None after saving. p.save() self.assertIsNone(p.bestchild) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertIsNone(p.bestchild) # Assigning None will not fail: Child.parent is null=False. setattr(c, "parent", None) # You also can't assign an object of the wrong type here msg = ( 'Cannot assign "<First: First object (1)>": "Child.parent" must ' 'be a "Parent" instance.' ) with self.assertRaisesMessage(ValueError, msg): setattr(c, "parent", First(id=1, second=1)) # You can assign None to Child.parent during object creation. Child(name='xyzzy', parent=None) # But when trying to save a Child with parent=None, the database will # raise IntegrityError. with self.assertRaises(IntegrityError), transaction.atomic(): Child.objects.create(name='xyzzy', parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertIs(c.parent, p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." with self.assertRaisesMessage(ValueError, msg): Child.objects.create(parent=p) msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." with self.assertRaisesMessage(ValueError, msg): ToFieldChild.objects.create(parent=p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertIsNot(c.parent, p) self.assertEqual(c.parent, p) def test_fk_to_bigautofield(self): ch = City.objects.create(name='Chicago') District.objects.create(city=ch, name='Far South') District.objects.create(city=ch, name='North') ny = City.objects.create(name='New York', id=2 ** 33) District.objects.create(city=ny, name='Brooklyn') District.objects.create(city=ny, name='Manhattan') def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name='First') c2 = Category.objects.create(name='Second') c3 = Category.objects.create(name='Third') r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r3, right=r4) Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second']) self.assertQuerysetEqual(q1, ["<Relation: First - Second>"]) q2 = Category.objects.filter(record__left_set__right__category__name='Second').order_by('name') self.assertQuerysetEqual(q2, ["<Category: First>", "<Category: Second>"]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) msg = 'Cannot assign "%r": "Child.parent" must be a "Parent" instance.' % c with self.assertRaisesMessage(ValueError, msg): Child.objects.create(name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category, models.CASCADE) self.assertEqual('id', cat.remote_field.get_related_field().name) def test_relation_unsaved(self): # The <field>_set manager does not join on Null value fields (#17541) Third.objects.create(name='Third 1') Third.objects.create(name='Third 2') th = Third(name="testing") # The object isn't saved and thus the relation field is null - we won't even # execute a query in this case. with self.assertNumQueries(0): self.assertEqual(th.child_set.count(), 0) th.save() # Now the model is saved, so we will need to execute a query. with self.assertNumQueries(1): self.assertEqual(th.child_set.count(), 0) def test_related_object(self): public_school = School.objects.create(is_public=True) public_student = Student.objects.create(school=public_school) private_school = School.objects.create(is_public=False) private_student = Student.objects.create(school=private_school) # Only one school is available via all() due to the custom default manager. self.assertSequenceEqual(School.objects.all(), [public_school]) self.assertEqual(public_student.school, public_school) # Make sure the base manager is used so that a student can still access # its related school even if the default manager doesn't normally # allow it. self.assertEqual(private_student.school, private_school) School._meta.base_manager_name = 'objects' School._meta._expire_cache() try: private_student = Student.objects.get(pk=private_student.pk) with self.assertRaises(School.DoesNotExist): private_student.school finally: School._meta.base_manager_name = None School._meta._expire_cache() def test_hasattr_related_object(self): # The exception raised on attribute access when a related object # doesn't exist should be an instance of a subclass of `AttributeError` # refs #21563 self.assertFalse(hasattr(Article(), 'reporter')) def test_clear_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) city = City.objects.prefetch_related('districts').get(id=c.id) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>']) city.districts.clear() self.assertQuerysetEqual(city.districts.all(), []) def test_remove_after_prefetch(self): c = City.objects.create(name='Musical City') d = District.objects.create(name='Ladida', city=c) city = City.objects.prefetch_related('districts').get(id=c.id) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>']) city.districts.remove(d) self.assertQuerysetEqual(city.districts.all(), []) def test_add_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) def test_set_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.set([d2]) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladidu>']) def test_add_then_remove_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) city.districts.remove(d2) self.assertEqual(city.districts.count(), 1) def test_cached_relation_invalidated_on_save(self): """ Model.save() invalidates stale ForeignKey relations after a primary key assignment. """ self.assertEqual(self.a.reporter, self.r) # caches a.reporter self.a.reporter_id = self.r2.pk self.a.save() self.assertEqual(self.a.reporter, self.r2)
52fb6ccaff218ae4cacc8348e3cdca3d2df9d74710a0b5342e4887906a9c7882
""" Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) class City(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, models.CASCADE, related_name='districts', null=True) name = models.CharField(max_length=50) def __str__(self): return self.name # If ticket #1578 ever slips back in, these models will not be able to be # created (the field names being lower-cased versions of their opposite # classes is important here). class First(models.Model): second = models.IntegerField() class Second(models.Model): first = models.ForeignKey(First, models.CASCADE, related_name='the_first') # Protect against repetition of #1839, #2415 and #2536. class Third(models.Model): name = models.CharField(max_length=20) third = models.ForeignKey('self', models.SET_NULL, null=True, related_name='child_set') class Parent(models.Model): name = models.CharField(max_length=20, unique=True) bestchild = models.ForeignKey('Child', models.SET_NULL, null=True, related_name='favored_by') class Child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent, models.CASCADE) class ToFieldChild(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, to_field='name') # Multiple paths to the same model (#7110, #7125) class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Record(models.Model): category = models.ForeignKey(Category, models.CASCADE) class Relation(models.Model): left = models.ForeignKey(Record, models.CASCADE, related_name='left_set') right = models.ForeignKey(Record, models.CASCADE, related_name='right_set') def __str__(self): return "%s - %s" % (self.left.category.name, self.right.category.name) # Test related objects visibility. class SchoolManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_public=True) class School(models.Model): is_public = models.BooleanField(default=False) objects = SchoolManager() class Student(models.Model): school = models.ForeignKey(School, models.CASCADE)
d482b8f123b8899ff557c4be9c302ff4756bb702df26fd77fcce8664e4caa681
import base64 import os import shutil import string import tempfile import unittest from datetime import timedelta from http import cookies from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessions.backends.cached_db import ( SessionStore as CacheDBSession, ) from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.file import SessionStore as FileSession from django.contrib.sessions.backends.signed_cookies import ( SessionStore as CookieSession, ) from django.contrib.sessions.exceptions import InvalidSessionKey from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.models import Session from django.contrib.sessions.serializers import ( JSONSerializer, PickleSerializer, ) from django.core import management from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.http import HttpResponse from django.test import ( RequestFactory, TestCase, ignore_warnings, override_settings, ) from django.utils import timezone from .models import SessionStore as CustomDatabaseSession class SessionTestsMixin: # This does not inherit from TestCase to avoid any tests being run with this # class, which wouldn't work, and to allow different TestCase subclasses to # be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() def tearDown(self): # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots # of runs (think buildbots) self.session.delete() def test_new_session(self): self.assertIs(self.session.modified, False) self.assertIs(self.session.accessed, False) def test_get_empty(self): self.assertIsNone(self.session.get('cat')) def test_store(self): self.session['cat'] = "dog" self.assertIs(self.session.modified, True) self.assertEqual(self.session.pop('cat'), 'dog') def test_pop(self): self.session['some key'] = 'exists' # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop('some key'), 'exists') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertIsNone(self.session.get('some key')) def test_pop_default(self): self.assertEqual(self.session.pop('some key', 'does not exist'), 'does not exist') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_pop_default_named_argument(self): self.assertEqual(self.session.pop('some key', default='does not exist'), 'does not exist') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_pop_no_default_keyerror_raised(self): with self.assertRaises(KeyError): self.session.pop('some key') def test_setdefault(self): self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar') self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) def test_update(self): self.session.update({'update key': 1}) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertEqual(self.session.get('update key', None), 1) def test_has_key(self): self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertIn('some key', self.session) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_values(self): self.assertEqual(list(self.session.values()), []) self.assertIs(self.session.accessed, True) self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.values()), [1]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_keys(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.keys()), ['x']) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_items(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [('x', 1)]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_clear(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [('x', 1)]) self.session.clear() self.assertEqual(list(self.session.items()), []) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) def test_save(self): self.session.save() self.assertIs(self.session.exists(self.session.session_key), True) def test_delete(self): self.session.save() self.session.delete(self.session.session_key) self.assertIs(self.session.exists(self.session.session_key), False) def test_flush(self): self.session['foo'] = 'bar' self.session.save() prev_key = self.session.session_key self.session.flush() self.assertIs(self.session.exists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertIsNone(self.session.session_key) self.assertIs(self.session.modified, True) self.assertIs(self.session.accessed, True) def test_cycle(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_key = self.session.session_key prev_data = list(self.session.items()) self.session.cycle_key() self.assertIs(self.session.exists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(list(self.session.items()), prev_data) def test_cycle_with_no_session_cache(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_data = self.session.items() self.session = self.backend(self.session.session_key) self.assertIs(hasattr(self.session, '_session_cache'), False) self.session.cycle_key() self.assertCountEqual(self.session.items(), prev_data) def test_save_doesnt_clear_data(self): self.session['a'] = 'b' self.session.save() self.assertEqual(self.session['a'], 'b') def test_invalid_key(self): # Submitting an invalid session key (either by guessing, or if the db has # removed the key) results in a new key being generated. try: session = self.backend('1') session.save() self.assertNotEqual(session.session_key, '1') self.assertIsNone(session.get('cat')) session.delete() finally: # Some backends leave a stale cache entry for the invalid # session key; make sure that entry is manually deleted session.delete('1') def test_session_key_empty_string_invalid(self): """Falsey values (Such as an empty string) are rejected.""" self.session._session_key = '' self.assertIsNone(self.session.session_key) def test_session_key_too_short_invalid(self): """Strings shorter than 8 characters are rejected.""" self.session._session_key = '1234567' self.assertIsNone(self.session.session_key) def test_session_key_valid_string_saved(self): """Strings of length 8 and up are accepted and stored.""" self.session._session_key = '12345678' self.assertEqual(self.session.session_key, '12345678') def test_session_key_is_read_only(self): def set_session_key(session): session.session_key = session._get_new_session_key() with self.assertRaises(AttributeError): set_session_key(self.session) # Custom session expiry def test_default_expiry(self): # A normal session has a max age equal to settings self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_custom_expiry_seconds(self): modification = timezone.now() self.session.set_expiry(10) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_timedelta(self): modification = timezone.now() # Mock timezone.now, because set_expiry calls it on this code path. original_now = timezone.now try: timezone.now = lambda: modification self.session.set_expiry(timedelta(seconds=10)) finally: timezone.now = original_now date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_datetime(self): modification = timezone.now() self.session.set_expiry(modification + timedelta(seconds=10)) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and different # set_expiry calls with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False): self.session.set_expiry(10) self.assertIs(self.session.get_expire_at_browser_close(), False) self.session.set_expiry(0) self.assertIs(self.session.get_expire_at_browser_close(), True) self.session.set_expiry(None) self.assertIs(self.session.get_expire_at_browser_close(), False) with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True): self.session.set_expiry(10) self.assertIs(self.session.get_expire_at_browser_close(), False) self.session.set_expiry(0) self.assertIs(self.session.get_expire_at_browser_close(), True) self.session.set_expiry(None) self.assertIs(self.session.get_expire_at_browser_close(), True) def test_decode(self): # Ensure we can decode what we encode data = {'a test key': 'a test value'} encoded = self.session.encode(data) self.assertEqual(self.session.decode(encoded), data) def test_decode_failure_logged_to_security(self): bad_encode = base64.b64encode(b'flaskdj:alkdjf') with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: self.assertEqual({}, self.session.decode(bad_encode)) # The failed decode is logged. self.assertIn('corrupted', cm.output[0]) def test_actual_expiry(self): # this doesn't work with JSONSerializer (serializing timedelta) with override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'): self.session = self.backend() # reinitialize after overriding settings # Regression test for #19200 old_session_key = None new_session_key = None try: self.session['foo'] = 'bar' self.session.set_expiry(-timedelta(seconds=10)) self.session.save() old_session_key = self.session.session_key # With an expiry date in the past, the session expires instantly. new_session = self.backend(self.session.session_key) new_session_key = new_session.session_key self.assertNotIn('foo', new_session) finally: self.session.delete(old_session_key) self.session.delete(new_session_key) def test_session_load_does_not_create_record(self): """ Loading an unknown session key does not create a session record. Creating session records on load is a DOS vulnerability. """ session = self.backend('someunknownkey') session.load() self.assertIsNone(session.session_key) self.assertIs(session.exists(session.session_key), False) # provided unknown key was cycled, not reused self.assertNotEqual(session.session_key, 'someunknownkey') def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self): """ Sessions shouldn't be resurrected by a concurrent request. """ # Create new session. s1 = self.backend() s1['test_data'] = 'value1' s1.save(must_create=True) # Logout in another context. s2 = self.backend(s1.session_key) s2.delete() # Modify session in first context. s1['test_data'] = 'value2' with self.assertRaises(UpdateError): # This should throw an exception as the session is deleted, not # resurrect the session. s1.save() self.assertEqual(s1.load(), {}) class DatabaseSessionTests(SessionTestsMixin, TestCase): backend = DatabaseSession session_engine = 'django.contrib.sessions.backends.db' @property def model(self): return self.backend.get_model_class() def test_session_str(self): "Session repr should be the session key." self.session['x'] = 1 self.session.save() session_key = self.session.session_key s = self.model.objects.get(session_key=session_key) self.assertEqual(str(s), session_key) def test_session_get_decoded(self): """ Test we can use Session.get_decoded to retrieve data stored in normal way """ self.session['x'] = 1 self.session.save() s = self.model.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {'x': 1}) def test_sessionmanager_save(self): """ Test SessionManager.save method """ # Create a session self.session['y'] = 1 self.session.save() s = self.model.objects.get(session_key=self.session.session_key) # Change it self.model.objects.save(s.session_key, {'y': 2}, s.expire_date) # Clear cache, so that it will be retrieved from DB del self.session._session_cache self.assertEqual(self.session['y'], 2) def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ self.assertEqual(0, self.model.objects.count()) # One object in the future self.session['foo'] = 'bar' self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session['foo'] = 'bar' other_session.set_expiry(-3600) other_session.save() # Two sessions are in the database before clearsessions... self.assertEqual(2, self.model.objects.count()) with override_settings(SESSION_ENGINE=self.session_engine): management.call_command('clearsessions') # ... and one is deleted. self.assertEqual(1, self.model.objects.count()) @override_settings(USE_TZ=True) class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests): pass class CustomDatabaseSessionTests(DatabaseSessionTests): backend = CustomDatabaseSession session_engine = 'sessions_tests.models' def test_extra_session_field(self): # Set the account ID to be picked up by a custom session storage # and saved to a custom session model database column. self.session['_auth_user_id'] = 42 self.session.save() # Make sure that the customized create_model_instance() was called. s = self.model.objects.get(session_key=self.session.session_key) self.assertEqual(s.account_id, 42) # Make the session "anonymous". self.session.pop('_auth_user_id') self.session.save() # Make sure that save() on an existing session did the right job. s = self.model.objects.get(session_key=self.session.session_key) self.assertIsNone(s.account_id) class CacheDBSessionTests(SessionTestsMixin, TestCase): backend = CacheDBSession def test_exists_searches_cache_first(self): self.session.save() with self.assertNumQueries(0): self.assertIs(self.session.exists(self.session.session_key), True) # Some backends might issue a warning @ignore_warnings(module="django.core.cache.backends.base") def test_load_overlong_key(self): self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) @override_settings(SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. with self.assertRaises(InvalidCacheBackendError): self.backend() @override_settings(USE_TZ=True) class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests): pass # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class FileSessionTests(SessionTestsMixin, unittest.TestCase): backend = FileSession def setUp(self): # Do file session tests in an isolated directory, and kill it after we're done. self.original_session_file_path = settings.SESSION_FILE_PATH self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp() # Reset the file session backend's internal caches if hasattr(self.backend, '_storage_path'): del self.backend._storage_path super().setUp() def tearDown(self): super().tearDown() settings.SESSION_FILE_PATH = self.original_session_file_path shutil.rmtree(self.temp_session_store) @override_settings( SESSION_FILE_PATH='/if/this/directory/exists/you/have/a/weird/computer', ) def test_configuration_check(self): del self.backend._storage_path # Make sure the file backend checks for a good storage dir with self.assertRaises(ImproperlyConfigured): self.backend() def test_invalid_key_backslash(self): # Ensure we don't allow directory-traversal. # This is tested directly on _key_to_file, as load() will swallow # a SuspiciousOperation in the same way as an IOError - by creating # a new session, making it unclear whether the slashes were detected. with self.assertRaises(InvalidSessionKey): self.backend()._key_to_file("a\\b\\c") def test_invalid_key_forwardslash(self): # Ensure we don't allow directory-traversal with self.assertRaises(InvalidSessionKey): self.backend()._key_to_file("a/b/c") @override_settings( SESSION_ENGINE="django.contrib.sessions.backends.file", SESSION_COOKIE_AGE=0, ) def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ storage_path = self.backend._get_storage_path() file_prefix = settings.SESSION_COOKIE_NAME def count_sessions(): return len([ session_file for session_file in os.listdir(storage_path) if session_file.startswith(file_prefix) ]) self.assertEqual(0, count_sessions()) # One object in the future self.session['foo'] = 'bar' self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session['foo'] = 'bar' other_session.set_expiry(-3600) other_session.save() # One object in the present without an expiry (should be deleted since # its modification time + SESSION_COOKIE_AGE will be in the past when # clearsessions runs). other_session2 = self.backend() other_session2['foo'] = 'bar' other_session2.save() # Three sessions are in the filesystem before clearsessions... self.assertEqual(3, count_sessions()) management.call_command('clearsessions') # ... and two are deleted. self.assertEqual(1, count_sessions()) class CacheSessionTests(SessionTestsMixin, unittest.TestCase): backend = CacheSession # Some backends might issue a warning @ignore_warnings(module="django.core.cache.backends.base") def test_load_overlong_key(self): self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) def test_default_cache(self): self.session.save() self.assertIsNotNone(caches['default'].get(self.session.cache_key)) @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'sessions': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'session', }, }, SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): # Re-initialize the session backend to make use of overridden settings. self.session = self.backend() self.session.save() self.assertIsNone(caches['default'].get(self.session.cache_key)) self.assertIsNotNone(caches['sessions'].get(self.session.cache_key)) def test_create_and_save(self): self.session = self.backend() self.session.create() self.session.save() self.assertIsNotNone(caches['default'].get(self.session.cache_key)) class SessionMiddlewareTests(TestCase): @override_settings(SESSION_COOKIE_SECURE=True) def test_secure_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True) @override_settings(SESSION_COOKIE_HTTPONLY=True) def test_httponly_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], True) self.assertIn( cookies.Morsel._reserved['httponly'], str(response.cookies[settings.SESSION_COOKIE_NAME]) ) @override_settings(SESSION_COOKIE_SAMESITE='Strict') def test_samesite_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse() middleware = SessionMiddleware() middleware.process_request(request) request.session['hello'] = 'world' response = middleware.process_response(request, response) self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict') @override_settings(SESSION_COOKIE_HTTPONLY=False) def test_no_httponly_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '') self.assertNotIn( cookies.Morsel._reserved['httponly'], str(response.cookies[settings.SESSION_COOKIE_NAME]) ) def test_session_save_on_500(self): request = RequestFactory().get('/') response = HttpResponse('Horrible error') response.status_code = 500 middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) # The value wasn't saved above. self.assertNotIn('hello', request.session.load()) def test_session_update_error_redirect(self): path = '/foo/' request = RequestFactory().get(path) response = HttpResponse() middleware = SessionMiddleware() request.session = DatabaseSession() request.session.save(must_create=True) request.session.delete() msg = ( "The request's session was deleted before the request completed. " "The user may have logged out in a concurrent request, for example." ) with self.assertRaisesMessage(SuspiciousOperation, msg): # Handle the response through the middleware. It will try to save # the deleted session which will cause an UpdateError that's caught # and raised as a SuspiciousOperation. middleware.process_response(request, response) def test_session_delete_on_end(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header looks like: # Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/ self.assertEqual( 'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; ' 'Max-Age=0; Path=/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]) ) @override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/') def test_session_delete_on_end_with_custom_domain_and_path(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header with a custom domain and path looks like: # Set-Cookie: sessionid=; Domain=.example.local; # expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; # Path=/example/ self.assertEqual( 'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, ' '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]) ) def test_flush_empty_without_session_cookie_doesnt_set_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # A cookie should not be set. self.assertEqual(response.cookies, {}) # The session is accessed so "Vary: Cookie" should be set. self.assertEqual(response['Vary'], 'Cookie') def test_empty_session_saved(self): """ If a session is emptied of data but still has a key, it should still be updated. """ request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Set a session key and some data. middleware.process_request(request) request.session['foo'] = 'bar' # Handle the response through the middleware. response = middleware.process_response(request, response) self.assertEqual(tuple(request.session.items()), (('foo', 'bar'),)) # A cookie should be set, along with Vary: Cookie. self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Empty the session data. del request.session['foo'] # Handle the response through the middleware. response = HttpResponse('Session test') response = middleware.process_response(request, response) self.assertEqual(dict(request.session.values()), {}) session = Session.objects.get(session_key=request.session.session_key) self.assertEqual(session.get_decoded(), {}) # While the session is empty, it hasn't been flushed so a cookie should # still be set, along with Vary: Cookie. self.assertGreater(len(request.session.session_key), 8) self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class CookieSessionTests(SessionTestsMixin, unittest.TestCase): backend = CookieSession def test_save(self): """ This test tested exists() in the other session backends, but that doesn't make sense for us. """ pass def test_cycle(self): """ This test tested cycle_key() which would create a new session key for the same session data. But we can't invalidate previously signed cookies (other than letting them expire naturally) so testing for this behavior is meaningless. """ pass @unittest.expectedFailure def test_actual_expiry(self): # The cookie backend doesn't handle non-default expiry dates, see #19201 super().test_actual_expiry() def test_unpickling_exception(self): # signed_cookies backend should handle unpickle exceptions gracefully # by creating a new session self.assertEqual(self.session.serializer, JSONSerializer) self.session.save() self.session.serializer = PickleSerializer self.session.load() @unittest.skip("Cookie backend doesn't have an external store to create records in.") def test_session_load_does_not_create_record(self): pass @unittest.skip("CookieSession is stored in the client and there is no way to query it.") def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self): pass
9552df03b67e0337b06ac226fd4795cab502ac0692993c1068e16ec14b0602dc
""" This custom Session model adds an extra column to store an account ID. In real-world applications, it gives you the option of querying the database for all active sessions for a particular account. """ from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models class CustomSession(AbstractBaseSession): """ A session model with a column for an account ID. """ account_id = models.IntegerField(null=True, db_index=True) @classmethod def get_session_store_class(cls): return SessionStore class SessionStore(DBStore): """ A database session store, that handles updating the account ID column inside the custom session model. """ @classmethod def get_model_class(cls): return CustomSession def create_model_instance(self, data): obj = super().create_model_instance(data) try: account_id = int(data.get('_auth_user_id')) except (ValueError, TypeError): account_id = None obj.account_id = account_id return obj