hash
stringlengths
64
64
content
stringlengths
0
1.51M
c7adefb67f2cbcf78b40a2bad8d79113eba5249af4379e3548022903f1db7471
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' # "%d. %b %Y", # '25. okt 2006' # "%d %b %Y", # '25 okt 2006' # "%d. %b. %Y", # '25. okt. 2006' # "%d %b. %Y", # '25 okt. 2006' # "%d. %B %Y", # '25. oktober 2006' # "%d %B %Y", # '25 oktober 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
14cd4c9cb84451a07c39ee7752b588e1c8d157d35a705cdef14ee33059471800
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' # 25 Ottobre 2006 TIME_FORMAT = 'H:i' # 14:30 DATETIME_FORMAT = 'l d F Y H:i' # Mercoledì 25 Ottobre 2006 14:30 YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006 MONTH_DAY_FORMAT = 'j F' # 25 Ottobre SHORT_DATE_FORMAT = 'd/m/Y' # 25/12/2009 SHORT_DATETIME_FORMAT = 'd/m/Y H:i' # 25/10/2009 14:30 FIRST_DAY_OF_WEEK = 1 # Lunedì # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%Y/%m/%d', # '2006/10/25' '%d-%m-%Y', # '25-10-2006' '%Y-%m-%d', # '2006-10-25' '%d-%m-%y', # '25-10-06' '%d/%m/%y', # '25/10/06' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d-%m-%Y %H:%M:%S', # '25-10-2006 14:30:59' '%d-%m-%Y %H:%M:%S.%f', # '25-10-2006 14:30:59.000200' '%d-%m-%Y %H:%M', # '25-10-2006 14:30' '%d-%m-%y %H:%M:%S', # '25-10-06 14:30:59' '%d-%m-%y %H:%M:%S.%f', # '25-10-06 14:30:59.000200' '%d-%m-%y %H:%M', # '25-10-06 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
1c3ef001c080825a3156b5493abe5e11dce44d328a181fafe26bda4e7992c945
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'G:i' DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\e\s G:i' YEAR_MONTH_FORMAT = r'F \d\e\l Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y G:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '31/12/2009' '%d/%m/%y', # '31/12/09' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S.%f', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M:%S.%f', '%d/%m/%y %H:%M', ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
e2b119d7c7db0accf44b8530d84a5684e986adb1314ba65bd0a857c5e358dc89
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' # '25 Hydref 2006' TIME_FORMAT = 'P' # '2:30 y.b.' DATETIME_FORMAT = 'j F Y, P' # '25 Hydref 2006, 2:30 y.b.' YEAR_MONTH_FORMAT = 'F Y' # 'Hydref 2006' MONTH_DAY_FORMAT = 'j F' # '25 Hydref' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 y.b.' FIRST_DAY_OF_WEEK = 1 # 'Dydd Llun' # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
1fe43f022d5d130cce578c04abc238a4985cf6595adcda6bdd1a04d17a2f6dde
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j N Y' DATETIME_FORMAT = "j N Y, G.i" TIME_FORMAT = 'G.i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y G.i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d-%m-%Y', # '25-10-2009' '%d/%m/%Y', # '25/10/2009' '%d-%m-%y', # '25-10-09' '%d/%m/%y', # '25/10/09' '%d %b %Y', # '25 Oct 2006', '%d %B %Y', # '25 October 2006' '%m/%d/%y', # '10/25/06' '%m/%d/%Y', # '10/25/2009' ] TIME_INPUT_FORMATS = [ '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ] DATETIME_INPUT_FORMATS = [ '%d-%m-%Y %H.%M.%S', # '25-10-2009 14.30.59' '%d-%m-%Y %H.%M.%S.%f', # '25-10-2009 14.30.59.000200' '%d-%m-%Y %H.%M', # '25-10-2009 14.30' '%d-%m-%y %H.%M.%S', # '25-10-09' 14.30.59' '%d-%m-%y %H.%M.%S.%f', # '25-10-09' 14.30.59.000200' '%d-%m-%y %H.%M', # '25-10-09' 14.30' '%m/%d/%y %H.%M.%S', # '10/25/06 14.30.59' '%m/%d/%y %H.%M.%S.%f', # '10/25/06 14.30.59.000200' '%m/%d/%y %H.%M', # '10/25/06 14.30' '%m/%d/%Y %H.%M.%S', # '25/10/2009 14.30.59' '%m/%d/%Y %H.%M.%S.%f', # '25/10/2009 14.30.59.000200' '%m/%d/%Y %H.%M', # '25/10/2009 14.30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
952d11a0acec0eb9ad9a9f3911e46b8dbfdc69e69380a322dbd3a0bf40ed08d8
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j M Y' # '25 Oct 2006' TIME_FORMAT = 'P' # '2:30 p.m.' DATETIME_FORMAT = 'j M Y, P' # '25 Oct 2006, 2:30 p.m.' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'j F' # '25 October' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 p.m.' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' # "%b %d %Y", # 'Oct 25 2006' # "%b %d, %Y", # 'Oct 25, 2006' # "%d %b %Y", # '25 Oct 2006' # "%d %b, %Y", # '25 Oct, 2006' # "%B %d %Y", # 'October 25 2006' # "%B %d, %Y", # 'October 25, 2006' # "%d %B %Y", # '25 October 2006' # "%d %B, %Y", # '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
c83490120b7d91cfd7c77aacc118488360eb79a068f017410a5cd886840a6857
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd/m/Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'd/m/Y P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' '%Y-%m-%d', # '2006-10-25' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
492547b1829168f89db2af941dddda20ec47e5f2419d87ba759b8eb692076bd2
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'Y \m. E j \d.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'Y \m. E j \d., H:i' YEAR_MONTH_FORMAT = r'Y \m. F' MONTH_DAY_FORMAT = r'E j \d.' SHORT_DATE_FORMAT = 'Y-m-d' SHORT_DATETIME_FORMAT = 'Y-m-d H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' ] TIME_INPUT_FORMATS = [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' '%H.%M.%S', # '14.30.59' '%H.%M.%S.%f', # '14.30.59.000200' '%H.%M', # '14.30' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y %H.%M.%S', # '25.10.06 14.30.59' '%d.%m.%y %H.%M.%S.%f', # '25.10.06 14.30.59.000200' '%d.%m.%y %H.%M', # '25.10.06 14.30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
a6b97815263417d4268b9f231400f178232d92150607cf7a9885ff4f0d7db2bf
# This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '31/12/2009' '%d/%m/%y', # '31/12/09' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S.%f', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M:%S.%f', '%d/%m/%y %H:%M', ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
1a617d0854e180f43dad819dbb39891db525f90759216ba2a6b3837c83360527
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '31/12/2009' '%d/%m/%y', # '31/12/09' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S.%f', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M:%S.%f', '%d/%m/%y %H:%M', ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
51d7c13853873b8189e49c27f619364428a030eafaf52f25eedca1abd0dc20e2
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. F Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y.', # '25. 10. 06.' # "%d. %b %y.", # '25. Oct 06.' # "%d. %B %y.", # '25. October 06.' # "%d. %b '%y.", # '25. Oct '06.' # "%d. %B '%y.", # '25. October '06.' # "%d. %b %Y.", # '25. Oct 2006.' # "%d. %B %Y.", # '25. October 2006.' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
19f7b07956b94dfa35212f6c84091455ff2a36671f9f20f04e11c9a5f059da44
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y' TIME_FORMAT = 'G:i' DATETIME_FORMAT = 'j. E Y G:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', # '05.01.2006' '%d.%m.%y', # '05.01.06' '%d. %m. %Y', # '5. 1. 2006' '%d. %m. %y', # '5. 1. 06' # "%d. %B %Y", # '25. October 2006' # "%d. %b. %Y", # '25. Oct. 2006' ] # Kept ISO formats as one is in first position TIME_INPUT_FORMATS = [ '%H:%M:%S', # '04:30:59' '%H.%M', # '04.30' '%H:%M', # '04:30' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '05.01.2006 04:30:59' '%d.%m.%Y %H:%M:%S.%f', # '05.01.2006 04:30:59.000200' '%d.%m.%Y %H.%M', # '05.01.2006 04.30' '%d.%m.%Y %H:%M', # '05.01.2006 04:30' '%d. %m. %Y %H:%M:%S', # '05. 01. 2006 04:30:59' '%d. %m. %Y %H:%M:%S.%f', # '05. 01. 2006 04:30:59.000200' '%d. %m. %Y %H.%M', # '05. 01. 2006 04.30' '%d. %m. %Y %H:%M', # '05. 01. 2006 04:30' '%Y-%m-%d %H.%M', # '2006-01-05 04.30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
5613b66db39397f04058c7a5934cf5809657f2d77b67323a1cfb1a7c4d4e46e0
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y.' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. E Y. H:i' YEAR_MONTH_FORMAT = 'F Y.' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y.' SHORT_DATETIME_FORMAT = 'j.m.Y. H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y.', # '25.10.2006.' '%d.%m.%y.', # '25.10.06.' '%d. %m. %Y.', # '25. 10. 2006.' '%d. %m. %y.', # '25. 10. 06.' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' '%d.%m.%y. %H:%M', # '25.10.06. 14:30' '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
5cc5379511941ced04b4e4b51eae1fe1ef96b9a10791679768dfd961f463173d
# This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday: ISO 8601 DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' '%Y%m%d', # '20061025' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S.%f', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M:%S.%f', '%d/%m/%y %H:%M', ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
b0321f5192d8bf33a94a693d0d564c0952a4eda6e18861503ffd4fb674b55d55
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j. F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'j.m.Y' SHORT_DATETIME_FORMAT = 'j.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' '%d. %m. %Y', # '25. 10. 2006' '%d. %m. %y', # '25. 10. 06' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d. %m. %Y %H:%M:%S', # '25. 10. 2006 14:30:59' '%d. %m. %Y %H:%M:%S.%f', # '25. 10. 2006 14:30:59.000200' '%d. %m. %Y %H:%M', # '25. 10. 2006 14:30' '%d. %m. %y %H:%M:%S', # '25. 10. 06 14:30:59' '%d. %m. %y %H:%M:%S.%f', # '25. 10. 06 14:30:59.000200' '%d. %m. %y %H:%M', # '25. 10. 06 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
23f0a8a1c497f6ad6c6ea83a3c574ceb8a69760a31328e09aabb0e69606295c8
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j E Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j E Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j E' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' '%y-%m-%d', # '06-10-25' # "%d. %B %Y", # '25. października 2006' # "%d. %b. %Y", # '25. paź. 2006' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' NUMBER_GROUPING = 3
e4a8dc955f99c7a610413241f738616a97fe98e2522e41a05ea49292e0d95d7a
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' TIME_FORMAT = 'P' DATETIME_FORMAT = 'N j, Y, P' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y', # '10/25/06' # "%b %d %Y", # 'Oct 25 2006' # "%b %d, %Y", # 'Oct 25, 2006' # "%d %b %Y", # '25 Oct 2006' # "%d %b, %Y", # '25 Oct, 2006' # "%B %d %Y", # 'October 25 2006' # "%B %d, %Y", # 'October 25, 2006' # "%d %B %Y", # '25 October 2006' # "%d %B, %Y", # '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
42a925f27d9f1b299cd46732e9ff7899b8fcfb0aba7268d9140eaa3ae6394dca
# This file is distributed under the same license as the Django package. # DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' '%Y%m%d', # '20061025' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S.%f', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M:%S.%f', '%d/%m/%y %H:%M', ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
411e85750024ee6b62ec6df72de967f6a735bbac30c6f6e97a73e4b35cdae3f4
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'Y년 n월 j일' TIME_FORMAT = 'A g:i' DATETIME_FORMAT = 'Y년 n월 j일 g:i A' YEAR_MONTH_FORMAT = 'Y년 n월' MONTH_DAY_FORMAT = 'n월 j일' SHORT_DATE_FORMAT = 'Y-n-j.' SHORT_DATETIME_FORMAT = 'Y-n-j H:i' # FIRST_DAY_OF_WEEK = # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y', # '10/25/06' # "%b %d %Y", # 'Oct 25 2006' # "%b %d, %Y", # 'Oct 25, 2006' # "%d %b %Y", # '25 Oct 2006' # "%d %b, %Y", #'25 Oct, 2006' # "%B %d %Y", # 'October 25 2006' # "%B %d, %Y", #'October 25, 2006' # "%d %B %Y", # '25 October 2006' # "%d %B, %Y", # '25 October, 2006' '%Y년 %m월 %d일', # '2006년 10월 25일', with localized suffix. ] TIME_INPUT_FORMATS = [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' '%H시 %M분 %S초', # '14시 30분 59초' '%H시 %M분', # '14시 30분' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M:%S.%f', # '10/25/2006 14:30:59.000200' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M:%S.%f', # '10/25/06 14:30:59.000200' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%Y년 %m월 %d일 %H시 %M분 %S초', # '2006년 10월 25일 14시 30분 59초' '%Y년 %m월 %d일 %H시 %M분', # '2006년 10월 25일 14시 30분' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
569f2d28e3d3a589e56cac5b2ed165e705ca0bf538b321aa00a11a0755a5c012
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j N Y' SHORT_DATETIME_FORMAT = 'j N Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' '%d.%m.%Y', # Swiss [fr_CH] '25.10.2006' '%d.%m.%y', # Swiss [fr_CH] '25.10.06' # '%d %B %Y', '%d %b %Y', # '25 octobre 2006', '25 oct. 2006' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d.%m.%Y %H:%M:%S', # Swiss [fr_CH), '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # Swiss (fr_CH), '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # Swiss (fr_CH), '25.10.2006 14:30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
175a0e2d49431d572b7583d5bd2dd73b3d201d8b35ff3be5a559e74b543bf4b8
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'Y. \g\a\d\a j. F' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'Y. \g\a\d\a j. F, H:i' YEAR_MONTH_FORMAT = r'Y. \g. F' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = r'j.m.Y' SHORT_DATETIME_FORMAT = 'j.m.Y H:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%d.%m.%Y', # '25.10.2006' '%d.%m.%y', # '25.10.06' ] TIME_INPUT_FORMATS = [ '%H:%M:%S', # '14:30:59' '%H:%M:%S.%f', # '14:30:59.000200' '%H:%M', # '14:30' '%H.%M.%S', # '14.30.59' '%H.%M.%S.%f', # '14.30.59.000200' '%H.%M', # '14.30' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' '%d.%m.%y %H:%M', # '25.10.06 14:30' '%d.%m.%y %H.%M.%S', # '25.10.06 14.30.59' '%d.%m.%y %H.%M.%S.%f', # '25.10.06 14.30.59.000200' '%d.%m.%y %H.%M', # '25.10.06 14.30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' # Non-breaking space NUMBER_GROUPING = 3
66971af4c672107abcbcb620d6f0afb808a3c8b760b2cffe38dd49f0c4603e83
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j M Y' # '25 Oct 2006' TIME_FORMAT = 'P' # '2:30 p.m.' DATETIME_FORMAT = 'j M Y, P' # '25 Oct 2006, 2:30 p.m.' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'j F' # '25 October' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 p.m.' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y', # '25/10/06' '%d %b %Y', # '25 Oct 2006' '%d %b, %Y', # '25 Oct, 2006' '%d %B %Y', # '25 October 2006' '%d %B, %Y', # '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
e058fd0f154d8a92ab6898ac747fcd8bdf77700ce7f82d29f7cf350cdd3b02b1
import functools import re from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db.migrations.operations.models import AlterModelOptions from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.utils import ( COMPILED_REGEX_TYPE, RegexObject, resolve_relation, ) from django.utils.topological_sort import stable_topological_sort class MigrationAutodetector: """ Take a pair of ProjectStates and compare them to see what the first would need doing to make it match the second (the second usually being the project's current state). Note that this naturally operates on entire projects at a time, as it's likely that changes interact (for example, you can't add a ForeignKey without having a migration to add the table it depends on first). A user interface may offer single-app usage if it wishes, with the caveat that it may not always be possible. """ def __init__(self, from_state, to_state, questioner=None): self.from_state = from_state self.to_state = to_state self.questioner = questioner or MigrationQuestioner() self.existing_apps = {app for app, model in from_state.models} def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None): """ Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed) """ changes = self._detect_changes(convert_apps, graph) changes = self.arrange_for_graph(changes, graph, migration_name) if trim_to_apps: changes = self._trim_to_apps(changes, trim_to_apps) return changes def deep_deconstruct(self, obj): """ Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly. """ if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) elif isinstance(obj, dict): return { key: self.deep_deconstruct(value) for key, value in obj.items() } elif isinstance(obj, functools.partial): return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords)) elif isinstance(obj, COMPILED_REGEX_TYPE): return RegexObject(obj) elif isinstance(obj, type): # If this is a type that implements 'deconstruct' as an instance method, # avoid treating this as being deconstructible itself - see #22951 return obj elif hasattr(obj, 'deconstruct'): deconstructed = obj.deconstruct() if isinstance(obj, models.Field): # we have a field which also returns a name deconstructed = deconstructed[1:] path, args, kwargs = deconstructed return ( path, [self.deep_deconstruct(value) for value in args], { key: self.deep_deconstruct(value) for key, value in kwargs.items() }, ) else: return obj def only_relation_agnostic_fields(self, fields): """ Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as the related fields change during renames). """ fields_def = [] for name, field in sorted(fields.items()): deconstruction = self.deep_deconstruct(field) if field.remote_field and field.remote_field.model: deconstruction[2].pop('to', None) fields_def.append(deconstruction) return fields_def def _detect_changes(self, convert_apps=None, graph=None): """ Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the names do matter for dependencies inside the set. convert_apps is the list of apps to convert to use migrations (i.e. to make initial migrations for, in the usual case) graph is an optional argument that, if provided, can help improve dependency generation and avoid potential circular dependencies. """ # The first phase is generating all the operations for each app # and gathering them into a big per-app list. # Then go through that list, order it, and split into migrations to # resolve dependencies caused by M2Ms and FKs. self.generated_operations = {} self.altered_indexes = {} self.altered_constraints = {} # Prepare some old/new state and model lists, separating # proxy models and ignoring unmigrated apps. self.old_model_keys = set() self.old_proxy_keys = set() self.old_unmanaged_keys = set() self.new_model_keys = set() self.new_proxy_keys = set() self.new_unmanaged_keys = set() for (app_label, model_name), model_state in self.from_state.models.items(): if not model_state.options.get('managed', True): self.old_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps: if model_state.options.get('proxy'): self.old_proxy_keys.add((app_label, model_name)) else: self.old_model_keys.add((app_label, model_name)) for (app_label, model_name), model_state in self.to_state.models.items(): if not model_state.options.get('managed', True): self.new_unmanaged_keys.add((app_label, model_name)) elif ( app_label not in self.from_state.real_apps or (convert_apps and app_label in convert_apps) ): if model_state.options.get('proxy'): self.new_proxy_keys.add((app_label, model_name)) else: self.new_model_keys.add((app_label, model_name)) self.from_state.resolve_fields_and_relations() self.to_state.resolve_fields_and_relations() # Renames have to come first self.generate_renamed_models() # Prepare lists of fields and generate through model map self._prepare_field_lists() self._generate_through_model_map() # Generate non-rename model operations self.generate_deleted_models() self.generate_created_models() self.generate_deleted_proxies() self.generate_created_proxies() self.generate_altered_options() self.generate_altered_managers() # Create the altered indexes and store them in self.altered_indexes. # This avoids the same computation in generate_removed_indexes() # and generate_added_indexes(). self.create_altered_indexes() self.create_altered_constraints() # Generate index removal operations before field is removed self.generate_removed_constraints() self.generate_removed_indexes() # Generate field renaming operations. self.generate_renamed_fields() # Generate removal of foo together. self.generate_removed_altered_unique_together() self.generate_removed_altered_index_together() # Generate field operations. self.generate_removed_fields() self.generate_added_fields() self.generate_altered_fields() self.generate_altered_order_with_respect_to() self.generate_altered_unique_together() self.generate_altered_index_together() self.generate_added_indexes() self.generate_added_constraints() self.generate_altered_db_table() self._sort_migrations() self._build_migration_list(graph) self._optimize_migrations() return self.migrations def _prepare_field_lists(self): """ Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it. """ self.kept_model_keys = self.old_model_keys & self.new_model_keys self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys self.through_users = {} self.old_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.from_state.models[ app_label, self.renamed_models.get((app_label, model_name), model_name) ].fields } self.new_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.to_state.models[app_label, model_name].fields } def _generate_through_model_map(self): """Through model map generation.""" for app_label, model_name in sorted(self.old_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] for field_name, field in old_model_state.fields.items(): if hasattr(field, 'remote_field') and getattr(field.remote_field, 'through', None): through_key = resolve_relation(field.remote_field.through, app_label, model_name) self.through_users[through_key] = (app_label, old_model_name, field_name) @staticmethod def _resolve_dependency(dependency): """ Return the resolved dependency and a boolean denoting whether or not it was swappable. """ if dependency[0] != '__setting__': return dependency, False resolved_app_label, resolved_object_name = getattr(settings, dependency[1]).split('.') return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True def _build_migration_list(self, graph=None): """ Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off the operations before it into a migration and move onto the next app. If the loops completes without doing anything, there's a circular dependency (which _should_ be impossible as the operations are all split at this point so they can't depend and be depended on). """ self.migrations = {} num_ops = sum(len(x) for x in self.generated_operations.values()) chop_mode = False while num_ops: # On every iteration, we step through all the apps and see if there # is a completed set of operations. # If we find that a subset of the operations are complete we can # try to chop it off from the rest and continue, but we only # do this if we've already been through the list once before # without any chopping and nothing has changed. for app_label in sorted(self.generated_operations): chopped = [] dependencies = set() for operation in list(self.generated_operations[app_label]): deps_satisfied = True operation_dependencies = set() for dep in operation._auto_deps: # Temporarily resolve the swappable dependency to # prevent circular references. While keeping the # dependency checks on the resolved model, add the # swappable dependencies. original_dep = dep dep, is_swappable_dep = self._resolve_dependency(dep) if dep[0] != app_label: # External app dependency. See if it's not yet # satisfied. for other_operation in self.generated_operations.get(dep[0], []): if self.check_dependency(other_operation, dep): deps_satisfied = False break if not deps_satisfied: break else: if is_swappable_dep: operation_dependencies.add((original_dep[0], original_dep[1])) elif dep[0] in self.migrations: operation_dependencies.add((dep[0], self.migrations[dep[0]][-1].name)) else: # If we can't find the other app, we add a first/last dependency, # but only if we've already been through once and checked everything if chop_mode: # If the app already exists, we add a dependency on the last migration, # as we don't know which migration contains the target field. # If it's not yet migrated or has no migrations, we use __first__ if graph and graph.leaf_nodes(dep[0]): operation_dependencies.add(graph.leaf_nodes(dep[0])[0]) else: operation_dependencies.add((dep[0], "__first__")) else: deps_satisfied = False if deps_satisfied: chopped.append(operation) dependencies.update(operation_dependencies) del self.generated_operations[app_label][0] else: break # Make a migration! Well, only if there's stuff to put in it if dependencies or chopped: if not self.generated_operations[app_label] or chop_mode: subclass = type("Migration", (Migration,), {"operations": [], "dependencies": []}) instance = subclass("auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label) instance.dependencies = list(dependencies) instance.operations = chopped instance.initial = app_label not in self.existing_apps self.migrations.setdefault(app_label, []).append(instance) chop_mode = False else: self.generated_operations[app_label] = chopped + self.generated_operations[app_label] new_num_ops = sum(len(x) for x in self.generated_operations.values()) if new_num_ops == num_ops: if not chop_mode: chop_mode = True else: raise ValueError("Cannot resolve operation dependencies: %r" % self.generated_operations) num_ops = new_num_ops def _sort_migrations(self): """ Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app. """ for app_label, ops in sorted(self.generated_operations.items()): # construct a dependency graph for intra-app dependencies dependency_graph = {op: set() for op in ops} for op in ops: for dep in op._auto_deps: # Resolve intra-app dependencies to handle circular # references involving a swappable model. dep = self._resolve_dependency(dep)[0] if dep[0] == app_label: for op2 in ops: if self.check_dependency(op2, dep): dependency_graph[op].add(op2) # we use a stable sort for deterministic tests & general behavior self.generated_operations[app_label] = stable_topological_sort(ops, dependency_graph) def _optimize_migrations(self): # Add in internal dependencies among the migrations for app_label, migrations in self.migrations.items(): for m1, m2 in zip(migrations, migrations[1:]): m2.dependencies.append((app_label, m1.name)) # De-dupe dependencies for migrations in self.migrations.values(): for migration in migrations: migration.dependencies = list(set(migration.dependencies)) # Optimize migrations for app_label, migrations in self.migrations.items(): for migration in migrations: migration.operations = MigrationOptimizer().optimize(migration.operations, app_label) def check_dependency(self, operation, dependency): """ Return True if the given operation depends on the given dependency, False otherwise. """ # Created model if dependency[2] is None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() ) # Created field elif dependency[2] is not None and dependency[3] is True: return ( ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() and any(dependency[2] == x for x, y in operation.fields) ) or ( isinstance(operation, operations.AddField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) ) # Removed field elif dependency[2] is not None and dependency[3] is False: return ( isinstance(operation, operations.RemoveField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed model elif dependency[2] is None and dependency[3] is False: return ( isinstance(operation, operations.DeleteModel) and operation.name_lower == dependency[1].lower() ) # Field being altered elif dependency[2] is not None and dependency[3] == "alter": return ( isinstance(operation, operations.AlterField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # order_with_respect_to being unset for a field elif dependency[2] is not None and dependency[3] == "order_wrt_unset": return ( isinstance(operation, operations.AlterOrderWithRespectTo) and operation.name_lower == dependency[1].lower() and (operation.order_with_respect_to or "").lower() != dependency[2].lower() ) # Field is removed and part of an index/unique_together elif dependency[2] is not None and dependency[3] == "foo_together_change": return ( isinstance(operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether)) and operation.name_lower == dependency[1].lower() ) # Unknown dependency. Raise an error. else: raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): # Dependencies are (app_label, model_name, field_name, create/delete as True/False) operation._auto_deps = dependencies or [] if beginning: self.generated_operations.setdefault(app_label, []).insert(0, operation) else: self.generated_operations.setdefault(app_label, []).append(operation) def swappable_first_key(self, item): """ Place potential swappable models first in lists of created models (only real way to solve #22783). """ try: model_state = self.to_state.models[item] base_names = { base if isinstance(base, str) else base.__name__ for base in model_state.bases } string_version = "%s.%s" % (item[0], item[1]) if ( model_state.options.get('swappable') or "AbstractUser" in base_names or "AbstractBaseUser" in base_names or settings.AUTH_USER_MODEL.lower() == string_version.lower() ): return ("___" + item[0], "___" + item[1]) except LookupError: pass return item def generate_renamed_models(self): """ Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation. """ self.renamed_models = {} self.renamed_models_rel = {} added_models = self.new_model_keys - self.old_model_keys for app_label, model_name in sorted(added_models): model_state = self.to_state.models[app_label, model_name] model_fields_def = self.only_relation_agnostic_fields(model_state.fields) removed_models = self.old_model_keys - self.new_model_keys for rem_app_label, rem_model_name in removed_models: if rem_app_label == app_label: rem_model_state = self.from_state.models[rem_app_label, rem_model_name] rem_model_fields_def = self.only_relation_agnostic_fields(rem_model_state.fields) if model_fields_def == rem_model_fields_def: if self.questioner.ask_rename_model(rem_model_state, model_state): dependencies = [] fields = list(model_state.fields.values()) + [ field.remote_field for relations in self.to_state.relations[app_label, model_name].values() for field in relations.values() ] for field in fields: if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) self.add_operation( app_label, operations.RenameModel( old_name=rem_model_state.name, new_name=model_state.name, ), dependencies=dependencies, ) self.renamed_models[app_label, model_name] = rem_model_name renamed_models_rel_key = '%s.%s' % ( rem_model_state.app_label, rem_model_state.name_lower, ) self.renamed_models_rel[renamed_models_rel_key] = '%s.%s' % ( model_state.app_label, model_state.name_lower, ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.add((app_label, model_name)) break def generate_created_models(self): """ Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options that refer to collections of fields that might be deferred (e.g. unique_together, index_together). """ old_keys = self.old_model_keys | self.old_unmanaged_keys added_models = self.new_model_keys - old_keys added_unmanaged_models = self.new_unmanaged_keys - old_keys all_added_models = chain( sorted(added_models, key=self.swappable_first_key, reverse=True), sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True) ) for app_label, model_name in all_added_models: model_state = self.to_state.models[app_label, model_name] # Gather related fields related_fields = {} primary_key_rel = None for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: if field.primary_key: primary_key_rel = field.remote_field.model elif not field.remote_field.parent_link: related_fields[field_name] = field if getattr(field.remote_field, 'through', None): related_fields[field_name] = field # Are there indexes/unique|index_together to defer? indexes = model_state.options.pop('indexes') constraints = model_state.options.pop('constraints') unique_together = model_state.options.pop('unique_together', None) index_together = model_state.options.pop('index_together', None) order_with_respect_to = model_state.options.pop('order_with_respect_to', None) # Depend on the deletion of any possible proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Depend on the removal of base fields if the new model has # a field with the same name. old_base_model_state = self.from_state.models.get((base_app_label, base_name)) new_base_model_state = self.to_state.models.get((base_app_label, base_name)) if old_base_model_state and new_base_model_state: removed_base_fields = set(old_base_model_state.fields).difference( new_base_model_state.fields, ).intersection(model_state.fields) for removed_base_field in removed_base_fields: dependencies.append((base_app_label, base_name, removed_base_field, False)) # Depend on the other end of the primary key if it's a relation if primary_key_rel: dependencies.append( resolve_relation( primary_key_rel, app_label, model_name, ) + (None, True) ) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[d for d in model_state.fields.items() if d[0] not in related_fields], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), dependencies=dependencies, beginning=True, ) # Don't add operations which modify the database for unmanaged models if not model_state.options.get('managed', True): continue # Generate operations for each related field for name, field in sorted(related_fields.items()): dependencies = self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) # Depend on our own model being created dependencies.append((app_label, model_name, None, True)) # Make operation self.add_operation( app_label, operations.AddField( model_name=model_name, name=name, field=field, ), dependencies=list(set(dependencies)), ) # Generate other opns if order_with_respect_to: self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=order_with_respect_to, ), dependencies=[ (app_label, model_name, order_with_respect_to, True), (app_label, model_name, None, True), ] ) related_dependencies = [ (app_label, model_name, name, True) for name in sorted(related_fields) ] related_dependencies.append((app_label, model_name, None, True)) for index in indexes: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=related_dependencies, ) for constraint in constraints: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=related_dependencies, ) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=unique_together, ), dependencies=related_dependencies ) if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=index_together, ), dependencies=related_dependencies ) # Fix relationships if the model changed from a proxy model to a # concrete model. relations = self.to_state.relations if (app_label, model_name) in self.old_proxy_keys: for related_model_key, related_fields in relations[app_label, model_name].items(): related_model_state = self.to_state.models[related_model_key] for related_field_name, related_field in related_fields.items(): self.add_operation( related_model_state.app_label, operations.AlterField( model_name=related_model_state.name, name=related_field_name, field=related_field, ), dependencies=[(app_label, model_name, None, True)], ) def generate_created_proxies(self): """ Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but for proxy models it's safe to skip all the pointless field stuff and chuck out an operation. """ added = self.new_proxy_keys - self.old_proxy_keys for app_label, model_name in sorted(added): model_state = self.to_state.models[app_label, model_name] assert model_state.options.get("proxy") # Depend on the deletion of any possible non-proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), # Depend on the deletion of any possible non-proxy version of us dependencies=dependencies, ) def generate_deleted_models(self): """ Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal of any model options that refer to collections of fields - the inverse of generate_created_models(). """ new_keys = self.new_model_keys | self.new_unmanaged_keys deleted_models = self.old_model_keys - new_keys deleted_unmanaged_models = self.old_unmanaged_keys - new_keys all_deleted_models = chain(sorted(deleted_models), sorted(deleted_unmanaged_models)) for app_label, model_name in all_deleted_models: model_state = self.from_state.models[app_label, model_name] # Gather related fields related_fields = {} for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: related_fields[field_name] = field if getattr(field.remote_field, 'through', None): related_fields[field_name] = field # Generate option removal first unique_together = model_state.options.pop('unique_together', None) index_together = model_state.options.pop('index_together', None) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=None, ) ) if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=None, ) ) # Then remove each related field for name in sorted(related_fields): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=name, ) ) # Finally, remove the model. # This depends on both the removal/alteration of all incoming fields # and the removal of all its own related fields, and if it's # a through model the field that references it. dependencies = [] relations = self.from_state.relations for (related_object_app_label, object_name), relation_related_fields in ( relations[app_label, model_name].items() ): for field_name, field in relation_related_fields.items(): dependencies.append( (related_object_app_label, object_name, field_name, False), ) if not field.many_to_many: dependencies.append( (related_object_app_label, object_name, field_name, 'alter'), ) for name in sorted(related_fields): dependencies.append((app_label, model_name, name, False)) # We're referenced in another field's through= through_user = self.through_users.get((app_label, model_state.name_lower)) if through_user: dependencies.append((through_user[0], through_user[1], through_user[2], False)) # Finally, make the operation, deduping any dependencies self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), dependencies=list(set(dependencies)), ) def generate_deleted_proxies(self): """Make DeleteModel options for proxy models.""" deleted = self.old_proxy_keys - self.new_proxy_keys for app_label, model_name in sorted(deleted): model_state = self.from_state.models[app_label, model_name] assert model_state.options.get("proxy") self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), ) def generate_renamed_fields(self): """Work out renamed fields.""" self.renamed_fields = {} for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] field = new_model_state.get_field(field_name) # Scan to see if this is actually a rename! field_dec = self.deep_deconstruct(field) for rem_app_label, rem_model_name, rem_field_name in sorted(self.old_field_keys - self.new_field_keys): if rem_app_label == app_label and rem_model_name == model_name: old_field = old_model_state.get_field(rem_field_name) old_field_dec = self.deep_deconstruct(old_field) if field.remote_field and field.remote_field.model and 'to' in old_field_dec[2]: old_rel_to = old_field_dec[2]['to'] if old_rel_to in self.renamed_models_rel: old_field_dec[2]['to'] = self.renamed_models_rel[old_rel_to] old_field.set_attributes_from_name(rem_field_name) old_db_column = old_field.get_attname_column()[1] if (old_field_dec == field_dec or ( # Was the field renamed and db_column equal to the # old field's column added? old_field_dec[0:2] == field_dec[0:2] and dict(old_field_dec[2], db_column=old_db_column) == field_dec[2])): if self.questioner.ask_rename(model_name, rem_field_name, field_name, field): # A db_column mismatch requires a prior noop # AlterField for the subsequent RenameField to be a # noop on attempts at preserving the old name. if old_field.db_column != field.db_column: altered_field = field.clone() altered_field.name = rem_field_name self.add_operation( app_label, operations.AlterField( model_name=model_name, name=rem_field_name, field=altered_field, ), ) self.add_operation( app_label, operations.RenameField( model_name=model_name, old_name=rem_field_name, new_name=field_name, ) ) self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name)) self.old_field_keys.add((app_label, model_name, field_name)) self.renamed_fields[app_label, model_name, field_name] = rem_field_name break def generate_added_fields(self): """Make AddField operations.""" for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys): self._generate_added_field(app_label, model_name, field_name) def _generate_added_field(self, app_label, model_name, field_name): field = self.to_state.models[app_label, model_name].get_field(field_name) # Fields that are foreignkeys/m2ms depend on stuff dependencies = [] if field.remote_field and field.remote_field.model: dependencies.extend(self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, )) # You can't just add NOT NULL fields with no default or fields # which don't allow empty strings as default. time_fields = (models.DateField, models.DateTimeField, models.TimeField) preserve_default = ( field.null or field.has_default() or field.many_to_many or (field.blank and field.empty_strings_allowed) or (isinstance(field, time_fields) and field.auto_now) ) if not preserve_default: field = field.clone() if isinstance(field, time_fields) and field.auto_now_add: field.default = self.questioner.ask_auto_now_add_addition(field_name, model_name) else: field.default = self.questioner.ask_not_null_addition(field_name, model_name) if ( field.unique and field.default is not models.NOT_PROVIDED and callable(field.default) ): self.questioner.ask_unique_callable_default_addition(field_name, model_name) self.add_operation( app_label, operations.AddField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) def generate_removed_fields(self): """Make RemoveField operations.""" for app_label, model_name, field_name in sorted(self.old_field_keys - self.new_field_keys): self._generate_removed_field(app_label, model_name, field_name) def _generate_removed_field(self, app_label, model_name, field_name): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=field_name, ), # We might need to depend on the removal of an # order_with_respect_to or index/unique_together operation; # this is safely ignored if there isn't one dependencies=[ (app_label, model_name, field_name, "order_wrt_unset"), (app_label, model_name, field_name, "foo_together_change"), ], ) def generate_altered_fields(self): """ Make AlterField operations, or possibly RemovedField/AddField if alter isn't possible. """ for app_label, model_name, field_name in sorted(self.old_field_keys & self.new_field_keys): # Did the field change? old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_field_name = self.renamed_fields.get((app_label, model_name, field_name), field_name) old_field = self.from_state.models[app_label, old_model_name].get_field(old_field_name) new_field = self.to_state.models[app_label, model_name].get_field(field_name) dependencies = [] # Implement any model renames on relations; these are handled by RenameModel # so we need to exclude them from the comparison if hasattr(new_field, "remote_field") and getattr(new_field.remote_field, "model", None): rename_key = resolve_relation(new_field.remote_field.model, app_label, model_name) if rename_key in self.renamed_models: new_field.remote_field.model = old_field.remote_field.model # Handle ForeignKey which can only have a single to_field. remote_field_name = getattr(new_field.remote_field, 'field_name', None) if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: # Repoint both model and field name because to_field # inclusion in ForeignKey.deconstruct() is based on # both. new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = old_field.remote_field.field_name # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, 'from_fields', None) if from_fields: from_rename_key = (app_label, model_name) new_field.from_fields = tuple([ self.renamed_fields.get(from_rename_key + (from_field,), from_field) for from_field in from_fields ]) new_field.to_fields = tuple([ self.renamed_fields.get(rename_key + (to_field,), to_field) for to_field in new_field.to_fields ]) dependencies.extend(self._get_dependencies_for_foreign_key( app_label, model_name, new_field, self.to_state, )) if ( hasattr(new_field, 'remote_field') and getattr(new_field.remote_field, 'through', None) ): rename_key = resolve_relation(new_field.remote_field.through, app_label, model_name) if rename_key in self.renamed_models: new_field.remote_field.through = old_field.remote_field.through old_field_dec = self.deep_deconstruct(old_field) new_field_dec = self.deep_deconstruct(new_field) # If the field was confirmed to be renamed it means that only # db_column was allowed to change which generate_renamed_fields() # already accounts for by adding an AlterField operation. if old_field_dec != new_field_dec and old_field_name == field_name: both_m2m = old_field.many_to_many and new_field.many_to_many neither_m2m = not old_field.many_to_many and not new_field.many_to_many if both_m2m or neither_m2m: # Either both fields are m2m or neither is preserve_default = True if (old_field.null and not new_field.null and not new_field.has_default() and not new_field.many_to_many): field = new_field.clone() new_default = self.questioner.ask_not_null_alteration(field_name, model_name) if new_default is not models.NOT_PROVIDED: field.default = new_default preserve_default = False else: field = new_field self.add_operation( app_label, operations.AlterField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) else: # We cannot alter between m2m and concrete fields self._generate_removed_field(app_label, model_name, field_name) self._generate_added_field(app_label, model_name, field_name) def create_altered_indexes(self): option_name = operations.AddIndex.option_name for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_indexes = old_model_state.options[option_name] new_indexes = new_model_state.options[option_name] add_idx = [idx for idx in new_indexes if idx not in old_indexes] rem_idx = [idx for idx in old_indexes if idx not in new_indexes] self.altered_indexes.update({ (app_label, model_name): { 'added_indexes': add_idx, 'removed_indexes': rem_idx, } }) def generate_added_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes['added_indexes']: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ) ) def generate_removed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes['removed_indexes']: self.add_operation( app_label, operations.RemoveIndex( model_name=model_name, name=index.name, ) ) def create_altered_constraints(self): option_name = operations.AddConstraint.option_name for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_constraints = old_model_state.options[option_name] new_constraints = new_model_state.options[option_name] add_constraints = [c for c in new_constraints if c not in old_constraints] rem_constraints = [c for c in old_constraints if c not in new_constraints] self.altered_constraints.update({ (app_label, model_name): { 'added_constraints': add_constraints, 'removed_constraints': rem_constraints, } }) def generate_added_constraints(self): for (app_label, model_name), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints['added_constraints']: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ) ) def generate_removed_constraints(self): for (app_label, model_name), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints['removed_constraints']: self.add_operation( app_label, operations.RemoveConstraint( model_name=model_name, name=constraint.name, ) ) @staticmethod def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state): remote_field_model = None if hasattr(field.remote_field, 'model'): remote_field_model = field.remote_field.model else: relations = project_state.relations[app_label, model_name] for (remote_app_label, remote_model_name), fields in relations.items(): if any( field == related_field.remote_field for related_field in fields.values() ): remote_field_model = f'{remote_app_label}.{remote_model_name}' break # Account for FKs to swappable models swappable_setting = getattr(field, 'swappable_setting', None) if swappable_setting is not None: dep_app_label = "__setting__" dep_object_name = swappable_setting else: dep_app_label, dep_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies = [(dep_app_label, dep_object_name, None, True)] if getattr(field.remote_field, 'through', None): through_app_label, through_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies.append((through_app_label, through_object_name, None, True)) return dependencies def _get_altered_foo_together_operations(self, option_name): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] # We run the old version through the field renames to account for those old_value = old_model_state.options.get(option_name) old_value = { tuple( self.renamed_fields.get((app_label, model_name, n), n) for n in unique ) for unique in old_value } if old_value else set() new_value = new_model_state.options.get(option_name) new_value = set(new_value) if new_value else set() if old_value != new_value: dependencies = [] for foo_togethers in new_value: for field_name in foo_togethers: field = new_model_state.get_field(field_name) if field.remote_field and field.remote_field.model: dependencies.extend(self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, )) yield ( old_value, new_value, app_label, model_name, dependencies, ) def _generate_removed_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): removal_value = new_value.intersection(old_value) if removal_value or old_value: self.add_operation( app_label, operation(name=model_name, **{operation.option_name: removal_value}), dependencies=dependencies, ) def generate_removed_altered_unique_together(self): self._generate_removed_altered_foo_together(operations.AlterUniqueTogether) def generate_removed_altered_index_together(self): self._generate_removed_altered_foo_together(operations.AlterIndexTogether) def _generate_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): removal_value = new_value.intersection(old_value) if new_value != removal_value: self.add_operation( app_label, operation(name=model_name, **{operation.option_name: new_value}), dependencies=dependencies, ) def generate_altered_unique_together(self): self._generate_altered_foo_together(operations.AlterUniqueTogether) def generate_altered_index_together(self): self._generate_altered_foo_together(operations.AlterIndexTogether) def generate_altered_db_table(self): models_to_check = self.kept_model_keys.union(self.kept_proxy_keys, self.kept_unmanaged_keys) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_name = old_model_state.options.get('db_table') new_db_table_name = new_model_state.options.get('db_table') if old_db_table_name != new_db_table_name: self.add_operation( app_label, operations.AlterModelTable( name=model_name, table=new_db_table_name, ) ) def generate_altered_options(self): """ Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them). """ models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys, # unmanaged converted to managed self.old_unmanaged_keys & self.new_model_keys, # managed converted to unmanaged self.old_model_keys & self.new_unmanaged_keys, ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_options = { key: value for key, value in old_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } new_options = { key: value for key, value in new_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } if old_options != new_options: self.add_operation( app_label, operations.AlterModelOptions( name=model_name, options=new_options, ) ) def generate_altered_order_with_respect_to(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if (old_model_state.options.get("order_with_respect_to") != new_model_state.options.get("order_with_respect_to")): # Make sure it comes second if we're adding # (removal dependency is part of RemoveField) dependencies = [] if new_model_state.options.get("order_with_respect_to"): dependencies.append(( app_label, model_name, new_model_state.options["order_with_respect_to"], True, )) # Actually generate the operation self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=new_model_state.options.get('order_with_respect_to'), ), dependencies=dependencies, ) def generate_altered_managers(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.managers != new_model_state.managers: self.add_operation( app_label, operations.AlterModelManagers( name=model_name, managers=new_model_state.managers, ) ) def arrange_for_graph(self, changes, graph, migration_name=None): """ Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app. """ leaves = graph.leaf_nodes() name_map = {} for app_label, migrations in list(changes.items()): if not migrations: continue # Find the app label's current leaf node app_leaf = None for leaf in leaves: if leaf[0] == app_label: app_leaf = leaf break # Do they want an initial migration for this app? if app_leaf is None and not self.questioner.ask_initial(app_label): # They don't. for migration in migrations: name_map[(app_label, migration.name)] = (app_label, "__first__") del changes[app_label] continue # Work out the next number in the sequence if app_leaf is None: next_number = 1 else: next_number = (self.parse_number(app_leaf[1]) or 0) + 1 # Name each migration for i, migration in enumerate(migrations): if i == 0 and app_leaf: migration.dependencies.append(app_leaf) new_name_parts = ['%04i' % next_number] if migration_name: new_name_parts.append(migration_name) elif i == 0 and not app_leaf: new_name_parts.append('initial') else: new_name_parts.append(migration.suggest_name()[:100]) new_name = '_'.join(new_name_parts) name_map[(app_label, migration.name)] = (app_label, new_name) next_number += 1 migration.name = new_name # Now fix dependencies for migrations in changes.values(): for migration in migrations: migration.dependencies = [name_map.get(d, d) for d in migration.dependencies] return changes def _trim_to_apps(self, changes, app_labels): """ Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies. """ # Gather other app dependencies in a first pass app_dependencies = {} for app_label, migrations in changes.items(): for migration in migrations: for dep_app_label, name in migration.dependencies: app_dependencies.setdefault(app_label, set()).add(dep_app_label) required_apps = set(app_labels) # Keep resolving till there's no change old_required_apps = None while old_required_apps != required_apps: old_required_apps = set(required_apps) required_apps.update(*[app_dependencies.get(app_label, ()) for app_label in required_apps]) # Remove all migrations that aren't needed for app_label in list(changes): if app_label not in required_apps: del changes[app_label] return changes @classmethod def parse_number(cls, name): """ Given a migration name, try to extract a number from the beginning of it. For a squashed migration such as '0001_squashed_0004…', return the second number. If no number is found, return None. """ if squashed_match := re.search(r'.*_squashed_(\d+)', name): return int(squashed_match[1]) match = re.match(r'^\d+', name) if match: return int(match[0]) return None
11a1aa08b134e98533029d6e85c16e7c838c9e029039a5f49cc123dbe4f26e59
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .. import Error, Tags, Warning, register CROSS_ORIGIN_OPENER_POLICY_VALUES = { 'same-origin', 'same-origin-allow-popups', 'unsafe-none', } REFERRER_POLICY_VALUES = { 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url', } SECRET_KEY_INSECURE_PREFIX = 'django-insecure-' SECRET_KEY_MIN_LENGTH = 50 SECRET_KEY_MIN_UNIQUE_CHARACTERS = 5 SECRET_KEY_WARNING_MSG = ( f"Your %s has less than {SECRET_KEY_MIN_LENGTH} characters, less than " f"{SECRET_KEY_MIN_UNIQUE_CHARACTERS} unique characters, or it's prefixed " f"with '{SECRET_KEY_INSECURE_PREFIX}' indicating that it was generated " f"automatically by Django. Please generate a long and random value, " f"otherwise many of Django's security-critical features will be " f"vulnerable to attack." ) W001 = Warning( "You do not have 'django.middleware.security.SecurityMiddleware' " "in your MIDDLEWARE so the SECURE_HSTS_SECONDS, " "SECURE_CONTENT_TYPE_NOSNIFF, SECURE_REFERRER_POLICY, " "SECURE_CROSS_ORIGIN_OPENER_POLICY, and SECURE_SSL_REDIRECT settings will " "have no effect.", id='security.W001', ) W002 = Warning( "You do not have " "'django.middleware.clickjacking.XFrameOptionsMiddleware' in your " "MIDDLEWARE, so your pages will not be served with an " "'x-frame-options' header. Unless there is a good reason for your " "site to be served in a frame, you should consider enabling this " "header to help prevent clickjacking attacks.", id='security.W002', ) W004 = Warning( "You have not set a value for the SECURE_HSTS_SECONDS setting. " "If your entire site is served only over SSL, you may want to consider " "setting a value and enabling HTTP Strict Transport Security. " "Be sure to read the documentation first; enabling HSTS carelessly " "can cause serious, irreversible problems.", id='security.W004', ) W005 = Warning( "You have not set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True. " "Without this, your site is potentially vulnerable to attack " "via an insecure connection to a subdomain. Only set this to True if " "you are certain that all subdomains of your domain should be served " "exclusively via SSL.", id='security.W005', ) W006 = Warning( "Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, " "so your pages will not be served with an " "'X-Content-Type-Options: nosniff' header. " "You should consider enabling this header to prevent the " "browser from identifying content types incorrectly.", id='security.W006', ) W008 = Warning( "Your SECURE_SSL_REDIRECT setting is not set to True. " "Unless your site should be available over both SSL and non-SSL " "connections, you may want to either set this setting True " "or configure a load balancer or reverse-proxy server " "to redirect all connections to HTTPS.", id='security.W008', ) W009 = Warning( SECRET_KEY_WARNING_MSG % 'SECRET_KEY', id='security.W009', ) W018 = Warning( "You should not have DEBUG set to True in deployment.", id='security.W018', ) W019 = Warning( "You have " "'django.middleware.clickjacking.XFrameOptionsMiddleware' in your " "MIDDLEWARE, but X_FRAME_OPTIONS is not set to 'DENY'. " "Unless there is a good reason for your site to serve other parts of " "itself in a frame, you should change it to 'DENY'.", id='security.W019', ) W020 = Warning( "ALLOWED_HOSTS must not be empty in deployment.", id='security.W020', ) W021 = Warning( "You have not set the SECURE_HSTS_PRELOAD setting to True. Without this, " "your site cannot be submitted to the browser preload list.", id='security.W021', ) W022 = Warning( 'You have not set the SECURE_REFERRER_POLICY setting. Without this, your ' 'site will not send a Referrer-Policy header. You should consider ' 'enabling this header to protect user privacy.', id='security.W022', ) E023 = Error( 'You have set the SECURE_REFERRER_POLICY setting to an invalid value.', hint='Valid values are: {}.'.format(', '.join(sorted(REFERRER_POLICY_VALUES))), id='security.E023', ) E024 = Error( 'You have set the SECURE_CROSS_ORIGIN_OPENER_POLICY setting to an invalid ' 'value.', hint='Valid values are: {}.'.format( ', '.join(sorted(CROSS_ORIGIN_OPENER_POLICY_VALUES)), ), id='security.E024', ) W025 = Warning(SECRET_KEY_WARNING_MSG, id='security.W025') def _security_middleware(): return 'django.middleware.security.SecurityMiddleware' in settings.MIDDLEWARE def _xframe_middleware(): return 'django.middleware.clickjacking.XFrameOptionsMiddleware' in settings.MIDDLEWARE @register(Tags.security, deploy=True) def check_security_middleware(app_configs, **kwargs): passed_check = _security_middleware() return [] if passed_check else [W001] @register(Tags.security, deploy=True) def check_xframe_options_middleware(app_configs, **kwargs): passed_check = _xframe_middleware() return [] if passed_check else [W002] @register(Tags.security, deploy=True) def check_sts(app_configs, **kwargs): passed_check = not _security_middleware() or settings.SECURE_HSTS_SECONDS return [] if passed_check else [W004] @register(Tags.security, deploy=True) def check_sts_include_subdomains(app_configs, **kwargs): passed_check = ( not _security_middleware() or not settings.SECURE_HSTS_SECONDS or settings.SECURE_HSTS_INCLUDE_SUBDOMAINS is True ) return [] if passed_check else [W005] @register(Tags.security, deploy=True) def check_sts_preload(app_configs, **kwargs): passed_check = ( not _security_middleware() or not settings.SECURE_HSTS_SECONDS or settings.SECURE_HSTS_PRELOAD is True ) return [] if passed_check else [W021] @register(Tags.security, deploy=True) def check_content_type_nosniff(app_configs, **kwargs): passed_check = ( not _security_middleware() or settings.SECURE_CONTENT_TYPE_NOSNIFF is True ) return [] if passed_check else [W006] @register(Tags.security, deploy=True) def check_ssl_redirect(app_configs, **kwargs): passed_check = ( not _security_middleware() or settings.SECURE_SSL_REDIRECT is True ) return [] if passed_check else [W008] def _check_secret_key(secret_key): return ( len(set(secret_key)) >= SECRET_KEY_MIN_UNIQUE_CHARACTERS and len(secret_key) >= SECRET_KEY_MIN_LENGTH and not secret_key.startswith(SECRET_KEY_INSECURE_PREFIX) ) @register(Tags.security, deploy=True) def check_secret_key(app_configs, **kwargs): try: secret_key = settings.SECRET_KEY except (ImproperlyConfigured, AttributeError): passed_check = False else: passed_check = _check_secret_key(secret_key) return [] if passed_check else [W009] @register(Tags.security, deploy=True) def check_secret_key_fallbacks(app_configs, **kwargs): warnings = [] try: fallbacks = settings.SECRET_KEY_FALLBACKS except (ImproperlyConfigured, AttributeError): warnings.append( Warning(W025.msg % 'SECRET_KEY_FALLBACKS', id=W025.id) ) else: for index, key in enumerate(fallbacks): if not _check_secret_key(key): warnings.append( Warning(W025.msg % f'SECRET_KEY_FALLBACKS[{index}]', id=W025.id) ) return warnings @register(Tags.security, deploy=True) def check_debug(app_configs, **kwargs): passed_check = not settings.DEBUG return [] if passed_check else [W018] @register(Tags.security, deploy=True) def check_xframe_deny(app_configs, **kwargs): passed_check = ( not _xframe_middleware() or settings.X_FRAME_OPTIONS == 'DENY' ) return [] if passed_check else [W019] @register(Tags.security, deploy=True) def check_allowed_hosts(app_configs, **kwargs): return [] if settings.ALLOWED_HOSTS else [W020] @register(Tags.security, deploy=True) def check_referrer_policy(app_configs, **kwargs): if _security_middleware(): if settings.SECURE_REFERRER_POLICY is None: return [W022] # Support a comma-separated string or iterable of values to allow fallback. if isinstance(settings.SECURE_REFERRER_POLICY, str): values = {v.strip() for v in settings.SECURE_REFERRER_POLICY.split(',')} else: values = set(settings.SECURE_REFERRER_POLICY) if not values <= REFERRER_POLICY_VALUES: return [E023] return [] @register(Tags.security, deploy=True) def check_cross_origin_opener_policy(app_configs, **kwargs): if ( _security_middleware() and settings.SECURE_CROSS_ORIGIN_OPENER_POLICY is not None and settings.SECURE_CROSS_ORIGIN_OPENER_POLICY not in CROSS_ORIGIN_OPENER_POLICY_VALUES ): return [E024] return []
d559b6e1f5ea03d8b21aef80d816cef07c491bbb106f6a2b2a28a33662d06576
from datetime import datetime from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mechanism. """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" algorithm = None _secret = None _secret_fallbacks = None def __init__(self): self.algorithm = self.algorithm or 'sha256' def _get_secret(self): return self._secret or settings.SECRET_KEY def _set_secret(self, secret): self._secret = secret secret = property(_get_secret, _set_secret) def _get_fallbacks(self): if self._secret_fallbacks is None: return settings.SECRET_KEY_FALLBACKS return self._secret_fallbacks def _set_fallbacks(self, fallbacks): self._secret_fallbacks = fallbacks secret_fallbacks = property(_get_fallbacks, _set_fallbacks) def make_token(self, user): """ Return a token that can be used once to do a password reset for the given user. """ return self._make_token_with_timestamp( user, self._num_seconds(self._now()), self.secret, ) def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with for secret in [self.secret, *self.secret_fallbacks]: if constant_time_compare( self._make_token_with_timestamp(user, ts, secret), token, ): break else: return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True def _make_token_with_timestamp(self, user, timestamp, secret): # timestamp is number of seconds since 2001-1-1. Converted to base 36, # this gives us a 6 digit string until about 2069. ts_b36 = int_to_base36(timestamp) hash_string = salted_hmac( self.key_salt, self._make_hash_value(user, timestamp), secret=secret, algorithm=self.algorithm, ).hexdigest()[::2] # Limit to shorten the URL. return "%s-%s" % (ts_b36, hash_string) def _make_hash_value(self, user, timestamp): """ Hash the user's primary key, email (if available), and some user state that's sure to change after a password reset to produce a token that is invalidated when it's used: 1. The password field will change upon a password reset (even if the same password is chosen, due to password salting). 2. The last_login field will usually be updated very shortly after a password reset. Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually invalidates the token. Running this data through salted_hmac() prevents password cracking attempts using the reset token, provided the secret isn't compromised. """ # Truncate microseconds so that tokens are consistent even if the # database doesn't support microseconds. login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) email_field = user.get_email_field_name() email = getattr(user, email_field, '') or '' return f'{user.pk}{user.password}{login_timestamp}{timestamp}{email}' def _num_seconds(self, dt): return int((dt - datetime(2001, 1, 1)).total_seconds()) def _now(self): # Used for mocking in tests return datetime.now() default_token_generator = PasswordResetTokenGenerator()
a2e7e35a73800a94cbda133ad6a06bf9d2cbe6f5deb71dd54750ea5afd6e5b1e
import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, migrations, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_lru_cache from .models import FoodManager, FoodQuerySet class DeconstructibleObject: """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return ( self.__module__ + '.' + self.__class__.__name__, self.args, self.kwargs ) class AutodetectorTests(TestCase): """ Tests the migration autodetector. """ author_empty = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))]) author_name = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ]) author_name_null = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ]) author_name_longer = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ]) author_name_renamed = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ]) author_name_default = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default='Ada Lovelace')), ]) author_name_check_constraint = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], {'constraints': [models.CheckConstraint(check=models.Q(name__contains='Bob'), name='name_contains_bob')]}, ) author_dates_of_birth_auto_now = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now=True)), ("date_time_of_birth", models.DateTimeField(auto_now=True)), ("time_of_birth", models.TimeField(auto_now=True)), ]) author_dates_of_birth_auto_now_add = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now_add=True)), ("date_time_of_birth", models.DateTimeField(auto_now_add=True)), ("time_of_birth", models.TimeField(auto_now_add=True)), ]) author_name_deconstructible_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ]) author_name_deconstructible_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ]) author_name_deconstructible_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ]) author_name_deconstructible_4 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ]) author_name_deconstructible_list_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 123])), ]) author_name_deconstructible_list_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 123])), ]) author_name_deconstructible_list_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=[DeconstructibleObject(), 999])), ]) author_name_deconstructible_tuple_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 123))), ]) author_name_deconstructible_tuple_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 123))), ]) author_name_deconstructible_tuple_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=(DeconstructibleObject(), 999))), ]) author_name_deconstructible_dict_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 123 })), ]) author_name_deconstructible_dict_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 123 })), ]) author_name_deconstructible_dict_3 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default={ 'item': DeconstructibleObject(), 'otheritem': 999 })), ]) author_name_nested_deconstructible_1 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_2 = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_changed_arg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2-changed'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_extra_arg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), None, a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), ))), ]) author_name_nested_deconstructible_changed_kwarg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c-changed')), ))), ]) author_name_nested_deconstructible_extra_kwarg = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), (DeconstructibleObject('t1'), DeconstructibleObject('t2'),), a=DeconstructibleObject('A'), b=DeconstructibleObject(B=DeconstructibleObject('c')), c=None, ))), ]) author_custom_pk = ModelState("testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))]) author_with_biography_non_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ]) author_with_biography_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ]) author_with_book = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) author_with_book_order_wrt = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}) author_renamed_with_book = ModelState("testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) author_with_publisher_string = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ]) author_with_publisher = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) author_with_user = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ]) author_with_custom_user = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ]) author_proxy = ModelState("testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",)) author_proxy_options = ModelState("testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author",)) author_proxy_notproxy = ModelState("testapp", "AuthorProxy", [], {}, ("testapp.author",)) author_proxy_third = ModelState("thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",)) author_proxy_third_notproxy = ModelState("thirdapp", "AuthorProxy", [], {}, ("testapp.author",)) author_proxy_proxy = ModelState("testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy",)) author_unmanaged = ModelState("testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author",)) author_unmanaged_managed = ModelState("testapp", "AuthorUnmanaged", [], {}, ("testapp.author",)) author_unmanaged_default_pk = ModelState("testapp", "Author", [("id", models.AutoField(primary_key=True))]) author_unmanaged_custom_pk = ModelState("testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ]) author_with_m2m = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ]) author_with_m2m_blank = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ]) author_with_m2m_through = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract")), ]) author_with_renamed_m2m_through = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Deal")), ]) author_with_former_m2m = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ]) author_with_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [('can_hire', 'Can hire')], "verbose_name": "Authi", }) author_with_db_table_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}) author_with_new_db_table_options = ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}) author_renamed_with_db_table_options = ModelState("testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}) author_renamed_with_new_db_table_options = ModelState("testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}) contract = ModelState("testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) contract_renamed = ModelState("testapp", "Deal", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ]) publisher = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ]) publisher_with_author = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) publisher_with_aardvark_author = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) publisher_with_book = ModelState("testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ]) other_pony = ModelState("otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ]) other_pony_food = ModelState("otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ('food_qs', FoodQuerySet.as_manager()), ('food_mgr', FoodManager('a', 'b')), ('food_mgr_kwargs', FoodManager('x', 'y', 3, 4)), ]) other_stable = ModelState("otherapp", "Stable", [("id", models.AutoField(primary_key=True))]) third_thing = ModelState("thirdapp", "Thing", [("id", models.AutoField(primary_key=True))]) book = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_proxy_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_proxy_proxy_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.AAuthorProxyProxy", models.CASCADE)), ]) book_migrations_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_no_author_fk = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.IntegerField()), ("title", models.CharField(max_length=200)), ]) book_with_no_author = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ]) book_with_author_renamed = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_field_and_author_renamed = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ]) book_with_multiple_authors = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ]) book_with_multiple_authors_through_attribution = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author", through="otherapp.Attribution")), ("title", models.CharField(max_length=200)), ]) book_indexes = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [models.Index(fields=["author", "title"], name="book_title_author_idx")], }) book_unordered_indexes = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [models.Index(fields=["title", "author"], name="book_author_title_idx")], }) book_foo_together = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("author", "title")}, "unique_together": {("author", "title")}, }) book_foo_together_2 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }) book_foo_together_3 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield")}, "unique_together": {("title", "newfield")}, }) book_foo_together_4 = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield2")}, "unique_together": {("title", "newfield2")}, }) attribution = ModelState("otherapp", "Attribution", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) edition = ModelState("thirdapp", "Edition", [ ("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ]) custom_user = ModelState("thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], bases=(AbstractBaseUser,)) custom_user_no_inherit = ModelState("thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ]) aardvark = ModelState("thirdapp", "Aardvark", [("id", models.AutoField(primary_key=True))]) aardvark_testapp = ModelState("testapp", "Aardvark", [("id", models.AutoField(primary_key=True))]) aardvark_based_on_author = ModelState("testapp", "Aardvark", [], bases=("testapp.Author",)) aardvark_pk_fk_author = ModelState("testapp", "Aardvark", [ ("id", models.OneToOneField("testapp.Author", models.CASCADE, primary_key=True)), ]) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) rabbit = ModelState("eggs", "Rabbit", [ ("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight", models.CASCADE)), ("parent", models.ForeignKey("eggs.Rabbit", models.CASCADE)), ], { "unique_together": {("parent", "knight")}, "indexes": [models.Index(fields=["parent", "knight"], name='rabbit_circular_fk_index')], }) def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations_ in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations_: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail("Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), )) def assertMigrationDependencies(self, changes, app_label, position, dependencies): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] if set(migration.dependencies) != set(dependencies): self.fail("Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), )) def assertOperationTypes(self, changes, app_label, position, types): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] real_types = [operation.__class__.__name__ for operation in migration.operations] if types != real_types: self.fail("Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), )) def assertOperationAttributes(self, changes, app_label, position, operation_position, **attrs): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail("No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), )) operation = migration.operations[operation_position] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail("Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(operation, attr, None), self.repr_changes(changes), )) def assertOperationFieldAttributes(self, changes, app_label, position, operation_position, **attrs): if not changes.get(app_label): self.fail("No migrations found for %s\n%s" % (app_label, self.repr_changes(changes))) if len(changes[app_label]) < position + 1: self.fail("No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes))) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail("No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), )) operation = migration.operations[operation_position] if not hasattr(operation, 'field'): self.fail("No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_position, )) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail("Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(field, attr, None), self.repr_changes(changes), )) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def get_changes(self, before_states, after_states, questioner=None): if not isinstance(before_states, ProjectState): before_states = self.make_project_state(before_states) if not isinstance(after_states, ProjectState): after_states = self.make_project_state(after_states) return MigrationAutodetector( before_states, after_states, questioner, )._detect_changes() def test_arrange_for_graph(self): """Tests auto-naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial")) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("otherapp", "0001_initial")) # Use project state to make a new migration change set before = self.make_project_state([self.publisher, self.other_pony]) after = self.make_project_state([ self.author_empty, self.publisher, self.other_pony, self.other_stable, ]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph changes = autodetector.arrange_for_graph(changes, graph) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_author") self.assertEqual(changes["testapp"][0].dependencies, [("testapp", "0002_foobar")]) self.assertEqual(changes["otherapp"][0].name, '0002_stable') self.assertEqual(changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")]) def test_arrange_for_graph_with_multiple_initial(self): # Make a fake graph. graph = MigrationGraph() # Use project state to make a new migration change set. before = self.make_project_state([]) after = self.make_project_state([self.author_with_book, self.book, self.attribution]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({'ask_initial': True})) changes = autodetector._detect_changes() changes = autodetector.arrange_for_graph(changes, graph) self.assertEqual(changes['otherapp'][0].name, '0001_initial') self.assertEqual(changes['otherapp'][0].dependencies, []) self.assertEqual(changes['otherapp'][1].name, '0002_initial') self.assertCountEqual( changes['otherapp'][1].dependencies, [('testapp', '0001_initial'), ('otherapp', '0001_initial')], ) self.assertEqual(changes['testapp'][0].name, '0001_initial') self.assertEqual(changes['testapp'][0].dependencies, [('otherapp', '0001_initial')]) def test_trim_apps(self): """ Trim does not remove dependencies but does remove unwanted apps. """ # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable, self.third_thing]) autodetector = MigrationAutodetector(before, after, MigrationQuestioner({"ask_initial": True})) changes = autodetector._detect_changes() # Run through arrange_for_graph graph = MigrationGraph() changes = autodetector.arrange_for_graph(changes, graph) changes["testapp"][0].dependencies.append(("otherapp", "0001_initial")) changes = autodetector._trim_to_apps(changes, {"testapp"}) # Make sure there's the right set of migrations self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertNotIn("thirdapp", changes) def test_custom_migration_name(self): """Tests custom naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency("testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial")) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state([self.author_empty, self.other_pony, self.other_stable]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph migration_name = 'custom_name' changes = autodetector.arrange_for_graph(changes, graph, migration_name) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_%s" % migration_name) self.assertEqual(changes["testapp"][0].dependencies, [("testapp", "0002_foobar")]) self.assertEqual(changes["otherapp"][0].name, "0002_%s" % migration_name) self.assertEqual(changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")]) def test_new_model(self): """Tests autodetection of new models.""" changes = self.get_changes([], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Pony") self.assertEqual([name for name, mgr in changes['otherapp'][0].operations[0].managers], ['food_qs', 'food_mgr', 'food_mgr_kwargs']) def test_old_model(self): """Tests deletion of old models.""" changes = self.get_changes([self.author_empty], []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") def test_add_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_empty], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_date_fields_with_auto_now_not_asking_for_default(self, mocked_ask_method): changes = self.get_changes([self.author_empty], [self.author_dates_of_birth_auto_now]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField", "AddField"]) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now=True) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_date_fields_with_auto_now_add_not_asking_for_null_addition(self, mocked_ask_method): changes = self.get_changes([self.author_empty], [self.author_dates_of_birth_auto_now_add]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField", "AddField"]) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_auto_now_add_addition') def test_add_date_fields_with_auto_now_add_asking_for_default(self, mocked_ask_method): changes = self.get_changes([self.author_empty], [self.author_dates_of_birth_auto_now_add]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField", "AddField"]) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) self.assertEqual(mocked_ask_method.call_count, 3) def test_remove_field(self): """Tests autodetection of removed fields.""" changes = self.get_changes([self.author_name], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RemoveField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_alter_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_name], [self.author_name_longer]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) def test_supports_functools_partial(self): def _content_file_name(instance, filename, key, **kwargs): return '{}/{}'.format(instance, filename) def content_file_name(key, **kwargs): return functools.partial(_content_file_name, key, **kwargs) # An unchanged partial reference. before = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('file'))), ])] after = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('file'))), ])] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, 'testapp', 0) # A changed partial reference. args_changed = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('other-file'))), ])] changes = self.get_changes(before, args_changed) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['AlterField']) # Can't use assertOperationFieldAttributes because we need the # deconstructed version, i.e., the exploded func/args/keywords rather # than the partial: we don't care if it's not the same instance of the # partial, only if it's the same source function, args, and keywords. value = changes['testapp'][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ('other-file',), {}), (value.func, value.args, value.keywords) ) kwargs_changed = [ModelState("testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("file", models.FileField(max_length=200, upload_to=content_file_name('file', spam='eggs'))), ])] changes = self.get_changes(before, kwargs_changed) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['AlterField']) value = changes['testapp'][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ('file',), {'spam': 'eggs'}), (value.func, value.args, value.keywords) ) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', side_effect=AssertionError("Should not have prompted for not null addition")) def test_alter_field_to_not_null_with_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default='Ada Lovelace') @mock.patch( 'django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', return_value=models.NOT_PROVIDED, ) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default=models.NOT_PROVIDED) @mock.patch( 'django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', return_value='Some Name', ) def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=False) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default="Some Name") def test_rename_field(self): """Tests autodetection of renamed fields.""" changes = self.get_changes( [self.author_name], [self.author_name_renamed], MigrationQuestioner({"ask_rename": True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="name", new_name="names") def test_rename_field_foreign_key_to_field(self): before = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('field', models.IntegerField(unique=True)), ]), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('foo', models.ForeignKey('app.Foo', models.CASCADE, to_field='field')), ]), ] after = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('renamed_field', models.IntegerField(unique=True)), ]), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('foo', models.ForeignKey('app.Foo', models.CASCADE, to_field='renamed_field')), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) # Right number/type of migrations? self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['RenameField']) self.assertOperationAttributes(changes, 'app', 0, 0, old_name='field', new_name='renamed_field') def test_rename_foreign_object_fields(self): fields = ('first', 'second') renamed_fields = ('first_renamed', 'second_renamed') before = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('first', models.IntegerField()), ('second', models.IntegerField()), ], options={'unique_together': {fields}}), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('first', models.IntegerField()), ('second', models.IntegerField()), ('foo', models.ForeignObject( 'app.Foo', models.CASCADE, from_fields=fields, to_fields=fields, )), ]), ] # Case 1: to_fields renames. after = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('first_renamed', models.IntegerField()), ('second_renamed', models.IntegerField()), ], options={'unique_together': {renamed_fields}}), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('first', models.IntegerField()), ('second', models.IntegerField()), ('foo', models.ForeignObject( 'app.Foo', models.CASCADE, from_fields=fields, to_fields=renamed_fields, )), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['RenameField', 'RenameField', 'AlterUniqueTogether']) self.assertOperationAttributes( changes, 'app', 0, 0, model_name='foo', old_name='first', new_name='first_renamed', ) self.assertOperationAttributes( changes, 'app', 0, 1, model_name='foo', old_name='second', new_name='second_renamed', ) # Case 2: from_fields renames. after = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('first', models.IntegerField()), ('second', models.IntegerField()), ], options={'unique_together': {fields}}), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('first_renamed', models.IntegerField()), ('second_renamed', models.IntegerField()), ('foo', models.ForeignObject( 'app.Foo', models.CASCADE, from_fields=renamed_fields, to_fields=fields, )), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['RenameField', 'RenameField']) self.assertOperationAttributes( changes, 'app', 0, 0, model_name='bar', old_name='first', new_name='first_renamed', ) self.assertOperationAttributes( changes, 'app', 0, 1, model_name='bar', old_name='second', new_name='second_renamed', ) def test_rename_referenced_primary_key(self): before = [ ModelState('app', 'Foo', [ ('id', models.CharField(primary_key=True, serialize=False)), ]), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('foo', models.ForeignKey('app.Foo', models.CASCADE)), ]), ] after = [ ModelState('app', 'Foo', [ ('renamed_id', models.CharField(primary_key=True, serialize=False)) ]), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('foo', models.ForeignKey('app.Foo', models.CASCADE)), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['RenameField']) self.assertOperationAttributes(changes, 'app', 0, 0, old_name='id', new_name='renamed_id') def test_rename_field_preserved_db_column(self): """ RenameField is used if a field is renamed and db_column equal to the old field's column is added. """ before = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('field', models.IntegerField()), ]), ] after = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ('renamed_field', models.IntegerField(db_column='field')), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['AlterField', 'RenameField']) self.assertOperationAttributes( changes, 'app', 0, 0, model_name='foo', name='field', ) self.assertEqual(changes['app'][0].operations[0].field.deconstruct(), ( 'field', 'django.db.models.IntegerField', [], {'db_column': 'field'}, )) self.assertOperationAttributes( changes, 'app', 0, 1, model_name='foo', old_name='field', new_name='renamed_field', ) def test_rename_related_field_preserved_db_column(self): before = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('foo', models.ForeignKey('app.Foo', models.CASCADE)), ]), ] after = [ ModelState('app', 'Foo', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('app', 'Bar', [ ('id', models.AutoField(primary_key=True)), ('renamed_foo', models.ForeignKey('app.Foo', models.CASCADE, db_column='foo_id')), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['AlterField', 'RenameField']) self.assertOperationAttributes( changes, 'app', 0, 0, model_name='bar', name='foo', ) self.assertEqual(changes['app'][0].operations[0].field.deconstruct(), ( 'foo', 'django.db.models.ForeignKey', [], {'to': 'app.foo', 'on_delete': models.CASCADE, 'db_column': 'foo_id'}, )) self.assertOperationAttributes( changes, 'app', 0, 1, model_name='bar', old_name='foo', new_name='renamed_foo', ) def test_rename_field_with_renamed_model(self): changes = self.get_changes( [self.author_name], [ ModelState('testapp', 'RenamedAuthor', [ ('id', models.AutoField(primary_key=True)), ('renamed_name', models.CharField(max_length=200)), ]), ], MigrationQuestioner({'ask_rename_model': True, 'ask_rename': True}), ) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['RenameModel', 'RenameField']) self.assertOperationAttributes( changes, 'testapp', 0, 0, old_name='Author', new_name='RenamedAuthor', ) self.assertOperationAttributes( changes, 'testapp', 0, 1, old_name='name', new_name='renamed_name', ) def test_rename_model(self): """Tests autodetection of renamed models.""" changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_author_renamed], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="Author", new_name="Writer") # Now that RenameModel handles related fields too, there should be # no AlterField for the related field. self.assertNumberMigrations(changes, 'otherapp', 0) def test_rename_model_case(self): """ Model name is case-insensitive. Changing case doesn't lead to any autodetected operations. """ author_renamed = ModelState('testapp', 'author', [ ('id', models.AutoField(primary_key=True)), ]) changes = self.get_changes( [self.author_empty, self.book], [author_renamed, self.book], questioner=MigrationQuestioner({'ask_rename_model': True}), ) self.assertNumberMigrations(changes, 'testapp', 0) self.assertNumberMigrations(changes, 'otherapp', 0) def test_renamed_referenced_m2m_model_case(self): publisher_renamed = ModelState('testapp', 'publisher', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=100)), ]) changes = self.get_changes( [self.publisher, self.author_with_m2m], [publisher_renamed, self.author_with_m2m], questioner=MigrationQuestioner({'ask_rename_model': True}), ) self.assertNumberMigrations(changes, 'testapp', 0) self.assertNumberMigrations(changes, 'otherapp', 0) def test_rename_m2m_through_model(self): """ Tests autodetection of renamed models that are used in M2M relations as through models. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [self.author_with_renamed_m2m_through, self.publisher, self.contract_renamed], MigrationQuestioner({'ask_rename_model': True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['RenameModel']) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name='Contract', new_name='Deal') def test_rename_model_with_renamed_rel_field(self): """ Tests autodetection of renamed models while simultaneously renaming one of the fields that relate to the renamed model. """ changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_field_and_author_renamed], MigrationQuestioner({"ask_rename": True, "ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name="Author", new_name="Writer") # Right number/type of migrations for related field rename? # Alter is already taken care of. self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["RenameField"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, old_name="author", new_name="writer") def test_rename_model_with_fks_in_different_position(self): """ #24537 - The order of fields in a model does not influence the RenameModel detection. """ before = [ ModelState("testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ]), ModelState("testapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("some_label", models.CharField(max_length=255)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ]), ] after = [ ModelState("testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ]), ModelState("testapp", "RenamedEntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ("some_label", models.CharField(max_length=255)), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({"ask_rename_model": True})) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB") def test_rename_model_reverse_relation_dependencies(self): """ The migration to rename a model pointed to by a foreign key in another app must run after the other app's migration that adds the foreign key with model's original name. Therefore, the renaming migration has a dependency on that other migration. """ before = [ ModelState('testapp', 'EntityA', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('otherapp', 'EntityB', [ ('id', models.AutoField(primary_key=True)), ('entity_a', models.ForeignKey('testapp.EntityA', models.CASCADE)), ]), ] after = [ ModelState('testapp', 'RenamedEntityA', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('otherapp', 'EntityB', [ ('id', models.AutoField(primary_key=True)), ('entity_a', models.ForeignKey('testapp.RenamedEntityA', models.CASCADE)), ]), ] changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename_model': True})) self.assertNumberMigrations(changes, 'testapp', 1) self.assertMigrationDependencies(changes, 'testapp', 0, [('otherapp', '__first__')]) self.assertOperationTypes(changes, 'testapp', 0, ['RenameModel']) self.assertOperationAttributes(changes, 'testapp', 0, 0, old_name='EntityA', new_name='RenamedEntityA') def test_fk_dependency(self): """Having a ForeignKey automatically adds a dependency.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (author), # thirdapp (edition) depends on otherapp (book) changes = self.get_changes([], [self.author_name, self.book, self.edition]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("testapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="Edition") self.assertMigrationDependencies(changes, 'thirdapp', 0, [("otherapp", "auto_1")]) def test_proxy_fk_dependency(self): """FK dependencies still work on proxy models.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (authorproxy) changes = self.get_changes([], [self.author_empty, self.author_proxy_third, self.book_proxy_fk]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("thirdapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="AuthorProxy") self.assertMigrationDependencies(changes, 'thirdapp', 0, [("testapp", "auto_1")]) def test_same_app_no_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, []) def test_circular_fk_dependency(self): """ Having a circular ForeignKey dependency automatically resolves the situation into 2 migrations on one side and 1 on the other. """ changes = self.get_changes([], [self.author_with_book, self.book, self.publisher_with_book]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, [("otherapp", "auto_1")]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 2) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'otherapp', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'otherapp', 0, []) self.assertMigrationDependencies(changes, 'otherapp', 1, [("otherapp", "auto_1"), ("testapp", "auto_1")]) # both split migrations should be `initial` self.assertTrue(changes['otherapp'][0].initial) self.assertTrue(changes['otherapp'][1].initial) def test_same_app_circular_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher_with_author]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, 'testapp', 0, []) def test_same_app_circular_fk_dependency_with_unique_together_and_indexes(self): """ #22275 - A migration with circular FK dependency does not try to create unique together constraint and indexes before creating all required fields first. """ changes = self.get_changes([], [self.knight, self.rabbit]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'eggs', 1) self.assertOperationTypes( changes, 'eggs', 0, ["CreateModel", "CreateModel", "AddIndex", "AlterUniqueTogether"] ) self.assertNotIn("unique_together", changes['eggs'][0].operations[0].options) self.assertNotIn("unique_together", changes['eggs'][0].operations[1].options) self.assertMigrationDependencies(changes, 'eggs', 0, []) def test_alter_db_table_add(self): """Tests detection for adding db_table in model's options.""" changes = self.get_changes([self.author_empty], [self.author_with_db_table_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table="author_one") def test_alter_db_table_change(self): """Tests detection for changing db_table in model's options'.""" changes = self.get_changes([self.author_with_db_table_options], [self.author_with_new_db_table_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table="author_two") def test_alter_db_table_remove(self): """Tests detection for removing db_table in model's options.""" changes = self.get_changes([self.author_with_db_table_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", table=None) def test_alter_db_table_no_changes(self): """ Alter_db_table doesn't generate a migration if no changes have been made. """ changes = self.get_changes([self.author_with_db_table_options], [self.author_with_db_table_options]) # Right number of migrations? self.assertEqual(len(changes), 0) def test_keep_db_table_with_model_change(self): """ Tests when model changes but db_table stays as-is, autodetector must not create more than one operation. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor") def test_alter_db_table_with_model_change(self): """ Tests when model and db_table changes, autodetector must create two operations. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_new_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RenameModel", "AlterModelTable"]) self.assertOperationAttributes(changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor") self.assertOperationAttributes(changes, "testapp", 0, 1, name="newauthor", table="author_three") def test_identical_regex_doesnt_alter(self): from_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[ RegexValidator( re.compile('^[-a-zA-Z0-9_]+\\Z'), 'Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.', 'invalid' ) ]))] ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))] ) changes = self.get_changes([from_state], [to_state]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 0) def test_different_regex_does_alter(self): from_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[ RegexValidator( re.compile('^[a-z]+\\Z', 32), 'Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.', 'invalid' ) ]))] ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))] ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_empty_foo_together(self): """ #23452 - Empty unique/index_together shouldn't generate a migration. """ # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState("a", "model", [("id", models.AutoField(primary_key=True))]) # Explicitly testing for None, since this was the issue in #23452 after # an AlterFooTogether operation with e.g. () as value model_state_none = ModelState("a", "model", [ ("id", models.AutoField(primary_key=True)) ], { "index_together": None, "unique_together": None, }) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState("a", "model", [ ("id", models.AutoField(primary_key=True)) ], { "index_together": set(), "unique_together": set(), }) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ', '.join(o.__class__.__name__ for o in changes['a'][0].operations) self.fail('Created operation(s) %s from %s' % (ops, msg)) tests = ( (model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"'), (model_state_not_specified, model_state_none, '"not specified" to "None"'), (model_state_not_specified, model_state_empty, '"not specified" to "empty"'), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), (model_state_empty, model_state_not_specified, '"empty" to "not specified"'), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_create_model_with_indexes(self): """Test creation of new model with indexes already defined.""" author = ModelState('otherapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]}) changes = self.get_changes([], [author]) added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx') # Right number of migrations? self.assertEqual(len(changes['otherapp']), 1) # Right number of actions? migration = changes['otherapp'][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author') self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) def test_add_indexes(self): """Test change detection of new indexes.""" changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_indexes]) self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AddIndex']) added_index = models.Index(fields=['author', 'title'], name='book_title_author_idx') self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', index=added_index) def test_remove_indexes(self): """Test change detection of removed indexes.""" changes = self.get_changes([self.author_empty, self.book_indexes], [self.author_empty, self.book]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveIndex']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', name='book_title_author_idx') def test_order_fields_indexes(self): """Test change detection of reordering of fields in indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book_unordered_indexes] ) self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveIndex', 'AddIndex']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', name='book_title_author_idx') added_index = models.Index(fields=['title', 'author'], name='book_author_title_idx') self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='book', index=added_index) def test_create_model_with_check_constraint(self): """Test creation of new model with constraints already defined.""" author = ModelState('otherapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ], {'constraints': [models.CheckConstraint(check=models.Q(name__contains='Bob'), name='name_contains_bob')]}) changes = self.get_changes([], [author]) added_constraint = models.CheckConstraint(check=models.Q(name__contains='Bob'), name='name_contains_bob') # Right number of migrations? self.assertEqual(len(changes['otherapp']), 1) # Right number of actions? migration = changes['otherapp'][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddConstraint']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author') self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', constraint=added_constraint) def test_add_constraints(self): """Test change detection of new constraints.""" changes = self.get_changes([self.author_name], [self.author_name_check_constraint]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['AddConstraint']) added_constraint = models.CheckConstraint(check=models.Q(name__contains='Bob'), name='name_contains_bob') self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name='author', constraint=added_constraint) def test_remove_constraints(self): """Test change detection of removed constraints.""" changes = self.get_changes([self.author_name_check_constraint], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['RemoveConstraint']) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name='author', name='name_contains_bob') def test_add_foo_together(self): """Tests index/unique_together detection.""" changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_foo_together]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together={("author", "title")}) def test_remove_foo_together(self): """Tests index/unique_together detection.""" changes = self.get_changes([self.author_empty, self.book_foo_together], [self.author_empty, self.book]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together=set()) def test_foo_together_remove_fk(self): """Tests unique_together and field removal detection & ordering""" changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_with_no_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, [ "AlterUniqueTogether", "AlterIndexTogether", "RemoveField" ]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="book", unique_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", index_together=set()) self.assertOperationAttributes(changes, "otherapp", 0, 2, model_name="book", name="author") def test_foo_together_no_changes(self): """ index/unique_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_foo_together] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_foo_together_ordering(self): """ index/unique_together also triggers on ordering changes. """ changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_foo_together_2] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, 'otherapp', 0, [ 'AlterUniqueTogether', 'AlterIndexTogether', ]) self.assertOperationAttributes( changes, 'otherapp', 0, 0, name='book', unique_together={('title', 'author')}, ) self.assertOperationAttributes( changes, 'otherapp', 0, 1, name='book', index_together={('title', 'author')}, ) def test_add_field_and_foo_together(self): """ Added fields will be created before using them in index/unique_together. """ changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_foo_together_3]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AddField", "AlterUniqueTogether", "AlterIndexTogether"]) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield")}) self.assertOperationAttributes(changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield")}) def test_create_model_and_unique_together(self): author = ModelState("otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ]) book_with_author = ModelState("otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }) changes = self.get_changes([self.book_with_no_author], [author, book_with_author]) # Right number of migrations? self.assertEqual(len(changes['otherapp']), 1) # Right number of actions? migration = changes['otherapp'][0] self.assertEqual(len(migration.operations), 4) # Right actions order? self.assertOperationTypes( changes, 'otherapp', 0, ['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether'] ) def test_remove_field_and_foo_together(self): """ Removed fields will be removed after updating index/unique_together. """ changes = self.get_changes( [self.author_empty, self.book_foo_together_3], [self.author_empty, self.book_foo_together] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, 'otherapp', 0, [ 'AlterUniqueTogether', 'AlterIndexTogether', 'RemoveField', ]) self.assertOperationAttributes( changes, 'otherapp', 0, 0, name='book', unique_together={('author', 'title')}, ) self.assertOperationAttributes( changes, 'otherapp', 0, 1, name='book', index_together={('author', 'title')}, ) self.assertOperationAttributes( changes, 'otherapp', 0, 2, model_name='book', name='newfield', ) def test_alter_field_and_foo_together(self): """Fields are altered after deleting some index/unique_together.""" initial_author = ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ('age', models.IntegerField(db_index=True)), ], { 'unique_together': {('name',)}, }) author_reversed_constraints = ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200, unique=True)), ('age', models.IntegerField()), ], { 'index_together': {('age',)}, }) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, [ 'AlterUniqueTogether', 'AlterField', 'AlterField', 'AlterIndexTogether', ]) self.assertOperationAttributes( changes, 'testapp', 0, 0, name='author', unique_together=set(), ) self.assertOperationAttributes( changes, 'testapp', 0, 1, model_name='author', name='age', ) self.assertOperationAttributes( changes, 'testapp', 0, 2, model_name='author', name='name', ) self.assertOperationAttributes( changes, 'testapp', 0, 3, name='author', index_together={('age',)}, ) def test_partly_alter_foo_together(self): initial_author = ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ('age', models.IntegerField()), ], { 'unique_together': {('name',), ('age',)}, 'index_together': {('name',)}, }) author_reversed_constraints = ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ('age', models.IntegerField()), ], { 'unique_together': {('age',)}, 'index_together': {('name',), ('age',)}, }) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, [ 'AlterUniqueTogether', 'AlterIndexTogether', ]) self.assertOperationAttributes( changes, 'testapp', 0, 0, name='author', unique_together={('age',)}, ) self.assertOperationAttributes( changes, 'testapp', 0, 1, name='author', index_together={('name',), ('age',)}, ) def test_rename_field_and_foo_together(self): """Fields are renamed before updating index/unique_together.""" changes = self.get_changes( [self.author_empty, self.book_foo_together_3], [self.author_empty, self.book_foo_together_4], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, 'otherapp', 0, [ 'RenameField', 'AlterUniqueTogether', 'AlterIndexTogether', ]) self.assertOperationAttributes( changes, 'otherapp', 0, 1, name='book', unique_together={('title', 'newfield2')}, ) self.assertOperationAttributes( changes, 'otherapp', 0, 2, name='book', index_together={('title', 'newfield2')}, ) def test_proxy(self): """The autodetector correctly deals with proxy models.""" # First, we test adding a proxy model changes = self.get_changes([self.author_empty], [self.author_empty, self.author_proxy]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []} ) # Now, we test turning a proxy model into a non-proxy model # It should delete the proxy then make the real one changes = self.get_changes( [self.author_empty, self.author_proxy], [self.author_empty, self.author_proxy_notproxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy") self.assertOperationAttributes(changes, "testapp", 0, 1, name="AuthorProxy", options={}) def test_proxy_non_model_parent(self): class Mixin: pass author_proxy_non_model_parent = ModelState( 'testapp', 'AuthorProxy', [], {'proxy': True}, (Mixin, 'testapp.author'), ) changes = self.get_changes( [self.author_empty], [self.author_empty, author_proxy_non_model_parent], ) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['CreateModel']) self.assertOperationAttributes( changes, 'testapp', 0, 0, name='AuthorProxy', options={'proxy': True, 'indexes': [], 'constraints': []}, bases=(Mixin, 'testapp.author'), ) def test_proxy_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on proxy models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_empty, self.author_proxy_third, self.book_proxy_fk]) # The model the FK is pointing from and to. self.assertEqual( changes['otherapp'][0].operations[0].fields[2][1].remote_field.model, 'thirdapp.AuthorProxy', ) # Now, we test the custom pk field name changes = self.get_changes([], [self.author_custom_pk, self.author_proxy_third, self.book_proxy_fk]) # The model the FK is pointing from and to. self.assertEqual( changes['otherapp'][0].operations[0].fields[2][1].remote_field.model, 'thirdapp.AuthorProxy', ) def test_proxy_to_mti_with_fk_to_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [self.author_empty, self.author_proxy_third, self.book_proxy_fk], ) changes = self.get_changes([], to_state) fk_field = changes['otherapp'][0].operations[0].fields[2][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ('testapp', 'author'), ) self.assertEqual(fk_field.remote_field.model, 'thirdapp.AuthorProxy') # Change AuthorProxy to use MTI. from_state = to_state.clone() to_state = self.make_project_state( [self.author_empty, self.author_proxy_third_notproxy, self.book_proxy_fk], ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ['DeleteModel', 'CreateModel']) # Right number/type of migrations for the Book model with a FK to # AuthorProxy? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AlterField']) # otherapp should depend on thirdapp. self.assertMigrationDependencies(changes, 'otherapp', 0, [('thirdapp', 'auto_1')]) # Now, test the pk table and field name. fk_field = changes['otherapp'][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ('thirdapp', 'authorproxy'), ) self.assertEqual(fk_field.remote_field.model, 'thirdapp.AuthorProxy') def test_proxy_to_mti_with_fk_to_proxy_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state([ self.author_empty, self.author_proxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ]) changes = self.get_changes([], to_state) fk_field = changes['otherapp'][0].operations[0].fields[1][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ('testapp', 'author'), ) self.assertEqual(fk_field.remote_field.model, 'testapp.AAuthorProxyProxy') # Change AuthorProxy to use MTI. FK still points to AAuthorProxyProxy, # a proxy of AuthorProxy. from_state = to_state.clone() to_state = self.make_project_state([ self.author_empty, self.author_proxy_notproxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ]) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['DeleteModel', 'CreateModel']) # Right number/type of migrations for the Book model with a FK to # AAuthorProxyProxy? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AlterField']) # otherapp should depend on testapp. self.assertMigrationDependencies(changes, 'otherapp', 0, [('testapp', 'auto_1')]) # Now, test the pk table and field name. fk_field = changes['otherapp'][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ('testapp', 'authorproxy'), ) self.assertEqual(fk_field.remote_field.model, 'testapp.AAuthorProxyProxy') def test_unmanaged_create(self): """The autodetector correctly deals with managed models.""" # First, we test adding an unmanaged model changes = self.get_changes([self.author_empty], [self.author_empty, self.author_unmanaged]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="AuthorUnmanaged", options={"managed": False}) def test_unmanaged_delete(self): changes = self.get_changes([self.author_empty, self.author_unmanaged], [self.author_empty]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['DeleteModel']) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty, self.author_unmanaged_managed] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="authorunmanaged", options={}) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. changes = self.get_changes( [self.author_empty, self.author_unmanaged_managed], [self.author_empty, self.author_unmanaged] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False}) def test_unmanaged_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on unmanaged models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_unmanaged_default_pk, self.book]) # The model the FK on the book model points to. fk_field = changes['otherapp'][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, 'testapp.Author') # Now, we test the custom pk field name changes = self.get_changes([], [self.author_unmanaged_custom_pk, self.book]) # The model the FK on the book model points to. fk_field = changes['otherapp'][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, 'testapp.Author') @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable(self): with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([self.custom_user], [self.custom_user, self.author_with_custom_user]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertMigrationDependencies(changes, 'testapp', 0, [("__setting__", "AUTH_USER_MODEL")]) def test_swappable_lowercase(self): model_state = ModelState('testapp', 'Document', [ ('id', models.AutoField(primary_key=True)), ('owner', models.ForeignKey( settings.AUTH_USER_MODEL.lower(), models.CASCADE, )), ]) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['CreateModel']) self.assertOperationAttributes(changes, 'testapp', 0, 0, name='Document') self.assertMigrationDependencies( changes, 'testapp', 0, [('__setting__', 'AUTH_USER_MODEL')], ) def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user]) with override_settings(AUTH_USER_MODEL="thirdapp.CustomUser"): after = self.make_project_state([self.custom_user, self.author_with_custom_user]) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name="author", name='user') fk_field = changes['testapp'][0].operations[0].field self.assertEqual(fk_field.remote_field.model, 'thirdapp.CustomUser') def test_add_field_with_default(self): """#22030 - Adding a field with a default should work.""" changes = self.get_changes([self.author_empty], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="name") def test_custom_deconstructible(self): """ Two instances which deconstruct to the same value aren't considered a change. """ changes = self.get_changes([self.author_name_deconstructible_1], [self.author_name_deconstructible_2]) # Right number of migrations? self.assertEqual(len(changes), 0) def test_deconstruct_field_kwarg(self): """Field instances are handled correctly by nested deconstruction.""" changes = self.get_changes([self.author_name_deconstructible_3], [self.author_name_deconstructible_4]) self.assertEqual(changes, {}) def test_deconstructible_list(self): """Nested deconstruction descends into lists.""" # When lists contain items that deconstruct to identical values, those lists # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_2] ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed lists should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_3] ) self.assertEqual(len(changes), 1) def test_deconstructible_tuple(self): """Nested deconstruction descends into tuples.""" # When tuples contain items that deconstruct to identical values, those tuples # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_2] ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed tuples should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_3] ) self.assertEqual(len(changes), 1) def test_deconstructible_dict(self): """Nested deconstruction descends into dict values.""" # When dicts contain items whose values deconstruct to identical values, # those dicts should be considered equal for the purpose of detecting # state changes (even if the original values are unequal). changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_2] ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed dicts should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_3] ) self.assertEqual(len(changes), 1) def test_nested_deconstructible_objects(self): """ Nested deconstruction is applied recursively to the args/kwargs of deconstructed objects. """ # If the items within a deconstructed object's args/kwargs have the same # deconstructed values - whether or not the items themselves are different # instances - then the object as a whole is regarded as unchanged. changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_2] ) self.assertEqual(changes, {}) # Differences that exist solely within the args list of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_arg] ) self.assertEqual(len(changes), 1) # Additional args should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_arg] ) self.assertEqual(len(changes), 1) # Differences that exist solely within the kwargs dict of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_kwarg] ) self.assertEqual(len(changes), 1) # Additional kwargs should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_kwarg] ) self.assertEqual(len(changes), 1) def test_deconstruct_type(self): """ #22951 -- Uninstantiated classes with deconstruct are correctly returned by deep_deconstruct during serialization. """ author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField( max_length=200, # IntegerField intentionally not instantiated. default=models.IntegerField, )) ], ) changes = self.get_changes([], [author]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) def test_replace_string_with_foreignkey(self): """ #22300 - Adding an FK in the same "spot" as a deleted CharField should work. """ changes = self.get_changes([self.author_with_publisher_string], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "RemoveField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Publisher") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publisher_name") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="publisher") def test_foreign_key_removed_before_target_model(self): """ Removing an FK and the model it targets in the same change must remove the FK field before the model to maintain consistency. """ changes = self.get_changes( [self.author_with_publisher, self.publisher], [self.author_name] ) # removes both the model and FK # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publisher") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Publisher") @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_many_to_many(self, mocked_ask_method): """#22435 - Adding a ManyToManyField should not prompt for a default.""" changes = self.get_changes([self.author_empty, self.publisher], [self.author_with_m2m, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers") def test_alter_many_to_many(self): changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_m2m_blank, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers") def test_create_with_through_model(self): """ Adding a m2m with a through model and the models that use it should be ordered correctly. """ changes = self.get_changes([], [self.author_with_m2m_through, self.publisher, self.contract]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, [ 'CreateModel', 'CreateModel', 'CreateModel', 'AddField', ]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name='Author') self.assertOperationAttributes(changes, 'testapp', 0, 1, name='Publisher') self.assertOperationAttributes(changes, 'testapp', 0, 2, name='Contract') self.assertOperationAttributes(changes, 'testapp', 0, 3, model_name='author', name='publishers') def test_many_to_many_removed_before_through_model(self): """ Removing a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution], [self.book_with_no_author, self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveField', 'DeleteModel']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='authors', model_name='book') self.assertOperationAttributes(changes, 'otherapp', 0, 1, name='Attribution') def test_many_to_many_removed_before_through_model_2(self): """ Removing a model that contains a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution], [self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveField', 'DeleteModel', 'DeleteModel']) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='authors', model_name='book') self.assertOperationAttributes(changes, 'otherapp', 0, 1, name='Attribution') self.assertOperationAttributes(changes, 'otherapp', 0, 2, name='Book') def test_m2m_w_through_multistep_remove(self): """ A model with a m2m field that specifies a "through" model cannot be removed in the same migration as that through model as the schema will pass through an inconsistent state. The autodetector should produce two migrations to avoid this issue. """ changes = self.get_changes([self.author_with_m2m_through, self.publisher, self.contract], [self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, [ "RemoveField", "RemoveField", "DeleteModel", "DeleteModel" ]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", model_name='contract') self.assertOperationAttributes(changes, "testapp", 0, 1, name="publisher", model_name='contract') self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 3, name="Contract") def test_concrete_field_changed_to_many_to_many(self): """ #23938 - Changing a concrete field into a ManyToManyField first removes the concrete field and then adds the m2m field. """ changes = self.get_changes([self.author_with_former_m2m], [self.author_with_m2m, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name='Publisher') self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 2, name="publishers", model_name='author') def test_many_to_many_changed_to_concrete_field(self): """ #23938 - Changing a ManyToManyField into a concrete field first removes the m2m field and then adds the concrete field. """ changes = self.get_changes([self.author_with_m2m, self.publisher], [self.author_with_former_m2m]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "AddField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 1, name="publishers", model_name='author') self.assertOperationAttributes(changes, 'testapp', 0, 2, name='Publisher') self.assertOperationFieldAttributes(changes, 'testapp', 0, 1, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ If two models with a ForeignKey from one to the other are removed at the same time, the autodetector should remove them in the correct order. """ changes = self.get_changes([self.author_with_publisher, self.publisher_with_author], []) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", model_name='publisher') self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Publisher") def test_alter_model_options(self): """Changing a model's options should make a change.""" changes = self.get_changes([self.author_empty], [self.author_with_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, options={ "permissions": [('can_hire', 'Can hire')], "verbose_name": "Authi", }) # Changing them back to empty should also make a change changes = self.get_changes([self.author_with_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="author", options={}) def test_alter_model_options_proxy(self): """Changing a proxy model's options should also make a change.""" changes = self.get_changes( [self.author_proxy, self.author_empty], [self.author_proxy_options, self.author_empty] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorproxy", options={ "verbose_name": "Super Author" }) def test_set_alter_order_with_respect_to(self): """Setting order_with_respect_to adds a field.""" changes = self.get_changes([self.book, self.author_with_book], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="author", order_with_respect_to="book") def test_add_alter_order_with_respect_to(self): """ Setting order_with_respect_to when adding the FK too does things in the right order. """ changes = self.get_changes([self.author_name], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AlterOrderWithRespectTo"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, model_name="author", name="book") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author", order_with_respect_to="book") def test_remove_alter_order_with_respect_to(self): """ Removing order_with_respect_to when removing the FK too does things in the right order. """ changes = self.get_changes([self.book, self.author_with_book_order_wrt], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterOrderWithRespectTo", "RemoveField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="author", order_with_respect_to=None) self.assertOperationAttributes(changes, 'testapp', 0, 1, model_name="author", name="book") def test_add_model_order_with_respect_to(self): """ Setting order_with_respect_to when adding the whole model does things in the right order. """ changes = self.get_changes([], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationAttributes( changes, 'testapp', 0, 0, name="Author", options={'order_with_respect_to': 'book'} ) self.assertNotIn("_order", [name for name, field in changes['testapp'][0].operations[0].fields]) def test_add_model_order_with_respect_to_index_foo_together(self): changes = self.get_changes([], [ self.book, ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ('book', models.ForeignKey('otherapp.Book', models.CASCADE)), ], options={ 'order_with_respect_to': 'book', 'index_together': {('name', '_order')}, 'unique_together': {('id', '_order')}, }), ]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['CreateModel']) self.assertOperationAttributes( changes, 'testapp', 0, 0, name='Author', options={ 'order_with_respect_to': 'book', 'index_together': {('name', '_order')}, 'unique_together': {('id', '_order')}, }, ) def test_add_model_order_with_respect_to_index_constraint(self): tests = [ ( 'AddIndex', {'indexes': [ models.Index(fields=['_order'], name='book_order_idx'), ]}, ), ( 'AddConstraint', {'constraints': [ models.CheckConstraint( check=models.Q(_order__gt=1), name='book_order_gt_1', ), ]}, ), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ('book', models.ForeignKey('otherapp.Book', models.CASCADE)), ], options={ 'order_with_respect_to': 'book', **extra_option, }) changes = self.get_changes([], [self.book, after]) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, [ 'CreateModel', operation, ]) self.assertOperationAttributes( changes, 'testapp', 0, 0, name='Author', options={'order_with_respect_to': 'book'}, ) def test_set_alter_order_with_respect_to_index_constraint_foo_together(self): tests = [ ( 'AddIndex', {'indexes': [ models.Index(fields=['_order'], name='book_order_idx'), ]}, ), ( 'AddConstraint', {'constraints': [ models.CheckConstraint( check=models.Q(_order__gt=1), name='book_order_gt_1', ), ]}, ), ('AlterIndexTogether', {'index_together': {('name', '_order')}}), ('AlterUniqueTogether', {'unique_together': {('id', '_order')}}), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState('testapp', 'Author', [ ('id', models.AutoField(primary_key=True)), ('name', models.CharField(max_length=200)), ('book', models.ForeignKey('otherapp.Book', models.CASCADE)), ], options={ 'order_with_respect_to': 'book', **extra_option, }) changes = self.get_changes( [self.book, self.author_with_book], [self.book, after], ) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, [ 'AlterOrderWithRespectTo', operation, ]) def test_alter_model_managers(self): """ Changing the model managers adds a new operation. """ changes = self.get_changes([self.other_pony], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["AlterModelManagers"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="pony") self.assertEqual([name for name, mgr in changes['otherapp'][0].operations[0].managers], ['food_qs', 'food_mgr', 'food_mgr_kwargs']) self.assertEqual(changes['otherapp'][0].operations[0].managers[1][1].args, ('a', 'b', 1, 2)) self.assertEqual(changes['otherapp'][0].operations[0].managers[2][1].args, ('x', 'y', 3, 4)) def test_swappable_first_inheritance(self): """Swappable models get their CreateModel first.""" changes = self.get_changes([], [self.custom_user, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="CustomUser") self.assertOperationAttributes(changes, 'thirdapp', 0, 1, name="Aardvark") def test_default_related_name_option(self): model_state = ModelState('app', 'model', [ ('id', models.AutoField(primary_key=True)), ], options={'default_related_name': 'related_name'}) changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['CreateModel']) self.assertOperationAttributes( changes, 'app', 0, 0, name='model', options={'default_related_name': 'related_name'}, ) altered_model_state = ModelState('app', 'Model', [ ('id', models.AutoField(primary_key=True)), ]) changes = self.get_changes([model_state], [altered_model_state]) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['AlterModelOptions']) self.assertOperationAttributes(changes, 'app', 0, 0, name='model', options={}) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_first_setting(self): """Swappable models get their CreateModel first.""" with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [self.custom_user_no_inherit, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'thirdapp', 1) self.assertOperationTypes(changes, 'thirdapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'thirdapp', 0, 0, name="CustomUser") self.assertOperationAttributes(changes, 'thirdapp', 0, 1, name="Aardvark") def test_bases_first(self): """Bases of other models come first.""" changes = self.get_changes([], [self.aardvark_based_on_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Aardvark") def test_bases_first_mixed_case_app_label(self): app_label = 'MiXedCaseApp' changes = self.get_changes([], [ ModelState(app_label, 'owner', [ ('id', models.AutoField(primary_key=True)), ]), ModelState(app_label, 'place', [ ('id', models.AutoField(primary_key=True)), ('owner', models.ForeignKey('MiXedCaseApp.owner', models.CASCADE)), ]), ModelState(app_label, 'restaurant', [], bases=('MiXedCaseApp.place',)), ]) self.assertNumberMigrations(changes, app_label, 1) self.assertOperationTypes(changes, app_label, 0, [ 'CreateModel', 'CreateModel', 'CreateModel', ]) self.assertOperationAttributes(changes, app_label, 0, 0, name='owner') self.assertOperationAttributes(changes, app_label, 0, 1, name='place') self.assertOperationAttributes(changes, app_label, 0, 2, name='restaurant') def test_multiple_bases(self): """#23956 - Inheriting models doesn't move *_ptr fields into AddField operations.""" A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))]) B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))]) C = ModelState("app", "C", [], bases=("app.A", "app.B")) D = ModelState("app", "D", [], bases=("app.A", "app.B")) E = ModelState("app", "E", [], bases=("app.A", "app.B")) changes = self.get_changes([], [A, B, C, D, E]) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, [ "CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel" ]) self.assertOperationAttributes(changes, "app", 0, 0, name="A") self.assertOperationAttributes(changes, "app", 0, 1, name="B") self.assertOperationAttributes(changes, "app", 0, 2, name="C") self.assertOperationAttributes(changes, "app", 0, 3, name="D") self.assertOperationAttributes(changes, "app", 0, 4, name="E") def test_proxy_bases_first(self): """Bases of proxies come first.""" changes = self.get_changes([], [self.author_empty, self.author_proxy, self.author_proxy_proxy]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="AuthorProxy") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="AAuthorProxyProxy") def test_pk_fk_included(self): """ A relation used as the primary key is kept as part of CreateModel. """ changes = self.get_changes([], [self.aardvark_pk_fk_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Author") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="Aardvark") def test_first_dependency(self): """ A dependency to an app with no migrations uses __first__. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {'migrations'} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("migrations", "__first__")]) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_last_dependency(self): """ A dependency to an app with existing migrations uses the last migration of that app. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {'migrations'} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ["CreateModel"]) self.assertOperationAttributes(changes, 'otherapp', 0, 0, name="Book") self.assertMigrationDependencies(changes, 'otherapp', 0, [("migrations", "0002_second")]) def test_alter_fk_before_model_deletion(self): """ ForeignKeys are altered _before_ the model they used to refer to are deleted. """ changes = self.get_changes( [self.author_name, self.publisher_with_author], [self.aardvark_testapp, self.publisher_with_aardvark_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel", "AlterField", "DeleteModel"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="Aardvark") self.assertOperationAttributes(changes, 'testapp', 0, 1, name="author") self.assertOperationAttributes(changes, 'testapp', 0, 2, name="Author") def test_fk_dependency_other_app(self): """ #23100 - ForeignKeys correctly depend on other apps' models. """ changes = self.get_changes([self.author_name, self.book], [self.author_with_book, self.book]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0, name="book") self.assertMigrationDependencies(changes, 'testapp', 0, [("otherapp", "__first__")]) def test_alter_field_to_fk_dependency_other_app(self): changes = self.get_changes( [self.author_empty, self.book_with_no_author_fk], [self.author_empty, self.book], ) self.assertNumberMigrations(changes, 'otherapp', 1) self.assertOperationTypes(changes, 'otherapp', 0, ['AlterField']) self.assertMigrationDependencies(changes, 'otherapp', 0, [('testapp', '__first__')]) def test_circular_dependency_mixed_addcreate(self): """ #23315 - The dependency resolver knows to put all CreateModel before AddField and not become unsolvable. """ address = ModelState("a", "Address", [ ("id", models.AutoField(primary_key=True)), ("country", models.ForeignKey("b.DeliveryCountry", models.CASCADE)), ]) person = ModelState("a", "Person", [ ("id", models.AutoField(primary_key=True)), ]) apackage = ModelState("b", "APackage", [ ("id", models.AutoField(primary_key=True)), ("person", models.ForeignKey("a.Person", models.CASCADE)), ]) country = ModelState("b", "DeliveryCountry", [ ("id", models.AutoField(primary_key=True)), ]) changes = self.get_changes([], [address, person, apackage, country]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'a', 0, ["CreateModel", "CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertOperationTypes(changes, 'b', 0, ["CreateModel", "CreateModel"]) @override_settings(AUTH_USER_MODEL="a.Tenant") def test_circular_dependency_swappable(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): tenant = ModelState("a", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("b.Address", models.CASCADE))], bases=(AbstractBaseUser,) ) address = ModelState("b", "Address", [ ("id", models.AutoField(primary_key=True)), ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)), ]) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'a', 0, []) self.assertMigrationDependencies(changes, 'a', 1, [('a', 'auto_1'), ('b', 'auto_1')]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'b', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'b', 0, [('__setting__', 'AUTH_USER_MODEL')]) @override_settings(AUTH_USER_MODEL="b.Tenant") def test_circular_dependency_swappable2(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models but with the swappable not being the first migrated model. """ with isolate_lru_cache(apps.get_swappable_settings_name): address = ModelState("a", "Address", [ ("id", models.AutoField(primary_key=True)), ("tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)), ]) tenant = ModelState("b", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("a.Address", models.CASCADE))], bases=(AbstractBaseUser,) ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 2) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'a', 1, ["AddField"]) self.assertMigrationDependencies(changes, 'a', 0, []) self.assertMigrationDependencies(changes, 'a', 1, [('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'b', 1) self.assertOperationTypes(changes, 'b', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'b', 0, [('a', 'auto_1')]) @override_settings(AUTH_USER_MODEL="a.Person") def test_circular_dependency_swappable_self(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): person = ModelState("a", "Person", [ ("id", models.AutoField(primary_key=True)), ("parent1", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE, related_name='children')) ]) changes = self.get_changes([], [person]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'a', 1) self.assertOperationTypes(changes, 'a', 0, ["CreateModel"]) self.assertMigrationDependencies(changes, 'a', 0, []) @override_settings(AUTH_USER_MODEL='a.User') def test_swappable_circular_multi_mti(self): with isolate_lru_cache(apps.get_swappable_settings_name): parent = ModelState('a', 'Parent', [ ('user', models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)) ]) child = ModelState('a', 'Child', [], bases=('a.Parent',)) user = ModelState('a', 'User', [], bases=(AbstractBaseUser, 'a.Child')) changes = self.get_changes([], [parent, child, user]) self.assertNumberMigrations(changes, 'a', 1) self.assertOperationTypes(changes, 'a', 0, ['CreateModel', 'CreateModel', 'CreateModel', 'AddField']) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition', side_effect=AssertionError("Should not have prompted for not null addition")) def test_add_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and blank `CharField` or `TextField` without default should not prompt for a default. """ changes = self.get_changes([self.author_empty], [self.author_with_biography_blank]) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0) @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition') def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField` without default should prompt for a default. """ changes = self.get_changes([self.author_empty], [self.author_with_biography_non_blank]) self.assertEqual(mocked_ask_method.call_count, 2) # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, 'testapp', 0, 0) def test_mti_inheritance_model_removal(self): Animal = ModelState('app', 'Animal', [ ("id", models.AutoField(primary_key=True)), ]) Dog = ModelState('app', 'Dog', [], bases=('app.Animal',)) changes = self.get_changes([Animal, Dog], [Animal]) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['DeleteModel']) self.assertOperationAttributes(changes, 'app', 0, 0, name='Dog') def test_add_model_with_field_removed_from_base_model(self): """ Removing a base field takes place before adding a new inherited model that has a field with the same name. """ before = [ ModelState('app', 'readable', [ ('id', models.AutoField(primary_key=True)), ('title', models.CharField(max_length=200)), ]), ] after = [ ModelState('app', 'readable', [ ('id', models.AutoField(primary_key=True)), ]), ModelState('app', 'book', [ ('title', models.CharField(max_length=200)), ], bases=('app.readable',)), ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, 'app', 1) self.assertOperationTypes(changes, 'app', 0, ['RemoveField', 'CreateModel']) self.assertOperationAttributes(changes, 'app', 0, 0, name='title', model_name='readable') self.assertOperationAttributes(changes, 'app', 0, 1, name='book') def test_parse_number(self): tests = [ ('no_number', None), ('0001_initial', 1), ('0002_model3', 2), ('0002_auto_20380101_1112', 2), ('0002_squashed_0003', 3), ('0002_model2_squashed_0003_other4', 3), ('0002_squashed_0003_squashed_0004', 4), ('0002_model2_squashed_0003_other4_squashed_0005_other6', 5), ('0002_custom_name_20380101_1112_squashed_0003_model', 3), ('2_squashed_4', 4), ] for migration_name, expected_number in tests: with self.subTest(migration_name=migration_name): self.assertEqual( MigrationAutodetector.parse_number(migration_name), expected_number, ) def test_add_custom_fk_with_hardcoded_to(self): class HardcodedForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs['to'] = 'testapp.Author' super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs['to'] return name, path, args, kwargs book_hardcoded_fk_to = ModelState('testapp', 'Book', [ ('author', HardcodedForeignKey(on_delete=models.CASCADE)), ]) changes = self.get_changes( [self.author_empty], [self.author_empty, book_hardcoded_fk_to], ) self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ['CreateModel']) self.assertOperationAttributes(changes, 'testapp', 0, 0, name='Book') class MigrationSuggestNameTests(SimpleTestCase): def test_no_operations(self): class Migration(migrations.Migration): operations = [] migration = Migration('some_migration', 'test_app') self.assertIs(migration.suggest_name().startswith('auto_'), True) def test_no_operations_initial(self): class Migration(migrations.Migration): initial = True operations = [] migration = Migration('some_migration', 'test_app') self.assertEqual(migration.suggest_name(), 'initial') def test_single_operation(self): class Migration(migrations.Migration): operations = [migrations.CreateModel('Person', fields=[])] migration = Migration('0001_initial', 'test_app') self.assertEqual(migration.suggest_name(), 'person') class Migration(migrations.Migration): operations = [migrations.DeleteModel('Person')] migration = Migration('0002_initial', 'test_app') self.assertEqual(migration.suggest_name(), 'delete_person') def test_single_operation_long_name(self): class Migration(migrations.Migration): operations = [migrations.CreateModel('A' * 53, fields=[])] migration = Migration('some_migration', 'test_app') self.assertEqual(migration.suggest_name(), 'a' * 53) def test_two_operations(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel('Person', fields=[]), migrations.DeleteModel('Animal'), ] migration = Migration('some_migration', 'test_app') self.assertEqual(migration.suggest_name(), 'person_delete_animal') def test_two_create_models(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel('Person', fields=[]), migrations.CreateModel('Animal', fields=[]), ] migration = Migration('0001_initial', 'test_app') self.assertEqual(migration.suggest_name(), 'person_animal') def test_two_create_models_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel('Person', fields=[]), migrations.CreateModel('Animal', fields=[]), ] migration = Migration('0001_initial', 'test_app') self.assertEqual(migration.suggest_name(), 'initial') def test_many_operations_suffix(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel('Person1', fields=[]), migrations.CreateModel('Person2', fields=[]), migrations.CreateModel('Person3', fields=[]), migrations.DeleteModel('Person4'), migrations.DeleteModel('Person5'), ] migration = Migration('some_migration', 'test_app') self.assertEqual( migration.suggest_name(), 'person1_person2_person3_delete_person4_and_more', ) def test_operation_with_no_suggested_name(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel('Person', fields=[]), migrations.RunSQL('SELECT 1 FROM person;'), ] migration = Migration('some_migration', 'test_app') self.assertIs(migration.suggest_name().startswith('auto_'), True) def test_none_name(self): class Migration(migrations.Migration): operations = [migrations.RunSQL('SELECT 1 FROM person;')] migration = Migration('0001_initial', 'test_app') suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith('auto_'), True) def test_none_name_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [migrations.RunSQL('SELECT 1 FROM person;')] migration = Migration('0001_initial', 'test_app') self.assertEqual(migration.suggest_name(), 'initial') def test_auto(self): migration = migrations.Migration('0001_initial', 'test_app') suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith('auto_'), True)
2692b31a8a08764afe402bf05dfe6926c71870dc856f328f7c5f273950b0c16c
import os import sys import unittest from types import ModuleType, SimpleNamespace from unittest import mock from django.conf import ( ENVIRONMENT_VARIABLE, USE_DEPRECATED_PYTZ_DEPRECATED_MSG, LazySettings, Settings, settings, ) from django.core.exceptions import ImproperlyConfigured from django.http import HttpRequest from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, modify_settings, override_settings, signals, ) from django.test.utils import requires_tz_support from django.urls import clear_script_prefix, set_script_prefix from django.utils.deprecation import RemovedInDjango50Warning @modify_settings(ITEMS={ 'prepend': ['b'], 'append': ['d'], 'remove': ['a', 'e'] }) @override_settings(ITEMS=['a', 'c', 'e'], ITEMS_OUTER=[1, 2, 3], TEST='override', TEST_OUTER='outer') class FullyDecoratedTranTestCase(TransactionTestCase): available_apps = [] def test_override(self): self.assertEqual(settings.ITEMS, ['b', 'c', 'd']) self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3]) self.assertEqual(settings.TEST, 'override') self.assertEqual(settings.TEST_OUTER, 'outer') @modify_settings(ITEMS={ 'append': ['e', 'f'], 'prepend': ['a'], 'remove': ['d', 'c'], }) def test_method_list_override(self): self.assertEqual(settings.ITEMS, ['a', 'b', 'e', 'f']) self.assertEqual(settings.ITEMS_OUTER, [1, 2, 3]) @modify_settings(ITEMS={ 'append': ['b'], 'prepend': ['d'], 'remove': ['a', 'c', 'e'], }) def test_method_list_override_no_ops(self): self.assertEqual(settings.ITEMS, ['b', 'd']) @modify_settings(ITEMS={ 'append': 'e', 'prepend': 'a', 'remove': 'c', }) def test_method_list_override_strings(self): self.assertEqual(settings.ITEMS, ['a', 'b', 'd', 'e']) @modify_settings(ITEMS={'remove': ['b', 'd']}) @modify_settings(ITEMS={'append': ['b'], 'prepend': ['d']}) def test_method_list_override_nested_order(self): self.assertEqual(settings.ITEMS, ['d', 'c', 'b']) @override_settings(TEST='override2') def test_method_override(self): self.assertEqual(settings.TEST, 'override2') self.assertEqual(settings.TEST_OUTER, 'outer') def test_decorated_testcase_name(self): self.assertEqual(FullyDecoratedTranTestCase.__name__, 'FullyDecoratedTranTestCase') def test_decorated_testcase_module(self): self.assertEqual(FullyDecoratedTranTestCase.__module__, __name__) @modify_settings(ITEMS={ 'prepend': ['b'], 'append': ['d'], 'remove': ['a', 'e'] }) @override_settings(ITEMS=['a', 'c', 'e'], TEST='override') class FullyDecoratedTestCase(TestCase): def test_override(self): self.assertEqual(settings.ITEMS, ['b', 'c', 'd']) self.assertEqual(settings.TEST, 'override') @modify_settings(ITEMS={ 'append': 'e', 'prepend': 'a', 'remove': 'c', }) @override_settings(TEST='override2') def test_method_override(self): self.assertEqual(settings.ITEMS, ['a', 'b', 'd', 'e']) self.assertEqual(settings.TEST, 'override2') class ClassDecoratedTestCaseSuper(TestCase): """ Dummy class for testing max recursion error in child class call to super(). Refs #17011. """ def test_max_recursion_error(self): pass @override_settings(TEST='override') class ClassDecoratedTestCase(ClassDecoratedTestCaseSuper): @classmethod def setUpClass(cls): super().setUpClass() cls.foo = getattr(settings, 'TEST', 'BUG') def test_override(self): self.assertEqual(settings.TEST, 'override') def test_setupclass_override(self): """Settings are overridden within setUpClass (#21281).""" self.assertEqual(self.foo, 'override') @override_settings(TEST='override2') def test_method_override(self): self.assertEqual(settings.TEST, 'override2') def test_max_recursion_error(self): """ Overriding a method on a super class and then calling that method on the super class should not trigger infinite recursion. See #17011. """ super().test_max_recursion_error() @modify_settings(ITEMS={'append': 'mother'}) @override_settings(ITEMS=['father'], TEST='override-parent') class ParentDecoratedTestCase(TestCase): pass @modify_settings(ITEMS={'append': ['child']}) @override_settings(TEST='override-child') class ChildDecoratedTestCase(ParentDecoratedTestCase): def test_override_settings_inheritance(self): self.assertEqual(settings.ITEMS, ['father', 'mother', 'child']) self.assertEqual(settings.TEST, 'override-child') class SettingsTests(SimpleTestCase): def setUp(self): self.testvalue = None signals.setting_changed.connect(self.signal_callback) def tearDown(self): signals.setting_changed.disconnect(self.signal_callback) def signal_callback(self, sender, setting, value, **kwargs): if setting == 'TEST': self.testvalue = value def test_override(self): settings.TEST = 'test' self.assertEqual('test', settings.TEST) with self.settings(TEST='override'): self.assertEqual('override', settings.TEST) self.assertEqual('test', settings.TEST) del settings.TEST def test_override_change(self): settings.TEST = 'test' self.assertEqual('test', settings.TEST) with self.settings(TEST='override'): self.assertEqual('override', settings.TEST) settings.TEST = 'test2' self.assertEqual('test', settings.TEST) del settings.TEST def test_override_doesnt_leak(self): with self.assertRaises(AttributeError): getattr(settings, 'TEST') with self.settings(TEST='override'): self.assertEqual('override', settings.TEST) settings.TEST = 'test' with self.assertRaises(AttributeError): getattr(settings, 'TEST') @override_settings(TEST='override') def test_decorator(self): self.assertEqual('override', settings.TEST) def test_context_manager(self): with self.assertRaises(AttributeError): getattr(settings, 'TEST') override = override_settings(TEST='override') with self.assertRaises(AttributeError): getattr(settings, 'TEST') override.enable() self.assertEqual('override', settings.TEST) override.disable() with self.assertRaises(AttributeError): getattr(settings, 'TEST') def test_class_decorator(self): # SimpleTestCase can be decorated by override_settings, but not ut.TestCase class SimpleTestCaseSubclass(SimpleTestCase): pass class UnittestTestCaseSubclass(unittest.TestCase): pass decorated = override_settings(TEST='override')(SimpleTestCaseSubclass) self.assertIsInstance(decorated, type) self.assertTrue(issubclass(decorated, SimpleTestCase)) with self.assertRaisesMessage(Exception, "Only subclasses of Django SimpleTestCase"): decorated = override_settings(TEST='override')(UnittestTestCaseSubclass) def test_signal_callback_context_manager(self): with self.assertRaises(AttributeError): getattr(settings, 'TEST') with self.settings(TEST='override'): self.assertEqual(self.testvalue, 'override') self.assertIsNone(self.testvalue) @override_settings(TEST='override') def test_signal_callback_decorator(self): self.assertEqual(self.testvalue, 'override') # # Regression tests for #10130: deleting settings. # def test_settings_delete(self): settings.TEST = 'test' self.assertEqual('test', settings.TEST) del settings.TEST msg = "'Settings' object has no attribute 'TEST'" with self.assertRaisesMessage(AttributeError, msg): getattr(settings, 'TEST') def test_settings_delete_wrapped(self): with self.assertRaisesMessage(TypeError, "can't delete _wrapped."): delattr(settings, '_wrapped') def test_override_settings_delete(self): """ Allow deletion of a setting in an overridden settings set (#18824) """ previous_i18n = settings.USE_I18N previous_tz = settings.USE_TZ with self.settings(USE_I18N=False): del settings.USE_I18N with self.assertRaises(AttributeError): getattr(settings, 'USE_I18N') # Should also work for a non-overridden setting del settings.USE_TZ with self.assertRaises(AttributeError): getattr(settings, 'USE_TZ') self.assertNotIn('USE_I18N', dir(settings)) self.assertNotIn('USE_TZ', dir(settings)) self.assertEqual(settings.USE_I18N, previous_i18n) self.assertEqual(settings.USE_TZ, previous_tz) def test_override_settings_nested(self): """ override_settings uses the actual _wrapped attribute at runtime, not when it was instantiated. """ with self.assertRaises(AttributeError): getattr(settings, 'TEST') with self.assertRaises(AttributeError): getattr(settings, 'TEST2') inner = override_settings(TEST2='override') with override_settings(TEST='override'): self.assertEqual('override', settings.TEST) with inner: self.assertEqual('override', settings.TEST) self.assertEqual('override', settings.TEST2) # inner's __exit__ should have restored the settings of the outer # context manager, not those when the class was instantiated self.assertEqual('override', settings.TEST) with self.assertRaises(AttributeError): getattr(settings, 'TEST2') with self.assertRaises(AttributeError): getattr(settings, 'TEST') with self.assertRaises(AttributeError): getattr(settings, 'TEST2') @override_settings(SECRET_KEY='') def test_no_secret_key(self): msg = 'The SECRET_KEY setting must not be empty.' with self.assertRaisesMessage(ImproperlyConfigured, msg): settings.SECRET_KEY def test_no_settings_module(self): msg = ( 'Requested setting%s, but settings are not configured. You ' 'must either define the environment variable DJANGO_SETTINGS_MODULE ' 'or call settings.configure() before accessing settings.' ) orig_settings = os.environ[ENVIRONMENT_VARIABLE] os.environ[ENVIRONMENT_VARIABLE] = '' try: with self.assertRaisesMessage(ImproperlyConfigured, msg % 's'): settings._setup() with self.assertRaisesMessage(ImproperlyConfigured, msg % ' TEST'): settings._setup('TEST') finally: os.environ[ENVIRONMENT_VARIABLE] = orig_settings def test_already_configured(self): with self.assertRaisesMessage(RuntimeError, 'Settings already configured.'): settings.configure() def test_nonupper_settings_prohibited_in_configure(self): s = LazySettings() with self.assertRaisesMessage(TypeError, "Setting 'foo' must be uppercase."): s.configure(foo='bar') def test_nonupper_settings_ignored_in_default_settings(self): s = LazySettings() s.configure(SimpleNamespace(foo='bar')) with self.assertRaises(AttributeError): getattr(s, 'foo') @requires_tz_support @mock.patch('django.conf.global_settings.TIME_ZONE', 'test') def test_incorrect_timezone(self): with self.assertRaisesMessage(ValueError, 'Incorrect timezone setting: test'): settings._setup() def test_use_tz_false_deprecation(self): settings_module = ModuleType('fake_settings_module') settings_module.SECRET_KEY = 'foo' sys.modules['fake_settings_module'] = settings_module msg = ( 'The default value of USE_TZ will change from False to True in ' 'Django 5.0. Set USE_TZ to False in your project settings if you ' 'want to keep the current default behavior.' ) try: with self.assertRaisesMessage(RemovedInDjango50Warning, msg): Settings('fake_settings_module') finally: del sys.modules['fake_settings_module'] def test_use_deprecated_pytz_deprecation(self): settings_module = ModuleType('fake_settings_module') settings_module.USE_DEPRECATED_PYTZ = True settings_module.USE_TZ = True sys.modules['fake_settings_module'] = settings_module try: with self.assertRaisesMessage(RemovedInDjango50Warning, USE_DEPRECATED_PYTZ_DEPRECATED_MSG): Settings('fake_settings_module') finally: del sys.modules['fake_settings_module'] holder = LazySettings() with self.assertRaisesMessage(RemovedInDjango50Warning, USE_DEPRECATED_PYTZ_DEPRECATED_MSG): holder.configure(USE_DEPRECATED_PYTZ=True) class TestComplexSettingOverride(SimpleTestCase): def setUp(self): self.old_warn_override_settings = signals.COMPLEX_OVERRIDE_SETTINGS.copy() signals.COMPLEX_OVERRIDE_SETTINGS.add('TEST_WARN') def tearDown(self): signals.COMPLEX_OVERRIDE_SETTINGS = self.old_warn_override_settings self.assertNotIn('TEST_WARN', signals.COMPLEX_OVERRIDE_SETTINGS) def test_complex_override_warning(self): """Regression test for #19031""" msg = 'Overriding setting TEST_WARN can lead to unexpected behavior.' with self.assertWarnsMessage(UserWarning, msg) as cm: with override_settings(TEST_WARN='override'): self.assertEqual(settings.TEST_WARN, 'override') self.assertEqual(cm.filename, __file__) class SecureProxySslHeaderTest(SimpleTestCase): @override_settings(SECURE_PROXY_SSL_HEADER=None) def test_none(self): req = HttpRequest() self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https')) def test_set_without_xheader(self): req = HttpRequest() self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https')) def test_set_with_xheader_wrong(self): req = HttpRequest() req.META['HTTP_X_FORWARDED_PROTO'] = 'wrongvalue' self.assertIs(req.is_secure(), False) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https')) def test_set_with_xheader_right(self): req = HttpRequest() req.META['HTTP_X_FORWARDED_PROTO'] = 'https' self.assertIs(req.is_secure(), True) @override_settings(SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https')) def test_xheader_preferred_to_underlying_request(self): class ProxyRequest(HttpRequest): def _get_scheme(self): """Proxy always connecting via HTTPS""" return 'https' # Client connects via HTTP. req = ProxyRequest() req.META['HTTP_X_FORWARDED_PROTO'] = 'http' self.assertIs(req.is_secure(), False) class IsOverriddenTest(SimpleTestCase): def test_configure(self): s = LazySettings() s.configure(SECRET_KEY='foo') self.assertTrue(s.is_overridden('SECRET_KEY')) def test_module(self): settings_module = ModuleType('fake_settings_module') settings_module.SECRET_KEY = 'foo' settings_module.USE_TZ = False sys.modules['fake_settings_module'] = settings_module try: s = Settings('fake_settings_module') self.assertTrue(s.is_overridden('SECRET_KEY')) self.assertFalse(s.is_overridden('ALLOWED_HOSTS')) finally: del sys.modules['fake_settings_module'] def test_override(self): self.assertFalse(settings.is_overridden('ALLOWED_HOSTS')) with override_settings(ALLOWED_HOSTS=[]): self.assertTrue(settings.is_overridden('ALLOWED_HOSTS')) def test_unevaluated_lazysettings_repr(self): lazy_settings = LazySettings() expected = '<LazySettings [Unevaluated]>' self.assertEqual(repr(lazy_settings), expected) def test_evaluated_lazysettings_repr(self): lazy_settings = LazySettings() module = os.environ.get(ENVIRONMENT_VARIABLE) expected = '<LazySettings "%s">' % module # Force evaluation of the lazy object. lazy_settings.APPEND_SLASH self.assertEqual(repr(lazy_settings), expected) def test_usersettingsholder_repr(self): lazy_settings = LazySettings() lazy_settings.configure(APPEND_SLASH=False) expected = '<UserSettingsHolder>' self.assertEqual(repr(lazy_settings._wrapped), expected) def test_settings_repr(self): module = os.environ.get(ENVIRONMENT_VARIABLE) lazy_settings = Settings(module) expected = '<Settings "%s">' % module self.assertEqual(repr(lazy_settings), expected) class TestListSettings(SimpleTestCase): """ Make sure settings that should be lists or tuples throw ImproperlyConfigured if they are set to a string instead of a list or tuple. """ list_or_tuple_settings = ( 'ALLOWED_HOSTS', "INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS", "SECRET_KEY_FALLBACKS", ) def test_tuple_settings(self): settings_module = ModuleType('fake_settings_module') settings_module.SECRET_KEY = 'foo' msg = 'The %s setting must be a list or a tuple.' for setting in self.list_or_tuple_settings: setattr(settings_module, setting, ('non_list_or_tuple_value')) sys.modules['fake_settings_module'] = settings_module try: with self.assertRaisesMessage(ImproperlyConfigured, msg % setting): Settings('fake_settings_module') finally: del sys.modules['fake_settings_module'] delattr(settings_module, setting) class SettingChangeEnterException(Exception): pass class SettingChangeExitException(Exception): pass class OverrideSettingsIsolationOnExceptionTests(SimpleTestCase): """ The override_settings context manager restore settings if one of the receivers of "setting_changed" signal fails. Check the three cases of receiver failure detailed in receiver(). In each case, ALL receivers are called when exiting the context manager. """ def setUp(self): signals.setting_changed.connect(self.receiver) self.addCleanup(signals.setting_changed.disconnect, self.receiver) # Create a spy that's connected to the `setting_changed` signal and # executed AFTER `self.receiver`. self.spy_receiver = mock.Mock() signals.setting_changed.connect(self.spy_receiver) self.addCleanup(signals.setting_changed.disconnect, self.spy_receiver) def receiver(self, **kwargs): """ A receiver that fails while certain settings are being changed. - SETTING_BOTH raises an error while receiving the signal on both entering and exiting the context manager. - SETTING_ENTER raises an error only on enter. - SETTING_EXIT raises an error only on exit. """ setting = kwargs['setting'] enter = kwargs['enter'] if setting in ('SETTING_BOTH', 'SETTING_ENTER') and enter: raise SettingChangeEnterException if setting in ('SETTING_BOTH', 'SETTING_EXIT') and not enter: raise SettingChangeExitException def check_settings(self): """Assert that settings for these tests aren't present.""" self.assertFalse(hasattr(settings, 'SETTING_BOTH')) self.assertFalse(hasattr(settings, 'SETTING_ENTER')) self.assertFalse(hasattr(settings, 'SETTING_EXIT')) self.assertFalse(hasattr(settings, 'SETTING_PASS')) def check_spy_receiver_exit_calls(self, call_count): """ Assert that `self.spy_receiver` was called exactly `call_count` times with the ``enter=False`` keyword argument. """ kwargs_with_exit = [ kwargs for args, kwargs in self.spy_receiver.call_args_list if ('enter', False) in kwargs.items() ] self.assertEqual(len(kwargs_with_exit), call_count) def test_override_settings_both(self): """Receiver fails on both enter and exit.""" with self.assertRaises(SettingChangeEnterException): with override_settings(SETTING_PASS='BOTH', SETTING_BOTH='BOTH'): pass self.check_settings() # Two settings were touched, so expect two calls of `spy_receiver`. self.check_spy_receiver_exit_calls(call_count=2) def test_override_settings_enter(self): """Receiver fails on enter only.""" with self.assertRaises(SettingChangeEnterException): with override_settings(SETTING_PASS='ENTER', SETTING_ENTER='ENTER'): pass self.check_settings() # Two settings were touched, so expect two calls of `spy_receiver`. self.check_spy_receiver_exit_calls(call_count=2) def test_override_settings_exit(self): """Receiver fails on exit only.""" with self.assertRaises(SettingChangeExitException): with override_settings(SETTING_PASS='EXIT', SETTING_EXIT='EXIT'): pass self.check_settings() # Two settings were touched, so expect two calls of `spy_receiver`. self.check_spy_receiver_exit_calls(call_count=2) def test_override_settings_reusable_on_enter(self): """ Error is raised correctly when reusing the same override_settings instance. """ @override_settings(SETTING_ENTER='ENTER') def decorated_function(): pass with self.assertRaises(SettingChangeEnterException): decorated_function() signals.setting_changed.disconnect(self.receiver) # This call shouldn't raise any errors. decorated_function() class MediaURLStaticURLPrefixTest(SimpleTestCase): def set_script_name(self, val): clear_script_prefix() if val is not None: set_script_prefix(val) def test_not_prefixed(self): # Don't add SCRIPT_NAME prefix to absolute paths, URLs, or None. tests = ( '/path/', 'http://myhost.com/path/', 'http://myhost/path/', 'https://myhost/path/', None, ) for setting in ('MEDIA_URL', 'STATIC_URL'): for path in tests: new_settings = {setting: path} with self.settings(**new_settings): for script_name in ['/somesubpath', '/somesubpath/', '/', '', None]: with self.subTest(script_name=script_name, **new_settings): try: self.set_script_name(script_name) self.assertEqual(getattr(settings, setting), path) finally: clear_script_prefix() def test_add_script_name_prefix(self): tests = ( # Relative paths. ('/somesubpath', 'path/', '/somesubpath/path/'), ('/somesubpath/', 'path/', '/somesubpath/path/'), ('/', 'path/', '/path/'), # Invalid URLs. ('/somesubpath/', 'htp://myhost.com/path/', '/somesubpath/htp://myhost.com/path/'), # Blank settings. ('/somesubpath/', '', '/somesubpath/'), ) for setting in ('MEDIA_URL', 'STATIC_URL'): for script_name, path, expected_path in tests: new_settings = {setting: path} with self.settings(**new_settings): with self.subTest(script_name=script_name, **new_settings): try: self.set_script_name(script_name) self.assertEqual(getattr(settings, setting), expected_path) finally: clear_script_prefix()
9b94ab7892d713ae7e7dd982f5f9468270e4f579b75897a17d5d5767fa283b09
from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from django.test.utils import override_settings from .models import CustomEmailField class MockedPasswordResetTokenGenerator(PasswordResetTokenGenerator): def __init__(self, now): self._now_val = now super().__init__() def _now(self): return self._now_val class TokenGeneratorTest(TestCase): def test_make_token(self): user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) self.assertIs(p0.check_token(user, tk1), True) def test_10265(self): """ The token generated for a user created in the same request will work correctly. """ user = User.objects.create_user('comebackkid', '[email protected]', 'testpw') user_reload = User.objects.get(username='comebackkid') p0 = MockedPasswordResetTokenGenerator(datetime.now()) tk1 = p0.make_token(user) tk2 = p0.make_token(user_reload) self.assertEqual(tk1, tk2) def test_token_with_different_email(self): """Updating the user email address invalidates the token.""" tests = [ (CustomEmailField, None), (CustomEmailField, '[email protected]'), (User, '[email protected]'), ] for model, email in tests: with self.subTest(model=model.__qualname__, email=email): user = model.objects.create_user( 'changeemailuser', email=email, password='testpw', ) p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) self.assertIs(p0.check_token(user, tk1), True) setattr(user, user.get_email_field_name(), '[email protected]') user.save() self.assertIs(p0.check_token(user, tk1), False) def test_timeout(self): """The token is valid after n seconds, but no greater.""" # Uses a mocked version of PasswordResetTokenGenerator so we can change # the value of 'now'. user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') now = datetime.now() p0 = MockedPasswordResetTokenGenerator(now) tk1 = p0.make_token(user) p1 = MockedPasswordResetTokenGenerator( now + timedelta(seconds=settings.PASSWORD_RESET_TIMEOUT) ) self.assertIs(p1.check_token(user, tk1), True) p2 = MockedPasswordResetTokenGenerator( now + timedelta(seconds=(settings.PASSWORD_RESET_TIMEOUT + 1)) ) self.assertIs(p2.check_token(user, tk1), False) with self.settings(PASSWORD_RESET_TIMEOUT=60 * 60): p3 = MockedPasswordResetTokenGenerator( now + timedelta(seconds=settings.PASSWORD_RESET_TIMEOUT) ) self.assertIs(p3.check_token(user, tk1), True) p4 = MockedPasswordResetTokenGenerator( now + timedelta(seconds=(settings.PASSWORD_RESET_TIMEOUT + 1)) ) self.assertIs(p4.check_token(user, tk1), False) def test_check_token_with_nonexistent_token_and_user(self): user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') p0 = PasswordResetTokenGenerator() tk1 = p0.make_token(user) self.assertIs(p0.check_token(None, tk1), False) self.assertIs(p0.check_token(user, None), False) def test_token_with_different_secret(self): """ A valid token can be created with a secret other than SECRET_KEY by using the PasswordResetTokenGenerator.secret attribute. """ user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') new_secret = 'abcdefghijkl' # Create and check a token with a different secret. p0 = PasswordResetTokenGenerator() p0.secret = new_secret tk0 = p0.make_token(user) self.assertIs(p0.check_token(user, tk0), True) # Create and check a token with the default secret. p1 = PasswordResetTokenGenerator() self.assertEqual(p1.secret, settings.SECRET_KEY) self.assertNotEqual(p1.secret, new_secret) tk1 = p1.make_token(user) # Tokens created with a different secret don't validate. self.assertIs(p0.check_token(user, tk1), False) self.assertIs(p1.check_token(user, tk0), False) def test_token_with_different_secret_subclass(self): class CustomPasswordResetTokenGenerator(PasswordResetTokenGenerator): secret = 'test-secret' user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') custom_password_generator = CustomPasswordResetTokenGenerator() tk_custom = custom_password_generator.make_token(user) self.assertIs(custom_password_generator.check_token(user, tk_custom), True) default_password_generator = PasswordResetTokenGenerator() self.assertNotEqual( custom_password_generator.secret, default_password_generator.secret, ) self.assertEqual(default_password_generator.secret, settings.SECRET_KEY) # Tokens created with a different secret don't validate. tk_default = default_password_generator.make_token(user) self.assertIs(custom_password_generator.check_token(user, tk_default), False) self.assertIs(default_password_generator.check_token(user, tk_custom), False) @override_settings(SECRET_KEY='') def test_secret_lazy_validation(self): default_token_generator = PasswordResetTokenGenerator() msg = 'The SECRET_KEY setting must not be empty.' with self.assertRaisesMessage(ImproperlyConfigured, msg): default_token_generator.secret def test_check_token_secret_fallbacks(self): user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') p1 = PasswordResetTokenGenerator() p1.secret = 'secret' tk = p1.make_token(user) p2 = PasswordResetTokenGenerator() p2.secret = 'newsecret' p2.secret_fallbacks = ['secret'] self.assertIs(p1.check_token(user, tk), True) self.assertIs(p2.check_token(user, tk), True) @override_settings( SECRET_KEY='secret', SECRET_KEY_FALLBACKS=['oldsecret'], ) def test_check_token_secret_key_fallbacks(self): user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') p1 = PasswordResetTokenGenerator() p1.secret = 'oldsecret' tk = p1.make_token(user) p2 = PasswordResetTokenGenerator() self.assertIs(p2.check_token(user, tk), True) @override_settings( SECRET_KEY='secret', SECRET_KEY_FALLBACKS=['oldsecret'], ) def test_check_token_secret_key_fallbacks_override(self): user = User.objects.create_user('tokentestuser', '[email protected]', 'testpw') p1 = PasswordResetTokenGenerator() p1.secret = 'oldsecret' tk = p1.make_token(user) p2 = PasswordResetTokenGenerator() p2.secret_fallbacks = [] self.assertIs(p2.check_token(user, tk), False)
d4563931a905a055f8fbd4cf75c2f529dc183fc86747bff8cb07c5dccccb7bea
import datetime from django.core import signing from django.test import SimpleTestCase, override_settings from django.test.utils import freeze_time from django.utils.crypto import InvalidAlgorithm class TestSigner(SimpleTestCase): def test_signature(self): "signature() method should generate a signature" signer = signing.Signer('predictable-secret') signer2 = signing.Signer('predictable-secret2') for s in ( b'hello', b'3098247:529:087:', '\u2019'.encode(), ): self.assertEqual( signer.signature(s), signing.base64_hmac( signer.salt + 'signer', s, 'predictable-secret', algorithm=signer.algorithm, ) ) self.assertNotEqual(signer.signature(s), signer2.signature(s)) def test_signature_with_salt(self): "signature(value, salt=...) should work" signer = signing.Signer('predictable-secret', salt='extra-salt') self.assertEqual( signer.signature('hello'), signing.base64_hmac( 'extra-salt' + 'signer', 'hello', 'predictable-secret', algorithm=signer.algorithm, ) ) self.assertNotEqual( signing.Signer('predictable-secret', salt='one').signature('hello'), signing.Signer('predictable-secret', salt='two').signature('hello')) def test_custom_algorithm(self): signer = signing.Signer('predictable-secret', algorithm='sha512') self.assertEqual( signer.signature('hello'), 'Usf3uVQOZ9m6uPfVonKR-EBXjPe7bjMbp3_Fq8MfsptgkkM1ojidN0BxYaT5HAEN1' 'VzO9_jVu7R-VkqknHYNvw', ) def test_invalid_algorithm(self): signer = signing.Signer('predictable-secret', algorithm='whatever') msg = "'whatever' is not an algorithm accepted by the hashlib module." with self.assertRaisesMessage(InvalidAlgorithm, msg): signer.sign('hello') def test_sign_unsign(self): "sign/unsign should be reversible" signer = signing.Signer('predictable-secret') examples = [ 'q;wjmbk;wkmb', '3098247529087', '3098247:529:087:', 'jkw osanteuh ,rcuh nthu aou oauh ,ud du', '\u2019', ] for example in examples: signed = signer.sign(example) self.assertIsInstance(signed, str) self.assertNotEqual(example, signed) self.assertEqual(example, signer.unsign(signed)) def test_sign_unsign_non_string(self): signer = signing.Signer('predictable-secret') values = [ 123, 1.23, True, datetime.date.today(), ] for value in values: with self.subTest(value): signed = signer.sign(value) self.assertIsInstance(signed, str) self.assertNotEqual(signed, value) self.assertEqual(signer.unsign(signed), str(value)) def test_unsign_detects_tampering(self): "unsign should raise an exception if the value has been tampered with" signer = signing.Signer('predictable-secret') value = 'Another string' signed_value = signer.sign(value) transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) self.assertEqual(value, signer.unsign(signed_value)) for transform in transforms: with self.assertRaises(signing.BadSignature): signer.unsign(transform(signed_value)) def test_sign_unsign_object(self): signer = signing.Signer('predictable-secret') tests = [ ['a', 'list'], 'a string \u2019', {'a': 'dictionary'}, ] for obj in tests: with self.subTest(obj=obj): signed_obj = signer.sign_object(obj) self.assertNotEqual(obj, signed_obj) self.assertEqual(obj, signer.unsign_object(signed_obj)) signed_obj = signer.sign_object(obj, compress=True) self.assertNotEqual(obj, signed_obj) self.assertEqual(obj, signer.unsign_object(signed_obj)) def test_dumps_loads(self): "dumps and loads be reversible for any JSON serializable object" objects = [ ['a', 'list'], 'a string \u2019', {'a': 'dictionary'}, ] for o in objects: self.assertNotEqual(o, signing.dumps(o)) self.assertEqual(o, signing.loads(signing.dumps(o))) self.assertNotEqual(o, signing.dumps(o, compress=True)) self.assertEqual(o, signing.loads(signing.dumps(o, compress=True))) def test_decode_detects_tampering(self): "loads should raise exception for tampered objects" transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) value = { 'foo': 'bar', 'baz': 1, } encoded = signing.dumps(value) self.assertEqual(value, signing.loads(encoded)) for transform in transforms: with self.assertRaises(signing.BadSignature): signing.loads(transform(encoded)) def test_works_with_non_ascii_keys(self): binary_key = b'\xe7' # Set some binary (non-ASCII key) s = signing.Signer(binary_key) self.assertEqual( 'foo:EE4qGC5MEKyQG5msxYA0sBohAxLC0BJf8uRhemh0BGU', s.sign('foo'), ) def test_valid_sep(self): separators = ['/', '*sep*', ','] for sep in separators: signer = signing.Signer('predictable-secret', sep=sep) self.assertEqual( 'foo%sjZQoX_FtSO70jX9HLRGg2A_2s4kdDBxz1QoO_OpEQb0' % sep, signer.sign('foo'), ) def test_invalid_sep(self): """should warn on invalid separator""" msg = 'Unsafe Signer separator: %r (cannot be empty or consist of only A-z0-9-_=)' separators = ['', '-', 'abc'] for sep in separators: with self.assertRaisesMessage(ValueError, msg % sep): signing.Signer(sep=sep) def test_verify_with_non_default_key(self): old_signer = signing.Signer('secret') new_signer = signing.Signer('newsecret', fallback_keys=['othersecret', 'secret']) signed = old_signer.sign('abc') self.assertEqual(new_signer.unsign(signed), 'abc') def test_sign_unsign_multiple_keys(self): """The default key is a valid verification key.""" signer = signing.Signer('secret', fallback_keys=['oldsecret']) signed = signer.sign('abc') self.assertEqual(signer.unsign(signed), 'abc') @override_settings( SECRET_KEY='secret', SECRET_KEY_FALLBACKS=['oldsecret'], ) def test_sign_unsign_ignore_secret_key_fallbacks(self): old_signer = signing.Signer('oldsecret') signed = old_signer.sign('abc') signer = signing.Signer(fallback_keys=[]) with self.assertRaises(signing.BadSignature): signer.unsign(signed) @override_settings( SECRET_KEY='secret', SECRET_KEY_FALLBACKS=['oldsecret'], ) def test_default_keys_verification(self): old_signer = signing.Signer('oldsecret') signed = old_signer.sign('abc') signer = signing.Signer() self.assertEqual(signer.unsign(signed), 'abc') class TestTimestampSigner(SimpleTestCase): def test_timestamp_signer(self): value = 'hello' with freeze_time(123456789): signer = signing.TimestampSigner('predictable-key') ts = signer.sign(value) self.assertNotEqual(ts, signing.Signer('predictable-key').sign(value)) self.assertEqual(signer.unsign(ts), value) with freeze_time(123456800): self.assertEqual(signer.unsign(ts, max_age=12), value) # max_age parameter can also accept a datetime.timedelta object self.assertEqual(signer.unsign(ts, max_age=datetime.timedelta(seconds=11)), value) with self.assertRaises(signing.SignatureExpired): signer.unsign(ts, max_age=10) class TestBase62(SimpleTestCase): def test_base62(self): tests = [-10 ** 10, 10 ** 10, 1620378259, *range(-100, 100)] for i in tests: self.assertEqual(i, signing.b62_decode(signing.b62_encode(i)))
0611f3a9fc8572a88b1dbddaba2b0b3c2894539461fbac8838f3f05a4d37bbf1
import sys from django.template import ( Context, Engine, TemplateDoesNotExist, 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 from django.utils.html import escape class TemplateTestMixin: def _engine(self, **kwargs): return Engine(debug=self.debug_engine, **kwargs) def test_string_origin(self): template = self._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 = self._engine().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 = self._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 = self._engine() c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) if self.debug_engine: 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 = self._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 = self._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 = self._engine() 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 %}") if self.debug_engine: 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 = self._engine( libraries={'bad_tag': 'template_tests.templatetags.bad_tag'}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") if self.debug_engine: self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') def test_compile_tag_error_27584(self): engine = self._engine( app_dirs=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()) if self.debug_engine: 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 = self._engine( app_dirs=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()) if self.debug_engine: self.assertEqual(e.exception.template_debug['during'], '{% badtag %}') def test_render_tag_error_in_extended_block(self): """Errors in extended block are displayed correctly.""" e = self._engine(app_dirs=True) template = e.get_template('test_extends_block_error.html') context = Context() with self.assertRaises(TemplateDoesNotExist) as cm: template.render(context) if self.debug_engine: self.assertEqual( cm.exception.template_debug['during'], escape('{% include "missing.html" %}'), ) def test_super_errors(self): """ #18169 -- NoReverseMatch should not be silence in block.super. """ engine = self._engine(app_dirs=True) t = engine.get_template('included_content.html') with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = self._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 = self._engine().from_string('content') for node in template.nodelist: self.assertEqual(node.origin, template.origin) class TemplateTests(TemplateTestMixin, SimpleTestCase): debug_engine = False class DebugTemplateTests(TemplateTestMixin, SimpleTestCase): debug_engine = True
911a4e57a71e1f5b59b50c77a3232dd2e5ef85ada69e478ff58469d69f426d7c
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.security import base, csrf, sessions from django.core.management.utils import get_random_secret_key from django.test import SimpleTestCase from django.test.utils import override_settings class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W011]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W012]) @override_settings( SESSION_COOKIE_SECURE=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_secure(None), []) class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=[], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W014]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W015]) @override_settings( SESSION_COOKIE_HTTPONLY=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], ) def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_httponly(None), []) class CheckCSRFMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_csrf_middleware(self): """ Warn if CsrfViewMiddleware isn't in MIDDLEWARE. """ self.assertEqual(csrf.check_csrf_middleware(None), [csrf.W003]) @override_settings(MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware']) def test_with_csrf_middleware(self): self.assertEqual(csrf.check_csrf_middleware(None), []) class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=False, ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but CSRF_COOKIE_SECURE isn't True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_USE_SESSIONS=True, CSRF_COOKIE_SECURE=False, ) def test_use_sessions_with_csrf_cookie_secure_false(self): """ No warning if CSRF_COOKIE_SECURE isn't True while CSRF_USE_SESSIONS is True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings(MIDDLEWARE=[], CSRF_COOKIE_SECURE=False) def test_with_csrf_cookie_secure_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=True, ) def test_with_csrf_cookie_secure_true(self): self.assertEqual(csrf.check_csrf_cookie_secure(None), []) class CheckSecurityMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_security_middleware(self): """ Warn if SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_security_middleware(None), [base.W001]) @override_settings(MIDDLEWARE=['django.middleware.security.SecurityMiddleware']) def test_with_security_middleware(self): self.assertEqual(base.check_security_middleware(None), []) class CheckStrictTransportSecurityTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=0, ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(base.check_sts(None), [base.W004]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0) def test_no_sts_no_middleware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=3600, ) def test_with_sts(self): self.assertEqual(base.check_sts(None), []) class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. """ self.assertEqual(base.check_sts_include_subdomains(None), [base.W005]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_subdomains(self): self.assertEqual(base.check_sts_include_subdomains(None), []) class CheckStrictTransportSecurityPreloadTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_preload(self): """ Warn if SECURE_HSTS_PRELOAD isn't True. """ self.assertEqual(base.check_sts_preload(None), [base.W021]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600) def test_no_sts_preload_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_preload_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_preload(self): self.assertEqual(base.check_sts_preload(None), []) class CheckXFrameOptionsMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_middleware_not_installed(self): """ Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_xframe_options_middleware(None), [base.W002]) @override_settings(MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"]) def test_middleware_installed(self): self.assertEqual(base.check_xframe_options_middleware(None), []) class CheckXFrameOptionsDenyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS='SAMEORIGIN', ) def test_x_frame_options_not_deny(self): """ Warn if XFrameOptionsMiddleware is in MIDDLEWARE but X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), [base.W019]) @override_settings(MIDDLEWARE=[], X_FRAME_OPTIONS='SAMEORIGIN') def test_middleware_not_installed(self): """ No error if XFrameOptionsMiddleware isn't in MIDDLEWARE even if X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), []) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS='DENY', ) def test_xframe_deny(self): self.assertEqual(base.check_xframe_deny(None), []) class CheckContentTypeNosniffTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=False, ) def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(base.check_content_type_nosniff(None), [base.W006]) @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False) def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_content_type_nosniff(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=True, ) def test_with_content_type_nosniff(self): self.assertEqual(base.check_content_type_nosniff(None), []) class CheckSSLRedirectTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, ) def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(base.check_ssl_redirect(None), [base.W008]) @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False) def test_no_ssl_redirect_no_middleware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_ssl_redirect(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=True, ) def test_with_ssl_redirect(self): self.assertEqual(base.check_ssl_redirect(None), []) class CheckSecretKeyTest(SimpleTestCase): @override_settings(SECRET_KEY=('abcdefghijklmnopqrstuvwx' * 2) + 'ab') def test_okay_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertGreater(len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS) self.assertEqual(base.check_secret_key(None), []) @override_settings(SECRET_KEY='') def test_empty_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_missing_secret_key(self): del settings.SECRET_KEY self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_none_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings( SECRET_KEY=base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() ) def test_insecure_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=('abcdefghijklmnopqrstuvwx' * 2) + 'a') def test_low_length_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH - 1) self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY='abcd' * 20) def test_low_entropy_secret_key(self): self.assertGreater(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertLess(len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS) self.assertEqual(base.check_secret_key(None), [base.W009]) class CheckSecretKeyFallbacksTest(SimpleTestCase): @override_settings(SECRET_KEY_FALLBACKS=[('abcdefghijklmnopqrstuvwx' * 2) + 'ab']) def test_okay_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertGreater( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual(base.check_secret_key_fallbacks(None), []) def test_no_secret_key_fallbacks(self): with self.settings(SECRET_KEY_FALLBACKS=None): del settings.SECRET_KEY_FALLBACKS self.assertEqual(base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS', id=base.W025.id), ]) @override_settings(SECRET_KEY_FALLBACKS=[ base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() ]) def test_insecure_secret_key_fallbacks(self): self.assertEqual(base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[0]', id=base.W025.id), ]) @override_settings(SECRET_KEY_FALLBACKS=[('abcdefghijklmnopqrstuvwx' * 2) + 'a']) def test_low_length_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH - 1, ) self.assertEqual(base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[0]', id=base.W025.id), ]) @override_settings(SECRET_KEY_FALLBACKS=['abcd' * 20]) def test_low_entropy_secret_key_fallbacks(self): self.assertGreater( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertLess( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual(base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[0]', id=base.W025.id), ]) @override_settings(SECRET_KEY_FALLBACKS=[ ('abcdefghijklmnopqrstuvwx' * 2) + 'ab', 'badkey', ]) def test_multiple_keys(self): self.assertEqual(base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[1]', id=base.W025.id), ]) @override_settings(SECRET_KEY_FALLBACKS=[ ('abcdefghijklmnopqrstuvwx' * 2) + 'ab', 'badkey1', 'badkey2', ]) def test_multiple_bad_keys(self): self.assertEqual(base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[1]', id=base.W025.id), Warning(base.W025.msg % 'SECRET_KEY_FALLBACKS[2]', id=base.W025.id), ]) class CheckDebugTest(SimpleTestCase): @override_settings(DEBUG=True) def test_debug_true(self): """ Warn if DEBUG is True. """ self.assertEqual(base.check_debug(None), [base.W018]) @override_settings(DEBUG=False) def test_debug_false(self): self.assertEqual(base.check_debug(None), []) class CheckAllowedHostsTest(SimpleTestCase): @override_settings(ALLOWED_HOSTS=[]) def test_allowed_hosts_empty(self): self.assertEqual(base.check_allowed_hosts(None), [base.W020]) @override_settings(ALLOWED_HOSTS=['.example.com']) def test_allowed_hosts_set(self): self.assertEqual(base.check_allowed_hosts(None), []) class CheckReferrerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=['django.middleware.security.SecurityMiddleware'], SECURE_REFERRER_POLICY=None, ) def test_no_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.W022]) @override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None) def test_no_referrer_policy_no_middleware(self): """ Don't warn if SECURE_REFERRER_POLICY is None and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_referrer_policy(None), []) @override_settings(MIDDLEWARE=['django.middleware.security.SecurityMiddleware']) def test_with_referrer_policy(self): tests = ( 'strict-origin', 'strict-origin,origin', 'strict-origin, origin', ['strict-origin', 'origin'], ('strict-origin', 'origin'), ) for value in tests: with self.subTest(value=value), override_settings(SECURE_REFERRER_POLICY=value): self.assertEqual(base.check_referrer_policy(None), []) @override_settings( MIDDLEWARE=['django.middleware.security.SecurityMiddleware'], SECURE_REFERRER_POLICY='invalid-value', ) def test_with_invalid_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.E023]) def failure_view_with_invalid_signature(): pass class CSRFFailureViewTest(SimpleTestCase): @override_settings(CSRF_FAILURE_VIEW='') def test_failure_view_import_error(self): self.assertEqual( csrf.check_csrf_failure_view(None), [ Error( "The CSRF failure view '' could not be imported.", id='security.E102', ) ], ) @override_settings( CSRF_FAILURE_VIEW='check_framework.test_security.failure_view_with_invalid_signature', ) def test_failure_view_invalid_signature(self): msg = ( "The CSRF failure view " "'check_framework.test_security.failure_view_with_invalid_signature' " "does not take the correct number of arguments." ) self.assertEqual( csrf.check_csrf_failure_view(None), [Error(msg, id='security.E101')], ) class CheckCrossOriginOpenerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=['django.middleware.security.SecurityMiddleware'], SECURE_CROSS_ORIGIN_OPENER_POLICY=None, ) def test_no_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings(MIDDLEWARE=['django.middleware.security.SecurityMiddleware']) def test_with_coop(self): tests = ['same-origin', 'same-origin-allow-popups', 'unsafe-none'] for value in tests: with self.subTest(value=value), override_settings( SECURE_CROSS_ORIGIN_OPENER_POLICY=value, ): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings( MIDDLEWARE=['django.middleware.security.SecurityMiddleware'], SECURE_CROSS_ORIGIN_OPENER_POLICY='invalid-value', ) def test_with_invalid_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), [base.E024])
806d3e607af2e430785d8aa662022cd351181a398d6d4b33f7605d39ba1d6818
import base64 import hashlib import os import shutil import sys import tempfile as sys_tempfile import unittest from io import BytesIO, StringIO from unittest import mock from urllib.parse import quote from django.core.exceptions import SuspiciousFileOperation from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile from django.http.multipartparser import ( FILE, MultiPartParser, MultiPartParserError, Parser, parse_header, ) from django.test import SimpleTestCase, TestCase, client, override_settings from . import uploadhandler from .models import FileModel UNICODE_FILENAME = 'test-0123456789_中文_Orléans.jpg' MEDIA_ROOT = sys_tempfile.mkdtemp() UPLOAD_TO = os.path.join(MEDIA_ROOT, 'test_upload') CANDIDATE_TRAVERSAL_FILE_NAMES = [ '/tmp/hax0rd.txt', # Absolute path, *nix-style. 'C:\\Windows\\hax0rd.txt', # Absolute path, win-style. 'C:/Windows/hax0rd.txt', # Absolute path, broken-style. '\\tmp\\hax0rd.txt', # Absolute path, broken in a different way. '/tmp\\hax0rd.txt', # Absolute path, broken by mixing. 'subdir/hax0rd.txt', # Descendant path, *nix-style. 'subdir\\hax0rd.txt', # Descendant path, win-style. 'sub/dir\\hax0rd.txt', # Descendant path, mixed. '../../hax0rd.txt', # Relative path, *nix-style. '..\\..\\hax0rd.txt', # Relative path, win-style. '../..\\hax0rd.txt', # Relative path, mixed. '..&#x2F;hax0rd.txt', # HTML entities. '..&sol;hax0rd.txt', # HTML entities. ] CANDIDATE_INVALID_FILE_NAMES = [ '/tmp/', # Directory, *nix-style. 'c:\\tmp\\', # Directory, win-style. '/tmp/.', # Directory dot, *nix-style. 'c:\\tmp\\.', # Directory dot, *nix-style. '/tmp/..', # Parent directory, *nix-style. 'c:\\tmp\\..', # Parent directory, win-style. '', # Empty filename. ] @override_settings(MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF='file_uploads.urls', MIDDLEWARE=[]) class FileUploadTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT) def test_upload_name_is_validated(self): candidates = [ '/tmp/', '/tmp/..', '/tmp/.', ] if sys.platform == 'win32': candidates.extend([ 'c:\\tmp\\', 'c:\\tmp\\..', 'c:\\tmp\\.', ]) for file_name in candidates: with self.subTest(file_name=file_name): self.assertRaises(SuspiciousFileOperation, UploadedFile, name=file_name) def test_simple_upload(self): with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, } response = self.client.post('/upload/', post_data) self.assertEqual(response.status_code, 200) def test_large_upload(self): file = tempfile.NamedTemporaryFile with file(suffix=".file1") as file1, file(suffix=".file2") as file2: file1.write(b'a' * (2 ** 21)) file1.seek(0) file2.write(b'a' * (10 * 2 ** 20)) file2.seek(0) post_data = { 'name': 'Ringo', 'file_field1': file1, 'file_field2': file2, } for key in list(post_data): try: post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + '_hash'] = hashlib.sha1(post_data[key].encode()).hexdigest() response = self.client.post('/verify/', post_data) self.assertEqual(response.status_code, 200) def _test_base64_upload(self, content, encode=base64.b64encode): payload = client.FakePayload("\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', 'Content-Type: application/octet-stream', 'Content-Transfer-Encoding: base64', ''])) payload.write(b'\r\n' + encode(content.encode()) + b'\r\n') payload.write('--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo_content/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.json()['file'], content) def test_base64_upload(self): self._test_base64_upload("This data will be transmitted base64-encoded.") def test_big_base64_upload(self): self._test_base64_upload("Big data" * 68000) # > 512Kb def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', 'Content-Type: application/octet-stream', 'Content-Transfer-Encoding: base64', '' ])) payload.write(b'\r\n!\r\n') payload.write('--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo_content/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.json()['file'], '') def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accented char in the name. with open(os.path.join(temp_dir, UNICODE_FILENAME), 'w+b') as file1: file1.write(b'b' * (2 ** 10)) file1.seek(0) response = self.client.post('/unicode_name/', {'file_unicode': file1}) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; filename*=UTF-8\'\'%s' % quote(UNICODE_FILENAME), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ])) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( '\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % quote( UNICODE_FILENAME ), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ]) ) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231_with_double_quotes(self): payload = client.FakePayload() payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; ' 'filename*="UTF-8\'\'%s"' % quote(UNICODE_FILENAME), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n', ])) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/unicode_name/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231_with_double_quotes(self): payload = client.FakePayload() payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name*="UTF-8\'\'file_unicode"; ' 'filename*="UTF-8\'\'%s"' % quote(UNICODE_FILENAME), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ])) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/unicode_name/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_blank_filenames(self): """ Receiving file upload when filename is blank (before and after sanitization) should be okay. """ filenames = [ '', # Normalized by MultiPartParser.IE_sanitize(). 'C:\\Windows\\', # Normalized by os.path.basename(). '/', 'ends-with-slash/', ] payload = client.FakePayload() for i, name in enumerate(filenames): payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n' ])) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) # Empty filenames should be ignored received = response.json() for i, name in enumerate(filenames): self.assertIsNone(received.get('file%s' % i)) def test_non_printable_chars_in_file_names(self): file_name = 'non-\x00printable\x00\n_chars.txt\x00' payload = client.FakePayload() payload.write('\r\n'.join([ '--' + client.BOUNDARY, f'Content-Disposition: form-data; name="file"; filename="{file_name}"', 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n' ])) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) # Non-printable chars are sanitized. received = response.json() self.assertEqual(received['file'], 'non-printable_chars.txt') def test_dangerous_file_names(self): """Uploaded file names should be sanitized before ever reaching the view.""" # This test simulates possible directory traversal attacks by a # malicious uploader We have to do some monkeybusiness here to construct # a malicious payload with an invalid file name (containing os.sep or # os.pardir). This similar to what an attacker would need to do when # trying such an attack. payload = client.FakePayload() for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES): payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n' ])) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) # The filenames should have been sanitized by the time it got to the view. received = response.json() for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES): got = received["file%s" % i] self.assertEqual(got, "hax0rd.txt") def test_filename_overflow(self): """File names over 256 characters (dangerous on some platforms) get fixed up.""" long_str = 'f' * 300 cases = [ # field name, filename, expected ('long_filename', '%s.txt' % long_str, '%s.txt' % long_str[:251]), ('long_extension', 'foo.%s' % long_str, '.%s' % long_str[:254]), ('no_extension', long_str, long_str[:255]), ('no_filename', '.%s' % long_str, '.%s' % long_str[:254]), ('long_everything', '%s.%s' % (long_str, long_str), '.%s' % long_str[:254]), ] payload = client.FakePayload() for name, filename, _ in cases: payload.write("\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="{}"; filename="{}"', 'Content-Type: application/octet-stream', '', 'Oops.', '' ]).format(name, filename)) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) result = response.json() for name, _, expected in cases: got = result[name] self.assertEqual(expected, got, 'Mismatch for {}'.format(name)) self.assertLess(len(got), 256, "Got a long file name (%s characters)." % len(got)) def test_file_content(self): file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file: no_content_type.write(b'no content') no_content_type.seek(0) simple_file.write(b'text content') simple_file.seek(0) simple_file.content_type = 'text/plain' string_io = StringIO('string content') bytes_io = BytesIO(b'binary content') response = self.client.post('/echo_content/', { 'no_content_type': no_content_type, 'simple_file': simple_file, 'string': string_io, 'binary': bytes_io, }) received = response.json() self.assertEqual(received['no_content_type'], 'no content') self.assertEqual(received['simple_file'], 'text content') self.assertEqual(received['string'], 'string content') self.assertEqual(received['binary'], 'binary content') def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file: no_content_type.write(b'something') no_content_type.seek(0) simple_file.write(b'something') simple_file.seek(0) simple_file.content_type = 'text/plain; test-key=test_value' response = self.client.post('/echo_content_type_extra/', { 'no_content_type': no_content_type, 'simple_file': simple_file, }) received = response.json() self.assertEqual(received['no_content_type'], {}) self.assertEqual(received['simple_file'], {'test-key': 'test_value'}) def test_truncated_multipart_handled_gracefully(self): """ If passed an incomplete multipart message, MultiPartParser does not attempt to read beyond the end of the stream, and simply will handle the part that can be parsed gracefully. """ payload_str = "\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="foo.txt"', 'Content-Type: application/octet-stream', '', 'file contents' '--' + client.BOUNDARY + '--', '', ]) payload = client.FakePayload(payload_str[:-10]) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } self.assertEqual(self.client.request(**r).json(), {}) def test_empty_multipart_handled_gracefully(self): """ If passed an empty multipart message, MultiPartParser will return an empty QueryDict. """ r = { 'CONTENT_LENGTH': 0, 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': client.FakePayload(b''), } self.assertEqual(self.client.request(**r).json(), {}) def test_custom_upload_handler(self): file = tempfile.NamedTemporaryFile with file() as smallfile, file() as bigfile: # A small file (under the 5M quota) smallfile.write(b'a' * (2 ** 21)) smallfile.seek(0) # A big file (over the quota) bigfile.write(b'a' * (10 * 2 ** 20)) bigfile.seek(0) # Small file posting should work. self.assertIn('f', self.client.post('/quota/', {'f': smallfile}).json()) # Large files don't go through. self.assertNotIn('f', self.client.post("/quota/", {'f': bigfile}).json()) def test_broken_custom_upload_handler(self): with tempfile.NamedTemporaryFile() as file: file.write(b'a' * (2 ** 21)) file.seek(0) msg = 'You cannot alter upload handlers after the upload has been processed.' with self.assertRaisesMessage(AttributeError, msg): self.client.post('/quota/broken/', {'f': file}) def test_stop_upload_temporary_file_handler(self): with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(b'a') temp_file.seek(0) response = self.client.post('/temp_file/stop_upload/', {'file': temp_file}) temp_path = response.json()['temp_path'] self.assertIs(os.path.exists(temp_path), False) def test_upload_interrupted_temporary_file_handler(self): # Simulate an interrupted upload by omitting the closing boundary. class MockedParser(Parser): def __iter__(self): for item in super().__iter__(): item_type, meta_data, field_stream = item yield item_type, meta_data, field_stream if item_type == FILE: return with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(b'a') temp_file.seek(0) with mock.patch( 'django.http.multipartparser.Parser', MockedParser, ): response = self.client.post( '/temp_file/upload_interrupted/', {'file': temp_file}, ) temp_path = response.json()['temp_path'] self.assertIs(os.path.exists(temp_path), False) def test_fileupload_getlist(self): file = tempfile.NamedTemporaryFile with file() as file1, file() as file2, file() as file2a: file1.write(b'a' * (2 ** 23)) file1.seek(0) file2.write(b'a' * (2 * 2 ** 18)) file2.seek(0) file2a.write(b'a' * (5 * 2 ** 20)) file2a.seek(0) response = self.client.post('/getlist_count/', { 'file1': file1, 'field1': 'test', 'field2': 'test3', 'field3': 'test5', 'field4': 'test6', 'field5': 'test7', 'file2': (file2, file2a) }) got = response.json() self.assertEqual(got.get('file1'), 1) self.assertEqual(got.get('file2'), 2) def test_fileuploads_closed_at_request_end(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post('/fd_closing/t/', { 'file': f1, 'file2': (f2a, f2b), }) request = response.wsgi_request # The files were parsed. self.assertTrue(hasattr(request, '_files')) file = request._files['file'] self.assertTrue(file.closed) files = request._files.getlist('file2') self.assertTrue(files[0].closed) self.assertTrue(files[1].closed) def test_no_parsing_triggered_by_fd_closing(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post('/fd_closing/f/', { 'file': f1, 'file2': (f2a, f2b), }) request = response.wsgi_request # The fd closing logic doesn't trigger parsing of the stream self.assertFalse(hasattr(request, '_files')) def test_file_error_blocking(self): """ The server should not block when there are upload errors (bug #8622). This can happen if something -- i.e. an exception handler -- tries to access POST while handling an error in parsing POST. This shouldn't cause an infinite loop! """ class POSTAccessingHandler(client.ClientHandler): """A handler that'll access POST during an exception.""" def handle_uncaught_exception(self, request, resolver, exc_info): ret = super().handle_uncaught_exception(request, resolver, exc_info) request.POST # evaluate return ret # Maybe this is a little more complicated that it needs to be; but if # the django.test.client.FakePayload.read() implementation changes then # this test would fail. So we need to know exactly what kind of error # it raises when there is an attempt to read more than the available bytes: try: client.FakePayload(b'a').read(2) except Exception as err: reference_error = err # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, } try: self.client.post('/upload_errors/', post_data) except reference_error.__class__ as err: self.assertNotEqual( str(err), str(reference_error), "Caught a repeated exception that'll cause an infinite loop in file uploads." ) except Exception as err: # CustomUploadError is the error that should have been raised self.assertEqual(err.__class__, uploadhandler.CustomUploadError) def test_filename_case_preservation(self): """ The storage backend shouldn't mess with the case of the filenames uploaded. """ # Synthesize the contents of a file upload with a mixed case filename # so we don't have to carry such a file in the Django tests source code # tree. vars = {'boundary': 'oUrBoUnDaRyStRiNg'} post_data = [ '--%(boundary)s', 'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"', 'Content-Type: application/octet-stream', '', 'file contents\n' '', '--%(boundary)s--\r\n', ] response = self.client.post( '/filename_case/', '\r\n'.join(post_data) % vars, 'multipart/form-data; boundary=%(boundary)s' % vars ) self.assertEqual(response.status_code, 200) id = int(response.content) obj = FileModel.objects.get(pk=id) # The name of the file uploaded and the file stored in the server-side # shouldn't differ. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt') def test_filename_traversal_upload(self): os.makedirs(UPLOAD_TO, exist_ok=True) tests = [ '..&#x2F;test.txt', '..&sol;test.txt', ] for file_name in tests: with self.subTest(file_name=file_name): payload = client.FakePayload() payload.write( '\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="my_file"; ' 'filename="%s";' % file_name, 'Content-Type: text/plain', '', 'file contents.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n', ]), ) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/upload_traversal/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['file_name'], 'test.txt') self.assertIs( os.path.exists(os.path.join(MEDIA_ROOT, 'test.txt')), False, ) self.assertIs( os.path.exists(os.path.join(UPLOAD_TO, 'test.txt')), True, ) @override_settings(MEDIA_ROOT=MEDIA_ROOT) class DirectoryCreationTests(SimpleTestCase): """ Tests for error handling during directory creation via _save_FIELD_file (ticket #6450) """ @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT) def setUp(self): self.obj = FileModel() @unittest.skipIf(sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().") def test_readonly_root(self): """Permission errors are not swallowed""" os.chmod(MEDIA_ROOT, 0o500) self.addCleanup(os.chmod, MEDIA_ROOT, 0o700) with self.assertRaises(PermissionError): self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'), save=False) def test_not_a_directory(self): # Create a file with the upload directory name open(UPLOAD_TO, 'wb').close() self.addCleanup(os.remove, UPLOAD_TO) msg = '%s exists and is not a directory.' % UPLOAD_TO with self.assertRaisesMessage(FileExistsError, msg): with SimpleUploadedFile('foo.txt', b'x') as file: self.obj.testfile.save('foo.txt', file, save=False) class MultiParserTests(SimpleTestCase): def test_empty_upload_handlers(self): # We're not actually parsing here; just checking if the parser properly # instantiates with empty upload handlers. MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': '1' }, StringIO('x'), [], 'utf-8') def test_invalid_content_type(self): with self.assertRaisesMessage(MultiPartParserError, 'Invalid Content-Type: text/plain'): MultiPartParser({ 'CONTENT_TYPE': 'text/plain', 'CONTENT_LENGTH': '1', }, StringIO('x'), [], 'utf-8') def test_negative_content_length(self): with self.assertRaisesMessage(MultiPartParserError, 'Invalid content length: -1'): MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': -1, }, StringIO('x'), [], 'utf-8') def test_bad_type_content_length(self): multipart_parser = MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': 'a', }, StringIO('x'), [], 'utf-8') self.assertEqual(multipart_parser._content_length, 0) def test_sanitize_file_name(self): parser = MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': '1' }, StringIO('x'), [], 'utf-8') for file_name in CANDIDATE_TRAVERSAL_FILE_NAMES: with self.subTest(file_name=file_name): self.assertEqual(parser.sanitize_file_name(file_name), 'hax0rd.txt') def test_sanitize_invalid_file_name(self): parser = MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': '1', }, StringIO('x'), [], 'utf-8') for file_name in CANDIDATE_INVALID_FILE_NAMES: with self.subTest(file_name=file_name): self.assertIsNone(parser.sanitize_file_name(file_name)) def test_rfc2231_parsing(self): test_data = ( (b"Content-Type: application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***"), (b"Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html"), (b"Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]['title'], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( (b"Content-Type: application/x-stuff; title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", b"'This%20is%20%2A%2A%2Afun%2A%2A%2A"), (b"Content-Type: application/x-stuff; title*='foo.html", b"'foo.html"), (b"Content-Type: application/x-stuff; title*=bar.html", b"bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]['title'], expected_title)
c2c9855a3a7bb10092c4dd931803a892f19fea63c969bc057d53e883713e262c
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock, skipIf from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.http import Http404, HttpRequest, HttpResponse from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse from django.urls.converters import IntConverter from django.utils.functional import SimpleLazyObject from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.views.debug import ( CallableSettingWrapper, ExceptionCycleWarning, ExceptionReporter, Path as DebugPath, SafeExceptionReporterFilter, default_urlconf, get_default_exception_reporter_filter, technical_404_response, technical_500_response, ) from django.views.decorators.debug import ( sensitive_post_parameters, sensitive_variables, ) from ..views import ( custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return 'jacob' class WithoutEmptyPathUrls: urlpatterns = [path('url/', index_page, name='url')] class CallableSettingWrapperTests(SimpleTestCase): """ Unittests for CallableSettingWrapper """ def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises/') self.assertEqual(response.status_code, 500) data = { 'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'), } with self.assertLogs('django.request', 'ERROR'): response = self.client.post('/raises/', data) self.assertContains(response, 'file_data.txt', status_code=500) self.assertNotContains(response, 'haha', status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.request', 'WARNING') as cm: response = self.client.get('/raises400_bad_request/') self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), 'Malformed request syntax: /raises400_bad_request/', ) # Ensure no 403.html template exists to test the default case. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', }]) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) # Set up a test 403.html template. @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '403.html': 'This is a test template for a 403 error ({{ exception }}).', }), ], }, }]) def test_403_template(self): response = self.client.get('/raises403/') self.assertContains(response, 'test template', status_code=403) self.assertContains(response, '(Insufficient Permissions).', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains( response, '<p>The current path, <code>not-in-urls</code>, didn’t match any ' 'of these.</p>', status_code=404, html=True, ) def test_404_not_in_urls(self): response = self.client.get('/not-in-urls') self.assertNotContains(response, "Raised by:", status_code=404) self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains(response, "Django tried these URL patterns", status_code=404) self.assertContains( response, '<p>The current path, <code>not-in-urls</code>, didn’t match any ' 'of these.</p>', status_code=404, html=True, ) # Pattern and view name of a RegexURLPattern appear. self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get('/') self.assertContains( response, '<p>The empty path didn’t match any of these.</p>', status_code=404, html=True, ) def test_technical_404(self): response = self.client.get('/technical404/') self.assertContains( response, '<pre class="exception_value">Testing technical 404.</pre>', status_code=404, html=True, ) self.assertContains(response, "Raised by:", status_code=404) self.assertContains( response, '<td>view_tests.views.technical404</td>', status_code=404, ) self.assertContains( response, '<p>The current path, <code>technical404/</code>, matched the ' 'last one.</p>', status_code=404, html=True, ) def test_classbased_technical_404(self): response = self.client.get('/classbased404/') self.assertContains( response, '<th>Raised by:</th><td>view_tests.views.Http404View</td>', status_code=404, html=True, ) def test_technical_500(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') self.assertContains( response, '<th>Raised during:</th><td>view_tests.views.raises500</td>', status_code=500, html=True, ) with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/', HTTP_ACCEPT='text/plain') self.assertContains( response, 'Raised during: view_tests.views.raises500', status_code=500, ) def test_classbased_technical_500(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/classbased500/') self.assertContains( response, '<th>Raised during:</th><td>view_tests.views.Raises500View</td>', status_code=500, html=True, ) with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/classbased500/', HTTP_ACCEPT='text/plain') self.assertContains( response, 'Raised during: view_tests.views.Raises500View', status_code=500, ) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"' self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content) self.assertIsNotNone(match) id_repr = match['id'] self.assertFalse( re.search(b'[^c0-9]', id_repr), "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr.decode() ) def test_template_exceptions(self): with self.assertLogs('django.request', 'ERROR'): try: self.client.get(reverse('template_exception')) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find("raise Exception('boom')"), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc ) @skipIf( sys.platform == 'win32', 'Raises OSError instead of TemplateDoesNotExist on Windows.', ) def test_safestring_in_exception(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/safestring_exception/') self.assertNotContains( response, '<script>alert(1);</script>', status_code=500, html=True, ) self.assertContains( response, '&lt;script&gt;alert(1);&lt;/script&gt;', count=3, status_code=500, html=True, ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [tempdir], }]), self.assertLogs('django.request', 'ERROR'): response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name})) self.assertContains(response, "%s (Source does not exist)" % template_path, status_code=500, count=2) # Assert as HTML. self.assertContains( response, '<li><code>django.template.loaders.filesystem.Loader</code>: ' '%s (Source does not exist)</li>' % os.path.join(tempdir, 'notfound.html'), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs('django.request', 'ERROR'): with self.assertRaises(TemplateDoesNotExist): self.client.get('/render_no_template/') @override_settings(ROOT_URLCONF='view_tests.default_urls') def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get('/') self.assertContains( response, "<h1>The install worked successfully! Congratulations!</h1>" ) @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls') def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get('/') self.assertContains( response, "Page not found <span>(404)</span>", status_code=404 ) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ with mock.patch.object(DebugPath, 'open') as m: default_urlconf(None) m.assert_called_once_with(encoding='utf-8') m.reset_mock() technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding='utf-8') def test_technical_404_converter_raise_404(self): with mock.patch.object(IntConverter, 'to_python', side_effect=Http404): response = self.client.get('/path-post/1/') self.assertContains(response, 'Page not found', status_code=404) def test_exception_reporter_from_request(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/custom_reporter_class_view/') self.assertContains(response, 'custom traceback text', status_code=500) @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.CustomExceptionReporter') def test_exception_reporter_from_settings(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') self.assertContains(response, 'custom traceback text', status_code=500) @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.TemplateOverrideExceptionReporter') def test_template_override_exception_reporter(self): with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/') self.assertContains( response, '<h1>Oh no, an error occurred!</h1>', status_code=500, html=True, ) with self.assertLogs('django.request', 'ERROR'): response = self.client.get('/raises500/', HTTP_ACCEPT='text/plain') self.assertContains(response, 'Oh dear, an error occurred!', status_code=500) class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection databases = {'default'} def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute('INVALID SQL') except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get('/'), *exc_info) self.assertContains(response, 'OperationalError at /', status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF='view_tests.urls', # No template directories are configured, so no templates will be found. TEMPLATES=[{ 'BACKEND': 'django.template.backends.dummy.TemplateStrings', }], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.security', 'WARNING'): response = self.client.get('/raises400/') self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs('django.request', 'WARNING') as cm: response = self.client.get('/raises400_bad_request/') self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), 'Malformed request syntax: /raises400_bad_request/', ) def test_403(self): response = self.client.get('/raises403/') self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) def test_404(self): response = self.client.get('/raises404/') self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"}) with self.assertLogs('django.request', 'ERROR'): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>jacob</p>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) self.assertIn('<p>No POST data</p>', html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_sharing_traceback(self): try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( '<form action="https://dpaste.com/" name="pasteform" ' 'id="pasteform" method="post">', html, ) def test_eol_support(self): """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" LINES = ['print %d' % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ['\n', '\r\n', '\r']: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]) ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertNotIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_suppressed_context(self): try: try: raise RuntimeError("Can't find my keys") except RuntimeError: raise ValueError("Can't find my keys") from None except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError</h1>', html) self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) self.assertNotIn('During handling of the above exception', html) def test_innermost_exception_without_traceback(self): try: try: raise RuntimeError('Oops') except Exception as exc: new_exc = RuntimeError('My context') exc.__context__ = new_exc raise except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() self.assertEqual(len(frames), 2) html = reporter.get_traceback_html() self.assertInHTML('<h1>RuntimeError</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) self.assertIn( 'During handling of the above exception (My context), another ' 'exception occurred', html, ) self.assertInHTML('<li class="frame user">None</li>', html) self.assertIn('Traceback (most recent call last):\n None', html) text = reporter.get_traceback_text() self.assertIn('Exception Type: RuntimeError', text) self.assertIn('Exception Value: Oops', text) self.assertIn('Traceback (most recent call last):\n None', text) self.assertIn( 'During handling of the above exception (My context), another ' 'exception occurred', text, ) def test_mid_stack_exception_without_traceback(self): try: try: raise RuntimeError('Inner Oops') except Exception as exc: new_exc = RuntimeError('My context') new_exc.__context__ = exc raise RuntimeError('Oops') from new_exc except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>RuntimeError</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<th>Exception Type:</th>', html) self.assertIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertInHTML('<li class="frame user">Traceback: None</li>', html) self.assertIn( 'During handling of the above exception (Inner Oops), another ' 'exception occurred:\n Traceback: None', html, ) text = reporter.get_traceback_text() self.assertIn('Exception Type: RuntimeError', text) self.assertIn('Exception Value: Oops', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn( 'During handling of the above exception (Inner Oops), another ' 'exception occurred:\n Traceback: None', text, ) def test_reporting_of_nested_exceptions(self): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second exception</p>')) from explicit except ValueError: raise IndexError(mark_safe('<p>Final exception</p>')) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:' implicit_exc = 'During handling of the above exception ({0}), another exception occurred:' reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;'))) self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;')) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format('<p>Top level</p>'), text) self.assertIn(implicit_exc.format('<p>Second exception</p>'), text) self.assertEqual(3, text.count('<p>Final exception</p>')) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', text, ) def test_reporting_frames_source_not_match(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, 'generated', 'exec') exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() with mock.patch( 'django.views.debug.ExceptionReporter._get_source', return_value=['wrong source'], ): request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame['context_line'], '<source code not available>') self.assertEqual(last_frame['filename'], 'generated') self.assertEqual(last_frame['function'], 'funcName') self.assertEqual(last_frame['lineno'], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' ' &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n' ' <source code not available>', text, ) def test_reporting_frames_for_cyclic_reference(self): try: def test_func(): try: raise RuntimeError('outer') from RuntimeError('inner') except RuntimeError as exc: raise exc.__cause__ test_func() except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, exc_type, exc_value, tb) def generate_traceback_frames(*args, **kwargs): nonlocal tb_frames tb_frames = reporter.get_traceback_frames() tb_frames = None tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True) msg = ( "Cycle in the exception chain detected: exception 'inner' " "encountered again." ) with self.assertWarnsMessage(ExceptionCycleWarning, msg): tb_generator.start() tb_generator.join(timeout=5) if tb_generator.is_alive(): # tb_generator is a daemon that runs until the main thread/process # exits. This is resource heavy when running the full test suite. # Setting the following values to None makes # reporter.get_traceback_frames() exit early. exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None tb_generator.join() self.fail('Cyclic reference in Exception Reporter.get_traceback_frames()') if tb_frames is None: # can happen if the thread generating traceback got killed # or exception while generating the traceback self.fail('Traceback generation failed') last_frame = tb_frames[-1] self.assertIn('raise exc.__cause__', last_frame['context_line']) self.assertEqual(last_frame['filename'], __file__) self.assertEqual(last_frame['function'], 'test_func') def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertIn('<th>Request Method:</th>', html) self.assertIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertNotIn('<p>Request data not supplied</p>', html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML('<h1>Report</h1>', html) self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html) self.assertNotIn('<th>Request Method:</th>', html) self.assertNotIn('<th>Request URL:</th>', html) self.assertNotIn('<th>Exception Type:</th>', html) self.assertNotIn('<th>Exception Value:</th>', html) self.assertIn('<h2>Traceback ', html) self.assertIn('<h2>Request information</h2>', html) self.assertIn('<p>Request data not supplied</p>', html) def test_non_utf8_values_handling(self): "Non-UTF-8 exceptions/values should not make the output generation choke." try: class NonUtf8Output(Exception): def __repr__(self): return b'EXC\xe9EXC' somevar = b'VAL\xe9VAL' # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('VAL\\xe9VAL', html) self.assertIn('EXC\\xe9EXC', html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe('<p>Local variable</p>') raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn('<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>', html) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError('OOM') oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr('')) try: class LargeOutput: def __repr__(self): return repr('A' * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe('abcdefghijkl<p>mnὀp</p>qrstuwxyz').encode('ascii') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<h2>Unicode error hint</h2>', html) self.assertIn('The string that could not be encoded/decoded was: ', html) self.assertIn('<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>', html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get('/test_view/') importlib.import_module('abc.def.invalid.name') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ModuleNotFoundError at /test_view/</h1>', html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get('/test_view/') broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback" ) @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>' # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' 'items (application/octet-stream)&gt;</pre></td>', html ) # COOKIES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML('<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get('/test_view/') request.user = ExceptionUser() try: raise ValueError('Oops') except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML('<h1>ValueError at /test_view/</h1>', html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn('<p>[unable to retrieve the current user]</p>', html) text = reporter.get_traceback_text() self.assertIn('USER: [unable to retrieve the current user]', text) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ reporter = ExceptionReporter(None, None, None, None) with mock.patch.object(DebugPath, 'open') as m: reporter.get_traceback_html() m.assert_called_once_with(encoding='utf-8') m.reset_mock() reporter.get_traceback_text() m.assert_called_once_with(encoding='utf-8') @override_settings(ALLOWED_HOSTS=['example.com']) def test_get_raw_insecure_uri(self): factory = RequestFactory(HTTP_HOST='evil.com') tests = [ ('////absolute-uri', 'http://evil.com//absolute-uri'), ('/?foo=bar', 'http://evil.com/?foo=bar'), ('/path/with:colons', 'http://evil.com/path/with:colons'), ] for url, expected in tests: with self.subTest(url=url): request = factory.get(url) reporter = ExceptionReporter(request, None, None, None) self.assertEqual(reporter._get_raw_insecure_uri(), expected) class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get('/test_view/') request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError at /test_view/', text) self.assertIn("Can't find my keys", text) self.assertIn('Request Method:', text) self.assertIn('Request URL:', text) self.assertIn('USER: jacob', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn('Request information:', text) self.assertNotIn('Request data not supplied', text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn('ValueError', text) self.assertIn("Can't find my keys", text) self.assertNotIn('Request Method:', text) self.assertNotIn('Request URL:', text) self.assertNotIn('USER:', text) self.assertIn('Exception Type:', text) self.assertIn('Exception Value:', text) self.assertIn('Traceback (most recent call last):', text) self.assertIn('Request data not supplied', text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get('/test_view/') reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get('/test_view/') try: render(request, 'debug/template_error.html') except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path(Path(__file__).parents[1], 'templates', 'debug', 'template_error.html') self.assertIn( 'Template error:\n' 'In template %(path)s, error at line 2\n' ' \'cycle\' tag requires at least two arguments\n' ' 1 : Template with error:\n' ' 2 : {%% cycle %%} \n' ' 3 : ' % {'path': templ_path}, text ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get('/test_view/?items=Oops') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post('/test_view/', data={'items': 'Oops'}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO('filecontent') request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn('items = <InMemoryUploadedFile:', text) # COOKIES rf = RequestFactory() rf.cookies['items'] = 'Oops' request = rf.get('/test_view/') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS='example.com') def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get('/', HTTP_HOST='evil.com') reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = { 'sausage-key': 'sausage-value', 'baked-beans-key': 'baked-beans-value', 'hash-brown-key': 'hash-brown-value', 'bacon-key': 'bacon-value', } def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertContains(response, 'scrambled', status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, 'baked-beans-value', status_code=500) self.assertContains(response, 'hash-brown-value', status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, 'sausage-value', status_code=500) self.assertNotContains(response, 'bacon-value', status_code=500) def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post('/some_url/', self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, 'cooked_eggs', status_code=500) self.assertNotContains(response, 'scrambled', status_code=500) self.assertContains(response, 'sauce', status_code=500) self.assertNotContains(response, 'worcestershire', status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertIn('worcestershire', body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn('cooked_eggs', body_plain) self.assertNotIn('scrambled', body_plain) self.assertNotIn('sauce', body_plain) self.assertNotIn('worcestershire', body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn('cooked_eggs', body_html) self.assertIn('scrambled', body_html) self.assertIn('sauce', body_html) self.assertNotIn('worcestershire', body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn('baked-beans-value', body_plain) self.assertIn('hash-brown-value', body_plain) self.assertIn('baked-beans-value', body_html) self.assertIn('hash-brown-value', body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn('sausage-value', body_plain) self.assertNotIn('bacon-value', body_plain) self.assertNotIn('sausage-value', body_html) self.assertNotIn('bacon-value', body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=[('Admin', '[email protected]')]): mail.outbox = [] # Empty outbox request = self.rf.post('/some_url/', self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn('cooked_eggs', body) self.assertNotIn('scrambled', body) self.assertNotIn('sauce', body) self.assertNotIn('worcestershire', body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF='view_tests.urls') class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_method_view, check_for_POST_params=False) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get('/raises500/') self.assertNotContains(response, "This should not be displayed", status_code=500) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get('/raises500/') self.assertContains(response, 'FOOBAR', status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ sensitive_settings = [ 'SECRET_KEY', 'SECRET_KEY_FALLBACKS', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ sensitive_settings = [ 'SECRET_KEY', 'SECRET_KEY_FALLBACKS', 'PASSWORD', 'API_KEY', 'AUTH_TOKEN', ] for setting in sensitive_settings: FOOBAR = { setting: "should not be displayed", 'recursive': {setting: "should not be displayed"}, } with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get('/raises500/') self.assertNotContains(response, 'should not be displayed', status_code=500) def test_cleanse_setting_basic(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual(reporter_filter.cleanse_setting('TEST', 'TEST'), 'TEST') self.assertEqual( reporter_filter.cleanse_setting('PASSWORD', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_ignore_case(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.cleanse_setting('password', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_recurses_in_dictionary(self): reporter_filter = SafeExceptionReporterFilter() initial = {'login': 'cooper', 'password': 'secret'} self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), {'login': 'cooper', 'password': reporter_filter.cleansed_substitute}, ) def test_cleanse_setting_recurses_in_dictionary_with_non_string_key(self): reporter_filter = SafeExceptionReporterFilter() initial = {('localhost', 8000): {'login': 'cooper', 'password': 'secret'}} self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), { ('localhost', 8000): { 'login': 'cooper', 'password': reporter_filter.cleansed_substitute, }, }, ) def test_cleanse_setting_recurses_in_list_tuples(self): reporter_filter = SafeExceptionReporterFilter() initial = [ { 'login': 'cooper', 'password': 'secret', 'apps': ( {'name': 'app1', 'api_key': 'a06b-c462cffae87a'}, {'name': 'app2', 'api_key': 'a9f4-f152e97ad808'}, ), 'tokens': ['98b37c57-ec62-4e39', '8690ef7d-8004-4916'], }, {'SECRET_KEY': 'c4d77c62-6196-4f17-a06b-c462cffae87a'}, ] cleansed = [ { 'login': 'cooper', 'password': reporter_filter.cleansed_substitute, 'apps': ( {'name': 'app1', 'api_key': reporter_filter.cleansed_substitute}, {'name': 'app2', 'api_key': reporter_filter.cleansed_substitute}, ), 'tokens': reporter_filter.cleansed_substitute, }, {'SECRET_KEY': reporter_filter.cleansed_substitute}, ] self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', initial), cleansed, ) self.assertEqual( reporter_filter.cleanse_setting('SETTING_NAME', tuple(initial)), tuple(cleansed), ) def test_request_meta_filtering(self): request = self.rf.get('/', HTTP_SECRET_HEADER='super_secret') reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.get_safe_request_meta(request)['HTTP_SECRET_HEADER'], reporter_filter.cleansed_substitute, ) def test_exception_report_uses_meta_filtering(self): response = self.client.get('/raises500/', HTTP_SECRET_HEADER='super_secret') self.assertNotIn(b'super_secret', response.content) response = self.client.get( '/raises500/', HTTP_SECRET_HEADER='super_secret', HTTP_ACCEPT='application/json', ) self.assertNotIn(b'super_secret', response.content) class CustomExceptionReporterFilter(SafeExceptionReporterFilter): cleansed_substitute = 'XXXXXXXXXXXXXXXXXXXX' hidden_settings = _lazy_re_compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE|DATABASE_URL', flags=re.I) @override_settings( ROOT_URLCONF='view_tests.urls', DEFAULT_EXCEPTION_REPORTER_FILTER='%s.CustomExceptionReporterFilter' % __name__, ) class CustomExceptionReporterFilterTests(SimpleTestCase): def setUp(self): get_default_exception_reporter_filter.cache_clear() def tearDown(self): get_default_exception_reporter_filter.cache_clear() def test_setting_allows_custom_subclass(self): self.assertIsInstance( get_default_exception_reporter_filter(), CustomExceptionReporterFilter, ) def test_cleansed_substitute_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting('password', 'super_secret'), reporter_filter.cleansed_substitute, ) def test_hidden_settings_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting('database_url', 'super_secret'), reporter_filter.cleansed_substitute, ) class NonHTMLResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase): """ Sensitive information can be filtered out of error reports. The plain text 500 debug-only error page is served when it has been detected the request doesn't accept HTML content. Don't check for (non)existence of frames vars in the traceback information section of the response content because they're not included in these error pages. Refs #14614. """ rf = RequestFactory(HTTP_ACCEPT='application/json') def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls') def test_non_html_response_encoding(self): response = self.client.get('/raises500/', HTTP_ACCEPT='application/json') self.assertEqual(response.headers['Content-Type'], 'text/plain; charset=utf-8') class DecoratorsTests(SimpleTestCase): def test_sensitive_variables_not_called(self): msg = ( 'sensitive_variables() must be called to use it as a decorator, ' 'e.g., use @sensitive_variables(), not @sensitive_variables.' ) with self.assertRaisesMessage(TypeError, msg): @sensitive_variables def test_func(password): pass def test_sensitive_post_parameters_not_called(self): msg = ( 'sensitive_post_parameters() must be called to use it as a ' 'decorator, e.g., use @sensitive_post_parameters(), not ' '@sensitive_post_parameters.' ) with self.assertRaisesMessage(TypeError, msg): @sensitive_post_parameters def test_func(request): return index_page(request) def test_sensitive_post_parameters_http_request(self): class MyClass: @sensitive_post_parameters() def a_view(self, request): return HttpResponse() msg = ( "sensitive_post_parameters didn't receive an HttpRequest object. " "If you are decorating a classmethod, make sure to use " "@method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())
90402b0aa46d006070dc29b66dd15374be87e65f8a22d275fcac7076b6c96819
from django.contrib.auth.models import Group from django.test import SimpleTestCase, override_settings from ..utils import setup @override_settings(DEBUG=True) class DebugTests(SimpleTestCase): @override_settings(DEBUG=False) @setup({'non_debug': '{% debug %}'}) def test_non_debug(self): output = self.engine.render_to_string('non_debug', {}) self.assertEqual(output, '') @setup({'modules': '{% debug %}'}) def test_modules(self): output = self.engine.render_to_string('modules', {}) self.assertIn( '&#x27;django&#x27;: &lt;module &#x27;django&#x27; ', output, ) @setup({'plain': '{% debug %}'}) def test_plain(self): output = self.engine.render_to_string('plain', {'a': 1}) self.assertTrue(output.startswith( '{&#x27;a&#x27;: 1}' '{&#x27;False&#x27;: False, &#x27;None&#x27;: None, ' '&#x27;True&#x27;: True}\n\n{' )) @setup({'non_ascii': '{% debug %}'}) def test_non_ascii(self): group = Group(name="清風") output = self.engine.render_to_string('non_ascii', {'group': group}) self.assertTrue(output.startswith( '{&#x27;group&#x27;: &lt;Group: 清風&gt;}' )) @setup({'script': '{% debug %}'}) def test_script(self): output = self.engine.render_to_string('script', {'frag': '<script>'}) self.assertTrue(output.startswith( '{&#x27;frag&#x27;: &#x27;&lt;script&gt;&#x27;}' ))
e4c1e42858ed8fb8ce2cd6028894ac7631747f940e32c886e8868ce6c031cf73
import os import site import sys from distutils.sysconfig import get_python_lib from setuptools import setup # Allow editable install into user site directory. # See https://github.com/pypa/pip/issues/7953. site.ENABLE_USER_SITE = "--user" in sys.argv[1:] # Warn if we are installing over top of an existing installation. This can # cause issues where files that were deleted from a more recent Django are # still present in site-packages. See #18115. overlay_warning = False if "install" in sys.argv: lib_paths = [get_python_lib()] if lib_paths[0].startswith("/usr/lib/"): # We have to try also with an explicit prefix of /usr/local in order to # catch Debian's custom user site-packages directory. lib_paths.append(get_python_lib(prefix="/usr/local")) for lib_path in lib_paths: existing_path = os.path.abspath(os.path.join(lib_path, "django")) if os.path.exists(existing_path): # We note the need for the warning here, but present it after the # command is run, so it's more likely to be seen. overlay_warning = True break setup() if overlay_warning: sys.stderr.write( """ ======== WARNING! ======== You have just installed Django over top of an existing installation, without removing it first. Because of this, your install may now include extraneous files from a previous version that have since been removed from Django. This is known to cause a variety of problems. You should manually remove the %(existing_path)s directory and re-install Django. """ % {"existing_path": existing_path} )
df8bcbc4392006b69c19f4f807d1edf0b6702b5c8c7e630c87a3fd9ad62803bb
#!/usr/bin/env python # # This Python file contains utility scripts to manage Django translations. # It has to be run inside the django git root directory. # # The following commands are available: # # * update_catalogs: check for new strings in core and contrib catalogs, and # output how much strings are new/changed. # # * lang_stats: output statistics for each catalog/language combination # # * fetch: fetch translations from transifex.com # # Each command support the --languages and --resources options to limit their # operation to the specified language or resource. For example, to get stats # for Spanish in contrib.admin, run: # # $ python scripts/manage_translations.py lang_stats --language=es --resources=admin import os from argparse import ArgumentParser from subprocess import run import django from django.conf import settings from django.core.management import call_command HAVE_JS = ["admin"] def _get_locale_dirs(resources, include_core=True): """ Return a tuple (contrib name, absolute path) for all locale directories, optionally including the django core catalog. If resources list is not None, filter directories matching resources content. """ contrib_dir = os.path.join(os.getcwd(), "django", "contrib") dirs = [] # Collect all locale directories for contrib_name in os.listdir(contrib_dir): path = os.path.join(contrib_dir, contrib_name, "locale") if os.path.isdir(path): dirs.append((contrib_name, path)) if contrib_name in HAVE_JS: dirs.append(("%s-js" % contrib_name, path)) if include_core: dirs.insert(0, ("core", os.path.join(os.getcwd(), "django", "conf", "locale"))) # Filter by resources, if any if resources is not None: res_names = [d[0] for d in dirs] dirs = [ld for ld in dirs if ld[0] in resources] if len(resources) > len(dirs): print( "You have specified some unknown resources. " "Available resource names are: %s" % (", ".join(res_names),) ) exit(1) return dirs def _tx_resource_for_name(name): """Return the Transifex resource name""" if name == "core": return "django.core" else: return "django.contrib-%s" % name def _check_diff(cat_name, base_path): """ Output the approximate number of changed/added strings in the en catalog. """ po_path = "%(path)s/en/LC_MESSAGES/django%(ext)s.po" % { "path": base_path, "ext": "js" if cat_name.endswith("-js") else "", } p = run( "git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path, capture_output=True, shell=True, ) num_changes = int(p.stdout.strip()) print("%d changed/added messages in '%s' catalog." % (num_changes, cat_name)) def update_catalogs(resources=None, languages=None): """ Update the en/LC_MESSAGES/django.po (main and contrib) files with new/updated translatable strings. """ settings.configure() django.setup() if resources is not None: print("`update_catalogs` will always process all resources.") contrib_dirs = _get_locale_dirs(None, include_core=False) os.chdir(os.path.join(os.getcwd(), "django")) print("Updating en catalogs for Django and contrib apps...") call_command("makemessages", locale=["en"]) print("Updating en JS catalogs for Django and contrib apps...") call_command("makemessages", locale=["en"], domain="djangojs") # Output changed stats _check_diff("core", os.path.join(os.getcwd(), "conf", "locale")) for name, dir_ in contrib_dirs: _check_diff(name, dir_) def lang_stats(resources=None, languages=None): """ Output language statistics of committed translation files for each Django catalog. If resources is provided, it should be a list of translation resource to limit the output (e.g. ['core', 'gis']). """ locale_dirs = _get_locale_dirs(resources) for name, dir_ in locale_dirs: print("\nShowing translations stats for '%s':" % name) langs = sorted(d for d in os.listdir(dir_) if not d.startswith("_")) for lang in langs: if languages and lang not in languages: continue # TODO: merge first with the latest en catalog po_path = "{path}/{lang}/LC_MESSAGES/django{ext}.po".format( path=dir_, lang=lang, ext="js" if name.endswith("-js") else "" ) p = run( ["msgfmt", "-vc", "-o", "/dev/null", po_path], capture_output=True, env={"LANG": "C"}, encoding="utf-8", ) if p.returncode == 0: # msgfmt output stats on stderr print("%s: %s" % (lang, p.stderr.strip())) else: print( "Errors happened when checking %s translation for %s:\n%s" % (lang, name, p.stderr) ) def fetch(resources=None, languages=None): """ Fetch translations from Transifex, wrap long lines, generate mo files. """ locale_dirs = _get_locale_dirs(resources) errors = [] for name, dir_ in locale_dirs: # Transifex pull if languages is None: run( [ "tx", "pull", "-r", _tx_resource_for_name(name), "-a", "-f", "--minimum-perc=5", ] ) target_langs = sorted( d for d in os.listdir(dir_) if not d.startswith("_") and d != "en" ) else: for lang in languages: run(["tx", "pull", "-r", _tx_resource_for_name(name), "-f", "-l", lang]) target_langs = languages # msgcat to wrap lines and msgfmt for compilation of .mo file for lang in target_langs: po_path = "%(path)s/%(lang)s/LC_MESSAGES/django%(ext)s.po" % { "path": dir_, "lang": lang, "ext": "js" if name.endswith("-js") else "", } if not os.path.exists(po_path): print( "No %(lang)s translation for resource %(name)s" % {"lang": lang, "name": name} ) continue run(["msgcat", "--no-location", "-o", po_path, po_path]) msgfmt = run(["msgfmt", "-c", "-o", "%s.mo" % po_path[:-3], po_path]) if msgfmt.returncode != 0: errors.append((name, lang)) if errors: print("\nWARNING: Errors have occurred in following cases:") for resource, lang in errors: print("\tResource %s for language %s" % (resource, lang)) exit(1) if __name__ == "__main__": RUNABLE_SCRIPTS = ("update_catalogs", "lang_stats", "fetch") parser = ArgumentParser() parser.add_argument("cmd", nargs=1, choices=RUNABLE_SCRIPTS) parser.add_argument( "-r", "--resources", action="append", help="limit operation to the specified resources", ) parser.add_argument( "-l", "--languages", action="append", help="limit operation to the specified languages", ) options = parser.parse_args() eval(options.cmd[0])(options.resources, options.languages)
5278aec4eab872905808dfaca4b914085118980d92497b28cde4bac4cd8bc7cc
""" This module collects helper functions and classes that "span" multiple levels of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ from django.http import ( Http404, HttpResponse, HttpResponsePermanentRedirect, HttpResponseRedirect, ) from django.template import loader from django.urls import NoReverseMatch, reverse from django.utils.functional import Promise def render( request, template_name, context=None, content_type=None, status=None, using=None ): """ Return an HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status) def redirect(to, *args, permanent=False, **kwargs): """ Return an HttpResponseRedirect to the appropriate URL for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the name. * A URL, which will be used as-is for the redirect location. Issues a temporary redirect by default; pass permanent=True to issue a permanent redirect. """ redirect_class = ( HttpResponsePermanentRedirect if permanent else HttpResponseRedirect ) return redirect_class(resolve_url(to, *args, **kwargs)) def _get_queryset(klass): """ Return a QuerySet or a Manager. Duck typing in action: any class with a `get()` method (for get_object_or_404) or a `filter()` method (for get_list_or_404) might do the job. """ # If it is a model class or anything else with ._default_manager if hasattr(klass, "_default_manager"): return klass._default_manager.all() return klass def get_object_or_404(klass, *args, **kwargs): """ Use get() to return an object, or raise an Http404 exception if the object does not exist. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Like with QuerySet.get(), MultipleObjectsReturned is raised if more than one object is found. """ queryset = _get_queryset(klass) if not hasattr(queryset, "get"): klass__name = ( klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ ) raise ValueError( "First argument to get_object_or_404() must be a Model, Manager, " "or QuerySet, not '%s'." % klass__name ) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: raise Http404( "No %s matches the given query." % queryset.model._meta.object_name ) def get_list_or_404(klass, *args, **kwargs): """ Use filter() to return a list of objects, or raise an Http404 exception if the list is empty. klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the filter() query. """ queryset = _get_queryset(klass) if not hasattr(queryset, "filter"): klass__name = ( klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ ) raise ValueError( "First argument to get_list_or_404() must be a Model, Manager, or " "QuerySet, not '%s'." % klass__name ) obj_list = list(queryset.filter(*args, **kwargs)) if not obj_list: raise Http404( "No %s matches the given query." % queryset.model._meta.object_name ) return obj_list def resolve_url(to, *args, **kwargs): """ Return a URL appropriate for the arguments passed. The arguments could be: * A model: the model's `get_absolute_url()` function will be called. * A view name, possibly with arguments: `urls.reverse()` will be used to reverse-resolve the name. * A URL, which will be returned as-is. """ # If it's a model, use get_absolute_url() if hasattr(to, "get_absolute_url"): return to.get_absolute_url() if isinstance(to, Promise): # Expand the lazy instance, as it can cause issues when it is passed # further to some Python functions like urlparse. to = str(to) # Handle relative URLs if isinstance(to, str) and to.startswith(("./", "../")): return to # Next try a reverse URL resolution. try: return reverse(to, args=args, kwargs=kwargs) except NoReverseMatch: # If this is a callable, re-raise. if callable(to): raise # If this doesn't "feel" like a URL, re-raise. if "/" not in to and "." not in to: raise # Finally, fall back and assume it's a URL return to
02a11ee25bfb5df0f8f217368c76a0555e73cb5043c1304a11357095f9ce6262
from django.utils.version import get_version VERSION = (4, 1, 0, "alpha", 0) __version__ = get_version(VERSION) def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( "/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) apps.populate(settings.INSTALLED_APPS)
26d466963f7e1c0d598927ce5f200bab948b2a7d95b3d0e276077968253940ad
#!/usr/bin/env python import argparse import atexit import copy import gc import os import shutil import socket import subprocess import sys import tempfile import warnings from pathlib import Path try: import django except ImportError as e: raise RuntimeError( "Django module not found, reference tests/README.rst for instructions." ) from e else: from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import connection, connections from django.test import TestCase, TransactionTestCase from django.test.runner import get_max_test_processes, parallel_type from django.test.selenium import SeleniumTestCaseBase from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner from django.utils.deprecation import RemovedInDjango50Warning from django.utils.log import DEFAULT_LOGGING try: import MySQLdb except ImportError: pass else: # Ignore informational warnings from QuerySet.explain(). warnings.filterwarnings("ignore", r"\(1003, *", category=MySQLdb.Warning) # Make deprecation warnings errors to ensure no usage of deprecated features. warnings.simplefilter("error", RemovedInDjango50Warning) # Make resource and runtime warning errors to ensure no usage of error prone # patterns. warnings.simplefilter("error", ResourceWarning) warnings.simplefilter("error", RuntimeWarning) # Ignore known warnings in test dependencies. warnings.filterwarnings( "ignore", "'U' mode is deprecated", DeprecationWarning, module="docutils.io" ) # Reduce garbage collection frequency to improve performance. Since CPython # uses refcounting, garbage collection only collects objects with cyclic # references, which are a minority, so the garbage collection threshold can be # larger than the default threshold of 700 allocations + deallocations without # much increase in memory usage. gc.set_threshold(100_000) RUNTESTS_DIR = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, "templates") # Create a specific subdirectory for the duration of the test suite. TMPDIR = tempfile.mkdtemp(prefix="django_") # Set the TMPDIR environment variable in addition to tempfile.tempdir # so that children processes inherit it. tempfile.tempdir = os.environ["TMPDIR"] = TMPDIR # Removing the temporary TMPDIR. atexit.register(shutil.rmtree, TMPDIR) # This is a dict mapping RUNTESTS_DIR subdirectory to subdirectories of that # directory to skip when searching for test modules. SUBDIRS_TO_SKIP = { "": {"import_error_package", "test_runner_apps"}, "gis_tests": {"data"}, } ALWAYS_INSTALLED_APPS = [ "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sites", "django.contrib.sessions", "django.contrib.messages", "django.contrib.admin.apps.SimpleAdminConfig", "django.contrib.staticfiles", ] ALWAYS_MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", ] # Need to add the associated contrib app to INSTALLED_APPS in some cases to # avoid "RuntimeError: Model class X doesn't declare an explicit app_label # and isn't in an application in INSTALLED_APPS." CONTRIB_TESTS_TO_APPS = { "deprecation": ["django.contrib.flatpages", "django.contrib.redirects"], "flatpages_tests": ["django.contrib.flatpages"], "redirects_tests": ["django.contrib.redirects"], } def get_test_modules(gis_enabled): """ Scan the tests directory and yield the names of all test modules. The yielded names have either one dotted part like "test_runner" or, in the case of GIS tests, two dotted parts like "gis_tests.gdal_tests". """ discovery_dirs = [""] if gis_enabled: # GIS tests are in nested apps discovery_dirs.append("gis_tests") else: SUBDIRS_TO_SKIP[""].add("gis_tests") for dirname in discovery_dirs: dirpath = os.path.join(RUNTESTS_DIR, dirname) subdirs_to_skip = SUBDIRS_TO_SKIP[dirname] with os.scandir(dirpath) as entries: for f in entries: if ( "." in f.name or os.path.basename(f.name) in subdirs_to_skip or f.is_file() or not os.path.exists(os.path.join(f.path, "__init__.py")) ): continue test_module = f.name if dirname: test_module = dirname + "." + test_module yield test_module def get_label_module(label): """Return the top-level module part for a test label.""" path = Path(label) if len(path.parts) == 1: # Interpret the label as a dotted module name. return label.split(".")[0] # Otherwise, interpret the label as a path. Check existence first to # provide a better error message than relative_to() if it doesn't exist. if not path.exists(): raise RuntimeError(f"Test label path {label} does not exist") path = path.resolve() rel_path = path.relative_to(RUNTESTS_DIR) return rel_path.parts[0] def get_filtered_test_modules(start_at, start_after, gis_enabled, test_labels=None): if test_labels is None: test_labels = [] # Reduce each test label to just the top-level module part. label_modules = set() for label in test_labels: test_module = get_label_module(label) label_modules.add(test_module) # It would be nice to put this validation earlier but it must come after # django.setup() so that connection.features.gis_enabled can be accessed. if "gis_tests" in label_modules and not gis_enabled: print("Aborting: A GIS database backend is required to run gis_tests.") sys.exit(1) def _module_match_label(module_name, label): # Exact or ancestor match. return module_name == label or module_name.startswith(label + ".") start_label = start_at or start_after for test_module in get_test_modules(gis_enabled): if start_label: if not _module_match_label(test_module, start_label): continue start_label = "" if not start_at: assert start_after # Skip the current one before starting. continue # If the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), include the test module. if not test_labels or any( _module_match_label(test_module, label_module) for label_module in label_modules ): yield test_module def setup_collect_tests(start_at, start_after, test_labels=None): state = { "INSTALLED_APPS": settings.INSTALLED_APPS, "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""), "TEMPLATES": settings.TEMPLATES, "LANGUAGE_CODE": settings.LANGUAGE_CODE, "STATIC_URL": settings.STATIC_URL, "STATIC_ROOT": settings.STATIC_ROOT, "MIDDLEWARE": settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = "urls" settings.STATIC_URL = "static/" settings.STATIC_ROOT = os.path.join(TMPDIR, "static") settings.TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [TEMPLATE_DIR], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ] settings.LANGUAGE_CODE = "en" settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. "auth": None, "contenttypes": None, "sessions": None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config["loggers"]["django"]["level"] = "ERROR" settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ "fields.W342", # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() # This flag must be evaluated after django.setup() because otherwise it can # raise AppRegistryNotReady when running gis_tests in isolation on some # backends (e.g. PostGIS). gis_enabled = connection.features.gis_enabled test_modules = list( get_filtered_test_modules( start_at, start_after, gis_enabled, test_labels=test_labels, ) ) return test_modules, state def teardown_collect_tests(state): # Restore the old settings. for key, value in state.items(): setattr(settings, key, value) def get_installed(): return [app_config.name for app_config in apps.get_app_configs()] # This function should be called only after calling django.setup(), # since it calls connection.features.gis_enabled. def get_apps_to_install(test_modules): for test_module in test_modules: if test_module in CONTRIB_TESTS_TO_APPS: yield from CONTRIB_TESTS_TO_APPS[test_module] yield test_module # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. if connection.features.gis_enabled: yield "django.contrib.gis" def setup_run_tests(verbosity, start_at, start_after, test_labels=None): test_modules, state = setup_collect_tests( start_at, start_after, test_labels=test_labels ) installed_apps = set(get_installed()) for app in get_apps_to_install(test_modules): if app in installed_apps: continue if verbosity >= 2: print(f"Importing application {app}") settings.INSTALLED_APPS.append(app) installed_apps.add(app) apps.set_installed_apps(settings.INSTALLED_APPS) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception( "Please define available_apps in TransactionTestCase and its subclasses." ) TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None # Set an environment variable that other code may consult to see if # Django's own test suite is running. os.environ["RUNNING_DJANGOS_TEST_SUITE"] = "true" test_labels = test_labels or test_modules return test_labels, state def teardown_run_tests(state): teardown_collect_tests(state) # Discard the multiprocessing.util finalizer that tries to remove a # temporary directory that's already removed by this script's # atexit.register(shutil.rmtree, TMPDIR) handler. Prevents # FileNotFoundError at the end of a test run (#27890). from multiprocessing.util import _finalizer_registry _finalizer_registry.pop((-100, 0), None) del os.environ["RUNNING_DJANGOS_TEST_SUITE"] class ActionSelenium(argparse.Action): """ Validate the comma-separated list of requested browsers. """ def __call__(self, parser, namespace, values, option_string=None): try: import selenium # NOQA except ImportError as e: raise ImproperlyConfigured(f"Error loading selenium module: {e}") browsers = values.split(",") for browser in browsers: try: SeleniumTestCaseBase.import_webdriver(browser) except ImportError: raise argparse.ArgumentError( self, "Selenium browser specification '%s' is not valid." % browser ) setattr(namespace, self.dest, browsers) def django_tests( verbosity, interactive, failfast, keepdb, reverse, test_labels, debug_sql, parallel, tags, exclude_tags, test_name_patterns, start_at, start_after, pdb, buffer, timing, shuffle, ): if parallel in {0, "auto"}: max_parallel = get_max_test_processes() else: max_parallel = parallel if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname( django.__file__ ) if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) test_labels, state = setup_run_tests(verbosity, start_at, start_after, test_labels) # Run the test suite, including the extra validation tests. if not hasattr(settings, "TEST_RUNNER"): settings.TEST_RUNNER = "django.test.runner.DiscoverRunner" if parallel in {0, "auto"}: # This doesn't work before django.setup() on some databases. if all(conn.features.can_clone_databases for conn in connections.all()): parallel = max_parallel else: parallel = 1 TestRunner = get_runner(settings) test_runner = TestRunner( verbosity=verbosity, interactive=interactive, failfast=failfast, keepdb=keepdb, reverse=reverse, debug_sql=debug_sql, parallel=parallel, tags=tags, exclude_tags=exclude_tags, test_name_patterns=test_name_patterns, pdb=pdb, buffer=buffer, timing=timing, shuffle=shuffle, ) failures = test_runner.run_tests(test_labels) teardown_run_tests(state) return failures def collect_test_modules(start_at, start_after): test_modules, state = setup_collect_tests(start_at, start_after) teardown_collect_tests(state) return test_modules def get_subprocess_args(options): subprocess_args = [sys.executable, __file__, "--settings=%s" % options.settings] if options.failfast: subprocess_args.append("--failfast") if options.verbosity: subprocess_args.append("--verbosity=%s" % options.verbosity) if not options.interactive: subprocess_args.append("--noinput") if options.tags: subprocess_args.append("--tag=%s" % options.tags) if options.exclude_tags: subprocess_args.append("--exclude_tag=%s" % options.exclude_tags) if options.shuffle is not False: if options.shuffle is None: subprocess_args.append("--shuffle") else: subprocess_args.append("--shuffle=%s" % options.shuffle) return subprocess_args def bisect_tests(bisection_label, options, test_labels, start_at, start_after): if not test_labels: test_labels = collect_test_modules(start_at, start_after) print("***** Bisecting test suite: %s" % " ".join(test_labels)) # Make sure the bisection point isn't in the test list # Also remove tests that need to be run in specific combinations for label in [bisection_label, "model_inheritance_same_model_name"]: try: test_labels.remove(label) except ValueError: pass subprocess_args = get_subprocess_args(options) iteration = 1 while len(test_labels) > 1: midpoint = len(test_labels) // 2 test_labels_a = test_labels[:midpoint] + [bisection_label] test_labels_b = test_labels[midpoint:] + [bisection_label] print("***** Pass %da: Running the first half of the test suite" % iteration) print("***** Test labels: %s" % " ".join(test_labels_a)) failures_a = subprocess.run(subprocess_args + test_labels_a) print("***** Pass %db: Running the second half of the test suite" % iteration) print("***** Test labels: %s" % " ".join(test_labels_b)) print("") failures_b = subprocess.run(subprocess_args + test_labels_b) if failures_a.returncode and not failures_b.returncode: print("***** Problem found in first half. Bisecting again...") iteration += 1 test_labels = test_labels_a[:-1] elif failures_b.returncode and not failures_a.returncode: print("***** Problem found in second half. Bisecting again...") iteration += 1 test_labels = test_labels_b[:-1] elif failures_a.returncode and failures_b.returncode: print("***** Multiple sources of failure found") break else: print("***** No source of failure found... try pair execution (--pair)") break if len(test_labels) == 1: print("***** Source of error: %s" % test_labels[0]) def paired_tests(paired_test, options, test_labels, start_at, start_after): if not test_labels: test_labels = collect_test_modules(start_at, start_after) print("***** Trying paired execution") # Make sure the constant member of the pair isn't in the test list # Also remove tests that need to be run in specific combinations for label in [paired_test, "model_inheritance_same_model_name"]: try: test_labels.remove(label) except ValueError: pass subprocess_args = get_subprocess_args(options) for i, label in enumerate(test_labels): print( "***** %d of %d: Check test pairing with %s" % (i + 1, len(test_labels), label) ) failures = subprocess.call(subprocess_args + [label, paired_test]) if failures: print("***** Found problem pair with %s" % label) return print("***** No problem pair found") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the Django test suite.") parser.add_argument( "modules", nargs="*", metavar="module", help='Optional path(s) to test modules; e.g. "i18n" or ' '"i18n.tests.TranslationTests.test_lazy_objects".', ) parser.add_argument( "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help="Verbosity level; 0=minimal output, 1=normal output, 2=all output", ) parser.add_argument( "--noinput", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--failfast", action="store_true", help="Tells Django to stop running the test suite after first failed test.", ) parser.add_argument( "--keepdb", action="store_true", help="Tells Django to preserve the test database between runs.", ) parser.add_argument( "--settings", help='Python path to settings module, e.g. "myproject.settings". If ' "this isn't provided, either the DJANGO_SETTINGS_MODULE " 'environment variable or "test_sqlite" will be used.', ) parser.add_argument( "--bisect", help="Bisect the test suite to discover a test that causes a test " "failure when combined with the named test.", ) parser.add_argument( "--pair", help="Run the test suite in pairs with the named test to find problem pairs.", ) parser.add_argument( "--shuffle", nargs="?", default=False, type=int, metavar="SEED", help=( "Shuffle the order of test cases to help check that tests are " "properly isolated." ), ) parser.add_argument( "--reverse", action="store_true", help="Sort test suites and test cases in opposite order to debug " "test side effects not apparent with normal execution lineup.", ) parser.add_argument( "--selenium", action=ActionSelenium, metavar="BROWSERS", help="A comma-separated list of browsers to run the Selenium tests against.", ) parser.add_argument( "--headless", action="store_true", help="Run selenium tests in headless mode, if the browser supports the option.", ) parser.add_argument( "--selenium-hub", help="A URL for a selenium hub instance to use in combination with --selenium.", ) parser.add_argument( "--external-host", default=socket.gethostname(), help=( "The external host that can be reached by the selenium hub instance when " "running Selenium tests via Selenium Hub." ), ) parser.add_argument( "--debug-sql", action="store_true", help="Turn on the SQL query logger within tests.", ) # 0 is converted to "auto" or 1 later on, depending on a method used by # multiprocessing to start subprocesses and on the backend support for # cloning databases. parser.add_argument( "--parallel", nargs="?", const="auto", default=0, type=parallel_type, metavar="N", help=( 'Run tests using up to N parallel processes. Use the value "auto" ' "to run one test process for each processor core." ), ) parser.add_argument( "--tag", dest="tags", action="append", help="Run only tests with the specified tags. Can be used multiple times.", ) parser.add_argument( "--exclude-tag", dest="exclude_tags", action="append", help="Do not run tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--start-after", dest="start_after", help="Run tests starting after the specified top-level module.", ) parser.add_argument( "--start-at", dest="start_at", help="Run tests starting at the specified top-level module.", ) parser.add_argument( "--pdb", action="store_true", help="Runs the PDB debugger on error or failure." ) parser.add_argument( "-b", "--buffer", action="store_true", help="Discard output of passing tests.", ) parser.add_argument( "--timing", action="store_true", help="Output timings, including database set up and total run time.", ) parser.add_argument( "-k", dest="test_name_patterns", action="append", help=( "Only run test methods and classes matching test name pattern. " "Same as unittest -k option. Can be used multiple times." ), ) options = parser.parse_args() using_selenium_hub = options.selenium and options.selenium_hub if options.selenium_hub and not options.selenium: parser.error( "--selenium-hub and --external-host require --selenium to be used." ) if using_selenium_hub and not options.external_host: parser.error("--selenium-hub and --external-host must be used together.") # Allow including a trailing slash on app_labels for tab completion convenience options.modules = [os.path.normpath(labels) for labels in options.modules] mutually_exclusive_options = [ options.start_at, options.start_after, options.modules, ] enabled_module_options = [ bool(option) for option in mutually_exclusive_options ].count(True) if enabled_module_options > 1: print( "Aborting: --start-at, --start-after, and test labels are mutually " "exclusive." ) sys.exit(1) for opt_name in ["start_at", "start_after"]: opt_val = getattr(options, opt_name) if opt_val: if "." in opt_val: print( "Aborting: --%s must be a top-level module." % opt_name.replace("_", "-") ) sys.exit(1) setattr(options, opt_name, os.path.normpath(opt_val)) if options.settings: os.environ["DJANGO_SETTINGS_MODULE"] = options.settings else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_sqlite") options.settings = os.environ["DJANGO_SETTINGS_MODULE"] if options.selenium: if not options.tags: options.tags = ["selenium"] elif "selenium" not in options.tags: options.tags.append("selenium") if options.selenium_hub: SeleniumTestCaseBase.selenium_hub = options.selenium_hub SeleniumTestCaseBase.external_host = options.external_host SeleniumTestCaseBase.headless = options.headless SeleniumTestCaseBase.browsers = options.selenium if options.bisect: bisect_tests( options.bisect, options, options.modules, options.start_at, options.start_after, ) elif options.pair: paired_tests( options.pair, options, options.modules, options.start_at, options.start_after, ) else: time_keeper = TimeKeeper() if options.timing else NullTimeKeeper() with time_keeper.timed("Total run"): failures = django_tests( options.verbosity, options.interactive, options.failfast, options.keepdb, options.reverse, options.modules, options.debug_sql, options.parallel, options.tags, options.exclude_tags, getattr(options, "test_name_patterns", None), options.start_at, options.start_after, options.pdb, options.buffer, options.timing, options.shuffle, ) time_keeper.print_results() if failures: sys.exit(1)
92bebe842941c4e76caf7d5a2510c321e108bff6d5b6d57cd92f14c457c461dd
# This is an example test settings file for use with the Django test suite. # # The 'sqlite3' backend requires only the ENGINE setting (an in- # memory database will be used). All other backends will require a # NAME and potentially authentication information. See the # following section in the docs for more information: # # https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/ # # The different databases that Django supports behave differently in certain # situations, so it is recommended to run the test suite against as many # database backends as possible. You may want to create a separate settings # file for each of the backends you test against. DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", }, "other": { "ENGINE": "django.db.backends.sqlite3", }, } SECRET_KEY = "django_tests_secret_key" # Use a fast hasher to speed up tests. PASSWORD_HASHERS = [ "django.contrib.auth.hashers.MD5PasswordHasher", ] DEFAULT_AUTO_FIELD = "django.db.models.AutoField" USE_TZ = False
904daa042a01af4ded9cb6f47ae32167b829ecdcaa969eccf8b1f16b02e05fbe
# Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys from os.path import abspath, dirname, join # Workaround for sphinx-build recursion limit overflow: # pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) # RuntimeError: maximum recursion depth exceeded while pickling an object # # Python's default allowed recursion depth is 1000 but this isn't enough for # building docs/ref/settings.txt sometimes. # https://groups.google.com/g/sphinx-dev/c/MtRf64eGtv4/discussion sys.setrecursionlimit(2000) # Make sure we get the version of this copy of Django sys.path.insert(1, dirname(dirname(abspath(__file__)))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(abspath(join(dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = "1.6.0" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "djangodocs", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.autosectionlabel", ] # AutosectionLabel settings. # Uses a <page>:<label> schema which doesn't work for duplicate sub-section # labels, so set max depth. autosectionlabel_prefix_document = True autosectionlabel_maxdepth = 2 # Linkcheck settings. linkcheck_ignore = [ # Special-use addresses and domain names. (RFC 6761/6890) r"^https?://(?:127\.0\.0\.1|\[::1\])(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*example\.(?:com|net|org)(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*(?:example|invalid|localhost|test)(?::\d+)?/", # Pages that are inaccessible because they require authentication. r"^https://github\.com/[^/]+/[^/]+/fork", r"^https://code\.djangoproject\.com/github/login", r"^https://code\.djangoproject\.com/newticket", r"^https://(?:code|www)\.djangoproject\.com/admin/", r"^https://www\.djangoproject\.com/community/add/blogs/", r"^https://www\.google\.com/webmasters/tools/ping", r"^https://search\.google\.com/search-console/welcome", # Fragments used to dynamically switch content or populate fields. r"^https://web\.libera\.chat/#", r"^https://github\.com/[^#]+#L\d+-L\d+$", r"^https://help\.apple\.com/itc/podcasts_connect/#/itc", # Anchors on certain pages with missing a[name] attributes. r"^https://tools\.ietf\.org/html/rfc1123\.html#section-", ] # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. if "spelling" in sys.argv: extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = "en_US" # Location of word list. spelling_word_list_filename = "spelling_wordlist" spelling_warning = True # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = ".txt" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "contents" # General substitutions. project = "Django" copyright = "Django Software Foundation and contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "4.1" # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version except ImportError: release = version else: def django_release(): pep440ver = get_version() if VERSION[3:5] == ("alpha", 0) and "dev" not in pep440ver: return pep440ver + ".dev" return pep440ver release = django_release() # The "development version" of Django django_next_version = "4.1" extlinks = { "bpo": ("https://bugs.python.org/issue%s", "bpo-"), "commit": ("https://github.com/django/django/commit/%s", ""), "cve": ("https://nvd.nist.gov/vuln/detail/CVE-%s", "CVE-"), # A file or directory. GitHub redirects from blob to tree if needed. "source": ("https://github.com/django/django/blob/main/%s", ""), "ticket": ("https://code.djangoproject.com/ticket/%s", "#"), } # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # Location for .po/.mo translation files used when language is set locale_dirs = ["locale/"] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = "%B %d, %Y" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "_theme", "requirements.txt"] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "default-role-error" # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "trac" # Links to Python's docs should reference the most recent version of the 3.x # branch, which is located at this URL. intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "sphinx": ("https://www.sphinx-doc.org/en/master/", None), "psycopg2": ("https://www.psycopg.org/docs/", None), } # Python's docs don't change every week. intersphinx_cache_limit = 90 # days # The 'versionadded' and 'versionchanged' directives are overridden. suppress_warnings = ["app.add_directive"] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%b %d, %Y" # Content template for the index page. # html_index = '' # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Djangodoc" modindex_common_prefix = ["django."] # Appended to every page rst_epilog = """ .. |django-users| replace:: :ref:`django-users <django-users-mailing-list>` .. |django-developers| replace:: :ref:`django-developers <django-developers-mailing-list>` .. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>` .. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>` """ # NOQA # -- Options for LaTeX output -------------------------------------------------- # Use XeLaTeX for Unicode support. latex_engine = "xelatex" latex_use_xindy = False # Set font for CJK and fallbacks for unicode characters. latex_elements = { "fontpkg": r""" \setmainfont{Symbola} """, "preamble": r""" \usepackage{newunicodechar} \usepackage[UTF8]{ctex} \newunicodechar{π}{\ensuremath{\pi}} \newunicodechar{≤}{\ensuremath{\le}} \newunicodechar{≥}{\ensuremath{\ge}} \newunicodechar{♥}{\ensuremath{\heartsuit}} \newunicodechar{…}{\ensuremath{\ldots}} """, } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). # latex_documents = [] latex_documents = [ ( "contents", "django.tex", "Django Documentation", "Django Software Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "ref/django-admin", "django-admin", "Utility script for the Django web framework", ["Django Software Foundation"], 1, ) ] # -- Options for Texinfo output ------------------------------------------------ # List of tuples (startdocname, targetname, title, author, dir_entry, # description, category, toctree_only) texinfo_documents = [ ( master_doc, "django", "", "", "Django", "Documentation of the Django framework", "Web development", False, ) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = "Django Software Foundation" epub_publisher = "Django Software Foundation" epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = 'Django' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. epub_theme = "djangodocs-epub" # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be an ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. epub_cover = ("", "epub-cover.html") # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the PIL. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True
84c3cc6150c2910b947d8d43dd75723f60aa4900e1107320a76e5af91cad4ccb
import logging import threading import weakref from django.utils.inspect import func_accepts_kwargs logger = logging.getLogger("django.dispatch") def _make_id(target): if hasattr(target, "__func__"): return (id(target.__self__), id(target.__func__)) return id(target) NONE_ID = _make_id(None) # A marker for caching NO_RECEIVERS = object() class Signal: """ Base class for all signals Internal attributes: receivers { receiverkey (id) : weakref(receiver) } """ def __init__(self, use_caching=False): """ Create a new signal. """ self.receivers = [] self.lock = threading.Lock() self.use_caching = use_caching # For convenience we create empty caches even if they are not used. # A note about caching: if use_caching is defined, then for each # distinct sender we cache the receivers that sender has in # 'sender_receivers_cache'. The cache is cleaned when .connect() or # .disconnect() is called and populated on send(). self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {} self._dead_receivers = False def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. If weak is True, then receiver must be weak referenceable. Receivers must be able to accept keyword arguments. If a receiver is connected with a dispatch_uid argument, it will not be added if another receiver was already connected with that dispatch_uid. sender The sender to which the receiver should respond. Must either be a Python object, or None to receive events from any sender. weak Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. """ from django.conf import settings # If DEBUG is on, check that we got a good receiver if settings.configured and settings.DEBUG: if not callable(receiver): raise TypeError("Signal receivers must be callable.") # Check for **kwargs if not func_accepts_kwargs(receiver): raise ValueError( "Signal receivers must accept keyword arguments (**kwargs)." ) if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) if weak: ref = weakref.ref receiver_object = receiver # Check for bound methods if hasattr(receiver, "__self__") and hasattr(receiver, "__func__"): ref = weakref.WeakMethod receiver_object = receiver.__self__ receiver = ref(receiver) weakref.finalize(receiver_object, self._remove_receiver) with self.lock: self._clear_dead_receivers() if not any(r_key == lookup_key for r_key, _ in self.receivers): self.receivers.append((lookup_key, receiver)) self.sender_receivers_cache.clear() def disconnect(self, receiver=None, sender=None, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be removed from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid is specified. sender The registered sender to disconnect dispatch_uid the unique identifier of the receiver to disconnect """ if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): (r_key, _) = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender_receivers_cache.clear() return disconnected def has_listeners(self, sender=None): return bool(self._live_receivers(sender)) def send(self, sender, **named): """ Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. Arguments: sender The sender of the signal. Either a specific object or None. named Named arguments which will be passed to receivers. Return a list of tuple pairs [(receiver, response), ... ]. """ if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] return [ (receiver, receiver(signal=self, sender=sender, **named)) for receiver in self._live_receivers(sender) ] def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. Arguments: sender The sender of the signal. Can be any Python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. Return a list of tuple pairs [(receiver, response), ... ]. If any receiver raises an error (specifically any subclass of Exception), return the error instance as the result for that receiver. """ if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. responses = [] for receiver in self._live_receivers(sender): try: response = receiver(signal=self, sender=sender, **named) except Exception as err: logger.error( "Error calling %s in Signal.send_robust() (%s)", receiver.__qualname__, err, exc_info=err, ) responses.append((receiver, err)) else: responses.append((receiver, response)) return responses def _clear_dead_receivers(self): # Note: caller is assumed to hold self.lock. if self._dead_receivers: self._dead_receivers = False self.receivers = [ r for r in self.receivers if not (isinstance(r[1], weakref.ReferenceType) and r[1]() is None) ] def _live_receivers(self, sender): """ Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers. """ receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this case in # .send() prior to calling _live_receivers() due to concurrent .send() call. if receivers is NO_RECEIVERS: return [] if receivers is None: with self.lock: self._clear_dead_receivers() senderkey = _make_id(sender) receivers = [] for (receiverkey, r_senderkey), receiver in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append(receiver) if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: # Note, we must cache the weakref versions. self.sender_receivers_cache[sender] = receivers non_weak_receivers = [] for receiver in receivers: if isinstance(receiver, weakref.ReferenceType): # Dereference the weak reference. receiver = receiver() if receiver is not None: non_weak_receivers.append(receiver) else: non_weak_receivers.append(receiver) return non_weak_receivers def _remove_receiver(self, receiver=None): # Mark that the self.receivers list has dead weakrefs. If so, we will # clean those up in connect, disconnect and _live_receivers while # holding self.lock. Note that doing the cleanup here isn't a good # idea, _remove_receiver() will be called as side effect of garbage # collection, and so the call can happen while we are already holding # self.lock. self._dead_receivers = True def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal (or list of signals) and keyword arguments to connect:: @receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): ... @receiver([post_save, post_delete], sender=MyModel) def signals_receiver(sender, **kwargs): ... """ def _decorator(func): if isinstance(signal, (list, tuple)): for s in signal: s.connect(func, **kwargs) else: signal.connect(func, **kwargs) return func return _decorator
d093f3a61f25ca4d62f6d6830a0b0ebcb864c5287e8d1fa0bcce293e17531b37
import sys import unittest from contextlib import contextmanager from django.test import LiveServerTestCase, tag from django.utils.functional import classproperty from django.utils.module_loading import import_string from django.utils.text import capfirst class SeleniumTestCaseBase(type(LiveServerTestCase)): # List of browsers to dynamically create test classes for. browsers = [] # A selenium hub URL to test against. selenium_hub = None # The external host Selenium Hub can reach. external_host = None # Sentinel value to differentiate browser-specific instances. browser = None # Run browsers in headless mode. headless = False def __new__(cls, name, bases, attrs): """ Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome). """ test_class = super().__new__(cls, name, bases, attrs) # If the test class is either browser-specific or a test base, return it. if test_class.browser or not any( name.startswith("test") and callable(value) for name, value in attrs.items() ): return test_class elif test_class.browsers: # Reuse the created test class to make it browser-specific. # We can't rename it to include the browser name or create a # subclass like we do with the remaining browsers as it would # either duplicate tests or prevent pickling of its instances. first_browser = test_class.browsers[0] test_class.browser = first_browser # Listen on an external interface if using a selenium hub. host = test_class.host if not test_class.selenium_hub else "0.0.0.0" test_class.host = host test_class.external_host = cls.external_host # Create subclasses for each of the remaining browsers and expose # them through the test's module namespace. module = sys.modules[test_class.__module__] for browser in test_class.browsers[1:]: browser_test_class = cls.__new__( cls, "%s%s" % (capfirst(browser), name), (test_class,), { "browser": browser, "host": host, "external_host": cls.external_host, "__module__": test_class.__module__, }, ) setattr(module, browser_test_class.__name__, browser_test_class) return test_class # If no browsers were specified, skip this class (it'll still be discovered). return unittest.skip("No browsers specified.")(test_class) @classmethod def import_webdriver(cls, browser): return import_string("selenium.webdriver.%s.webdriver.WebDriver" % browser) @classmethod def import_options(cls, browser): return import_string("selenium.webdriver.%s.options.Options" % browser) @classmethod def get_capability(cls, browser): from selenium.webdriver.common.desired_capabilities import DesiredCapabilities return getattr(DesiredCapabilities, browser.upper()) def create_options(self): options = self.import_options(self.browser)() if self.headless: try: options.headless = True except AttributeError: pass # Only Chrome and Firefox support the headless mode. return options def create_webdriver(self): if self.selenium_hub: from selenium import webdriver return webdriver.Remote( command_executor=self.selenium_hub, desired_capabilities=self.get_capability(self.browser), ) return self.import_webdriver(self.browser)(options=self.create_options()) @tag("selenium") class SeleniumTestCase(LiveServerTestCase, metaclass=SeleniumTestCaseBase): implicit_wait = 10 external_host = None @classproperty def live_server_url(cls): return "http://%s:%s" % (cls.external_host or cls.host, cls.server_thread.port) @classproperty def allowed_host(cls): return cls.external_host or cls.host @classmethod def setUpClass(cls): cls.selenium = cls.create_webdriver() cls.selenium.implicitly_wait(cls.implicit_wait) super().setUpClass() @classmethod def _tearDownClassInternal(cls): # quit() the WebDriver before attempting to terminate and join the # single-threaded LiveServerThread to avoid a dead lock if the browser # kept a connection alive. if hasattr(cls, "selenium"): cls.selenium.quit() super()._tearDownClassInternal() @contextmanager def disable_implicit_wait(self): """Disable the default implicit wait.""" self.selenium.implicitly_wait(0) try: yield finally: self.selenium.implicitly_wait(self.implicit_wait)
5f5d82f7c94a379256d7ec26b3b07a39a313a3e2e2f74c1a4298df244d55dc01
"""Django Unit Test framework.""" from django.test.client import AsyncClient, AsyncRequestFactory, Client, RequestFactory from django.test.testcases import ( LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature, ) from django.test.utils import ( ignore_warnings, modify_settings, override_settings, override_system_checks, tag, ) __all__ = [ "AsyncClient", "AsyncRequestFactory", "Client", "RequestFactory", "TestCase", "TransactionTestCase", "SimpleTestCase", "LiveServerTestCase", "skipIfDBFeature", "skipUnlessAnyDBFeature", "skipUnlessDBFeature", "ignore_warnings", "modify_settings", "override_settings", "override_system_checks", "tag", ]
ea67f40156fcb10616304e0095957bb672378f7be4f367bbadee869e2bd38a44
import argparse import ctypes import faulthandler import io import itertools import logging import multiprocessing import os import pickle import random import sys import textwrap import unittest import warnings from collections import defaultdict from contextlib import contextmanager from importlib import import_module from io import StringIO from django.core.management import call_command from django.db import connections from django.test import SimpleTestCase, TestCase from django.test.utils import NullTimeKeeper, TimeKeeper, iter_test_cases from django.test.utils import setup_databases as _setup_databases from django.test.utils import setup_test_environment from django.test.utils import teardown_databases as _teardown_databases from django.test.utils import teardown_test_environment from django.utils.crypto import new_hash from django.utils.datastructures import OrderedSet from django.utils.deprecation import RemovedInDjango50Warning try: import ipdb as pdb except ImportError: import pdb try: import tblib.pickling_support except ImportError: tblib = None class DebugSQLTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger("django.db.backends") self.logger.setLevel(logging.DEBUG) self.debug_sql_stream = None super().__init__(stream, descriptions, verbosity) def startTest(self, test): self.debug_sql_stream = StringIO() self.handler = logging.StreamHandler(self.debug_sql_stream) self.logger.addHandler(self.handler) super().startTest(test) def stopTest(self, test): super().stopTest(test) self.logger.removeHandler(self.handler) if self.showAll: self.debug_sql_stream.seek(0) self.stream.write(self.debug_sql_stream.read()) self.stream.writeln(self.separator2) def addError(self, test, err): super().addError(test, err) if self.debug_sql_stream is None: # Error before tests e.g. in setUpTestData(). sql = "" else: self.debug_sql_stream.seek(0) sql = self.debug_sql_stream.read() self.errors[-1] = self.errors[-1] + (sql,) def addFailure(self, test, err): super().addFailure(test, err) self.debug_sql_stream.seek(0) self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),) def addSubTest(self, test, subtest, err): super().addSubTest(test, subtest, err) if err is not None: self.debug_sql_stream.seek(0) errors = ( self.failures if issubclass(err[0], test.failureException) else self.errors ) errors[-1] = errors[-1] + (self.debug_sql_stream.read(),) def printErrorList(self, flavour, errors): for test, err, sql_debug in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour, self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln(err) self.stream.writeln(self.separator2) self.stream.writeln(sql_debug) class PDBDebugResult(unittest.TextTestResult): """ Custom result class that triggers a PDB session when an error or failure occurs. """ def addError(self, test, err): super().addError(test, err) self.debug(err) def addFailure(self, test, err): super().addFailure(test, err) self.debug(err) def addSubTest(self, test, subtest, err): if err is not None: self.debug(err) super().addSubTest(test, subtest, err) def debug(self, error): self._restoreStdout() self.buffer = False exc_type, exc_value, traceback = error print("\nOpening PDB: %r" % exc_value) pdb.post_mortem(traceback) class DummyList: """ Dummy list class for faking storage of results in unittest.TestResult. """ __slots__ = () def append(self, item): pass class RemoteTestResult(unittest.TestResult): """ Extend unittest.TestResult to record events in the child processes so they can be replayed in the parent process. Events include things like which tests succeeded or failed. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Fake storage of results to reduce memory usage. These are used by the # unittest default methods, but here 'events' is used instead. dummy_list = DummyList() self.failures = dummy_list self.errors = dummy_list self.skipped = dummy_list self.expectedFailures = dummy_list self.unexpectedSuccesses = dummy_list if tblib is not None: tblib.pickling_support.install() self.events = [] def __getstate__(self): # Make this class picklable by removing the file-like buffer # attributes. This is possible since they aren't used after unpickling # after being sent to ParallelTestSuite. state = self.__dict__.copy() state.pop("_stdout_buffer", None) state.pop("_stderr_buffer", None) state.pop("_original_stdout", None) state.pop("_original_stderr", None) return state @property def test_index(self): return self.testsRun - 1 def _confirm_picklable(self, obj): """ Confirm that obj can be pickled and unpickled as multiprocessing will need to pickle the exception in the child process and unpickle it in the parent process. Let the exception rise, if not. """ pickle.loads(pickle.dumps(obj)) def _print_unpicklable_subtest(self, test, subtest, pickle_exc): print( """ Subtest failed: test: {} subtest: {} Unfortunately, the subtest that failed cannot be pickled, so the parallel test runner cannot handle it cleanly. Here is the pickling error: > {} You should re-run this test with --parallel=1 to reproduce the failure with a cleaner failure message. """.format( test, subtest, pickle_exc ) ) def check_picklable(self, test, err): # Ensure that sys.exc_info() tuples are picklable. This displays a # clear multiprocessing.pool.RemoteTraceback generated in the child # process instead of a multiprocessing.pool.MaybeEncodingError, making # the root cause easier to figure out for users who aren't familiar # with the multiprocessing module. Since we're in a forked process, # our best chance to communicate with them is to print to stdout. try: self._confirm_picklable(err) except Exception as exc: original_exc_txt = repr(err[1]) original_exc_txt = textwrap.fill( original_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) pickle_exc_txt = repr(exc) pickle_exc_txt = textwrap.fill( pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) if tblib is None: print( """ {} failed: {} Unfortunately, tracebacks cannot be pickled, making it impossible for the parallel test runner to handle this exception cleanly. In order to see the traceback, you should install tblib: python -m pip install tblib """.format( test, original_exc_txt ) ) else: print( """ {} failed: {} Unfortunately, the exception it raised cannot be pickled, making it impossible for the parallel test runner to handle it cleanly. Here's the error encountered while trying to pickle the exception: {} You should re-run this test with the --parallel=1 option to reproduce the failure and get a correct traceback. """.format( test, original_exc_txt, pickle_exc_txt ) ) raise def check_subtest_picklable(self, test, subtest): try: self._confirm_picklable(subtest) except Exception as exc: self._print_unpicklable_subtest(test, subtest, exc) raise def startTestRun(self): super().startTestRun() self.events.append(("startTestRun",)) def stopTestRun(self): super().stopTestRun() self.events.append(("stopTestRun",)) def startTest(self, test): super().startTest(test) self.events.append(("startTest", self.test_index)) def stopTest(self, test): super().stopTest(test) self.events.append(("stopTest", self.test_index)) def addError(self, test, err): self.check_picklable(test, err) self.events.append(("addError", self.test_index, err)) super().addError(test, err) def addFailure(self, test, err): self.check_picklable(test, err) self.events.append(("addFailure", self.test_index, err)) super().addFailure(test, err) def addSubTest(self, test, subtest, err): # Follow Python's implementation of unittest.TestResult.addSubTest() by # not doing anything when a subtest is successful. if err is not None: # Call check_picklable() before check_subtest_picklable() since # check_picklable() performs the tblib check. self.check_picklable(test, err) self.check_subtest_picklable(test, subtest) self.events.append(("addSubTest", self.test_index, subtest, err)) super().addSubTest(test, subtest, err) def addSuccess(self, test): self.events.append(("addSuccess", self.test_index)) super().addSuccess(test) def addSkip(self, test, reason): self.events.append(("addSkip", self.test_index, reason)) super().addSkip(test, reason) def addExpectedFailure(self, test, err): # If tblib isn't installed, pickling the traceback will always fail. # However we don't want tblib to be required for running the tests # when they pass or fail as expected. Drop the traceback when an # expected failure occurs. if tblib is None: err = err[0], err[1], None self.check_picklable(test, err) self.events.append(("addExpectedFailure", self.test_index, err)) super().addExpectedFailure(test, err) def addUnexpectedSuccess(self, test): self.events.append(("addUnexpectedSuccess", self.test_index)) super().addUnexpectedSuccess(test) def wasSuccessful(self): """Tells whether or not this result was a success.""" failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"} return all(e[0] not in failure_types for e in self.events) def _exc_info_to_string(self, err, test): # Make this method no-op. It only powers the default unittest behavior # for recording errors, but this class pickles errors into 'events' # instead. return "" class RemoteTestRunner: """ Run tests and record everything but don't display anything. The implementation matches the unpythonic coding style of unittest2. """ resultclass = RemoteTestResult def __init__(self, failfast=False, resultclass=None, buffer=False): self.failfast = failfast self.buffer = buffer if resultclass is not None: self.resultclass = resultclass def run(self, test): result = self.resultclass() unittest.registerResult(result) result.failfast = self.failfast result.buffer = self.buffer test(result) return result def get_max_test_processes(): """ The maximum number of test processes when using the --parallel option. """ # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork(). if multiprocessing.get_start_method() != "fork": return 1 try: return int(os.environ["DJANGO_TEST_PROCESSES"]) except KeyError: return multiprocessing.cpu_count() def parallel_type(value): """Parse value passed to the --parallel option.""" if value == "auto": return value try: return int(value) except ValueError: raise argparse.ArgumentTypeError( f"{value!r} is not an integer or the string 'auto'" ) _worker_id = 0 def _init_worker(counter): """ Switch to databases dedicated to this worker. This helper lives at module-level because of the multiprocessing module's requirements. """ global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter.value for alias in connections: connection = connections[alias] connection.creation.setup_worker_connection(_worker_id) def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast, buffer = args runner = runner_class(failfast=failfast, buffer=buffer) result = runner.run(subsuite) return subsuite_index, result.events class ParallelTestSuite(unittest.TestSuite): """ Run a series of tests in parallel in several processes. While the unittest module's documentation implies that orchestrating the execution of tests is the responsibility of the test runner, in practice, it appears that TestRunner classes are more concerned with formatting and displaying test results. Since there are fewer use cases for customizing TestSuite than TestRunner, implementing parallelization at the level of the TestSuite improves interoperability with existing custom test runners. A single instance of a test runner can still collect results from all tests without being aware that they have been run in parallel. """ # In case someone wants to modify these in a subclass. init_worker = _init_worker run_subsuite = _run_subsuite runner_class = RemoteTestRunner def __init__(self, subsuites, processes, failfast=False, buffer=False): self.subsuites = subsuites self.processes = processes self.failfast = failfast self.buffer = buffer super().__init__() def run(self, result): """ Distribute test cases across workers. Return an identifier of each test case with its result in order to use imap_unordered to show results as soon as they're available. To minimize pickling errors when getting results from workers: - pass back numeric indexes in self.subsuites instead of tests - make tracebacks picklable with tblib, if available Even with tblib, errors may still occur for dynamically created exception classes which cannot be unpickled. """ counter = multiprocessing.Value(ctypes.c_int, 0) pool = multiprocessing.Pool( processes=self.processes, initializer=self.init_worker.__func__, initargs=[counter], ) args = [ (self.runner_class, index, subsuite, self.failfast, self.buffer) for index, subsuite in enumerate(self.subsuites) ] test_results = pool.imap_unordered(self.run_subsuite.__func__, args) while True: if result.shouldStop: pool.terminate() break try: subsuite_index, events = test_results.next(timeout=0.1) except multiprocessing.TimeoutError: continue except StopIteration: pool.close() break tests = list(self.subsuites[subsuite_index]) for event in events: event_name = event[0] handler = getattr(result, event_name, None) if handler is None: continue test = tests[event[1]] args = event[2:] handler(test, *args) pool.join() return result def __iter__(self): return iter(self.subsuites) class Shuffler: """ This class implements shuffling with a special consistency property. Consistency means that, for a given seed and key function, if two sets of items are shuffled, the resulting order will agree on the intersection of the two sets. For example, if items are removed from an original set, the shuffled order for the new set will be the shuffled order of the original set restricted to the smaller set. """ # This doesn't need to be cryptographically strong, so use what's fastest. hash_algorithm = "md5" @classmethod def _hash_text(cls, text): h = new_hash(cls.hash_algorithm, usedforsecurity=False) h.update(text.encode("utf-8")) return h.hexdigest() def __init__(self, seed=None): if seed is None: # Limit seeds to 10 digits for simpler output. seed = random.randint(0, 10**10 - 1) seed_source = "generated" else: seed_source = "given" self.seed = seed self.seed_source = seed_source @property def seed_display(self): return f"{self.seed!r} ({self.seed_source})" def _hash_item(self, item, key): text = "{}{}".format(self.seed, key(item)) return self._hash_text(text) def shuffle(self, items, key): """ Return a new list of the items in a shuffled order. The `key` is a function that accepts an item in `items` and returns a string unique for that item that can be viewed as a string id. The order of the return value is deterministic. It depends on the seed and key function but not on the original order. """ hashes = {} for item in items: hashed = self._hash_item(item, key) if hashed in hashes: msg = "item {!r} has same hash {!r} as item {!r}".format( item, hashed, hashes[hashed], ) raise RuntimeError(msg) hashes[hashed] = item return [hashes[hashed] for hashed in sorted(hashes)] class DiscoverRunner: """A Django test runner that uses unittest2 test discovery.""" test_suite = unittest.TestSuite parallel_test_suite = ParallelTestSuite test_runner = unittest.TextTestRunner test_loader = unittest.defaultTestLoader reorder_by = (TestCase, SimpleTestCase) def __init__( self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, test_name_patterns=None, pdb=False, buffer=False, enable_faulthandler=True, timing=False, shuffle=False, logger=None, **kwargs, ): self.pattern = pattern self.top_level = top_level self.verbosity = verbosity self.interactive = interactive self.failfast = failfast self.keepdb = keepdb self.reverse = reverse self.debug_mode = debug_mode self.debug_sql = debug_sql self.parallel = parallel self.tags = set(tags or []) self.exclude_tags = set(exclude_tags or []) if not faulthandler.is_enabled() and enable_faulthandler: try: faulthandler.enable(file=sys.stderr.fileno()) except (AttributeError, io.UnsupportedOperation): faulthandler.enable(file=sys.__stderr__.fileno()) self.pdb = pdb if self.pdb and self.parallel > 1: raise ValueError( "You cannot use --pdb with parallel tests; pass --parallel=1 to use it." ) self.buffer = buffer self.test_name_patterns = None self.time_keeper = TimeKeeper() if timing else NullTimeKeeper() if test_name_patterns: # unittest does not export the _convert_select_pattern function # that converts command-line arguments to patterns. self.test_name_patterns = { pattern if "*" in pattern else "*%s*" % pattern for pattern in test_name_patterns } self.shuffle = shuffle self._shuffler = None self.logger = logger @classmethod def add_arguments(cls, parser): parser.add_argument( "-t", "--top-level-directory", dest="top_level", help="Top level of project for unittest discovery.", ) parser.add_argument( "-p", "--pattern", default="test*.py", help="The test matching pattern. Defaults to test*.py.", ) parser.add_argument( "--keepdb", action="store_true", help="Preserves the test DB between runs." ) parser.add_argument( "--shuffle", nargs="?", default=False, type=int, metavar="SEED", help="Shuffles test case order.", ) parser.add_argument( "-r", "--reverse", action="store_true", help="Reverses test case order.", ) parser.add_argument( "--debug-mode", action="store_true", help="Sets settings.DEBUG to True.", ) parser.add_argument( "-d", "--debug-sql", action="store_true", help="Prints logged SQL queries on failure.", ) parser.add_argument( "--parallel", nargs="?", const="auto", default=0, type=parallel_type, metavar="N", help=( "Run tests using up to N parallel processes. Use the value " '"auto" to run one test process for each processor core.' ), ) parser.add_argument( "--tag", action="append", dest="tags", help="Run only tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--exclude-tag", action="append", dest="exclude_tags", help="Do not run tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--pdb", action="store_true", help="Runs a debugger (pdb, or ipdb if installed) on error or failure.", ) parser.add_argument( "-b", "--buffer", action="store_true", help="Discard output from passing tests.", ) parser.add_argument( "--no-faulthandler", action="store_false", dest="enable_faulthandler", help="Disables the Python faulthandler module during tests.", ) parser.add_argument( "--timing", action="store_true", help=("Output timings, including database set up and total run time."), ) parser.add_argument( "-k", action="append", dest="test_name_patterns", help=( "Only run test methods and classes that match the pattern " "or substring. Can be used multiple times. Same as " "unittest -k option." ), ) @property def shuffle_seed(self): if self._shuffler is None: return None return self._shuffler.seed def log(self, msg, level=None): """ Log the message at the given logging level (the default is INFO). If a logger isn't set, the message is instead printed to the console, respecting the configured verbosity. A verbosity of 0 prints no output, a verbosity of 1 prints INFO and above, and a verbosity of 2 or higher prints all levels. """ if level is None: level = logging.INFO if self.logger is None: if self.verbosity <= 0 or (self.verbosity == 1 and level < logging.INFO): return print(msg) else: self.logger.log(level, msg) def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler() def setup_shuffler(self): if self.shuffle is False: return shuffler = Shuffler(seed=self.shuffle) self.log(f"Using shuffle seed: {shuffler.seed_display}") self._shuffler = shuffler @contextmanager def load_with_patterns(self): original_test_name_patterns = self.test_loader.testNamePatterns self.test_loader.testNamePatterns = self.test_name_patterns try: yield finally: # Restore the original patterns. self.test_loader.testNamePatterns = original_test_name_patterns def load_tests_for_label(self, label, discover_kwargs): label_as_path = os.path.abspath(label) tests = None # If a module, or "module.ClassName[.method_name]", just run those. if not os.path.exists(label_as_path): with self.load_with_patterns(): tests = self.test_loader.loadTestsFromName(label) if tests.countTestCases(): return tests # Try discovery if "label" is a package or directory. is_importable, is_package = try_importing(label) if is_importable: if not is_package: return tests elif not os.path.isdir(label_as_path): if os.path.exists(label_as_path): assert tests is None raise RuntimeError( f"One of the test labels is a path to a file: {label!r}, " f"which is not supported. Use a dotted module name or " f"path to a directory instead." ) return tests kwargs = discover_kwargs.copy() if os.path.isdir(label_as_path) and not self.top_level: kwargs["top_level_dir"] = find_top_level(label_as_path) with self.load_with_patterns(): tests = self.test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from this run, # to support running tests from two different top-levels. self.test_loader._top_level_dir = None return tests def build_suite(self, test_labels=None, extra_tests=None, **kwargs): if extra_tests is not None: warnings.warn( "The extra_tests argument is deprecated.", RemovedInDjango50Warning, stacklevel=2, ) test_labels = test_labels or ["."] extra_tests = extra_tests or [] discover_kwargs = {} if self.pattern is not None: discover_kwargs["pattern"] = self.pattern if self.top_level is not None: discover_kwargs["top_level_dir"] = self.top_level self.setup_shuffler() all_tests = [] for label in test_labels: tests = self.load_tests_for_label(label, discover_kwargs) all_tests.extend(iter_test_cases(tests)) all_tests.extend(iter_test_cases(extra_tests)) if self.tags or self.exclude_tags: if self.tags: self.log( "Including test tag(s): %s." % ", ".join(sorted(self.tags)), level=logging.DEBUG, ) if self.exclude_tags: self.log( "Excluding test tag(s): %s." % ", ".join(sorted(self.exclude_tags)), level=logging.DEBUG, ) all_tests = filter_tests_by_tags(all_tests, self.tags, self.exclude_tags) # Put the failures detected at load time first for quicker feedback. # _FailedTest objects include things like test modules that couldn't be # found or that couldn't be loaded due to syntax errors. test_types = (unittest.loader._FailedTest, *self.reorder_by) all_tests = list( reorder_tests( all_tests, test_types, shuffler=self._shuffler, reverse=self.reverse, ) ) self.log("Found %d test(s)." % len(all_tests)) suite = self.test_suite(all_tests) if self.parallel > 1: subsuites = partition_suite_by_case(suite) # Since tests are distributed across processes on a per-TestCase # basis, there's no need for more processes than TestCases. processes = min(self.parallel, len(subsuites)) # Update also "parallel" because it's used to determine the number # of test databases. self.parallel = processes if processes > 1: suite = self.parallel_test_suite( subsuites, processes, self.failfast, self.buffer, ) return suite def setup_databases(self, **kwargs): return _setup_databases( self.verbosity, self.interactive, time_keeper=self.time_keeper, keepdb=self.keepdb, debug_sql=self.debug_sql, parallel=self.parallel, **kwargs, ) def get_resultclass(self): if self.debug_sql: return DebugSQLTextTestResult elif self.pdb: return PDBDebugResult def get_test_runner_kwargs(self): return { "failfast": self.failfast, "resultclass": self.get_resultclass(), "verbosity": self.verbosity, "buffer": self.buffer, } def run_checks(self, databases): # Checks are run after database creation since some checks require # database access. call_command("check", verbosity=self.verbosity, databases=databases) def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) try: return runner.run(suite) finally: if self._shuffler is not None: seed_display = self._shuffler.seed_display self.log(f"Used shuffle seed: {seed_display}") def teardown_databases(self, old_config, **kwargs): """Destroy all the non-mirror databases.""" _teardown_databases( old_config, verbosity=self.verbosity, parallel=self.parallel, keepdb=self.keepdb, ) def teardown_test_environment(self, **kwargs): unittest.removeHandler() teardown_test_environment() def suite_result(self, suite, result, **kwargs): return ( len(result.failures) + len(result.errors) + len(result.unexpectedSuccesses) ) def _get_databases(self, suite): databases = {} for test in iter_test_cases(suite): test_databases = getattr(test, "databases", None) if test_databases == "__all__": test_databases = connections if test_databases: serialized_rollback = getattr(test, "serialized_rollback", False) databases.update( (alias, serialized_rollback or databases.get(alias, False)) for alias in test_databases ) return databases def get_databases(self, suite): databases = self._get_databases(suite) unused_databases = [alias for alias in connections if alias not in databases] if unused_databases: self.log( "Skipping setup of unused database(s): %s." % ", ".join(sorted(unused_databases)), level=logging.DEBUG, ) return databases def run_tests(self, test_labels, extra_tests=None, **kwargs): """ Run the unit tests for all the test labels in the provided list. Test labels should be dotted Python paths to test modules, test classes, or test methods. Return the number of tests that failed. """ if extra_tests is not None: warnings.warn( "The extra_tests argument is deprecated.", RemovedInDjango50Warning, stacklevel=2, ) self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) databases = self.get_databases(suite) serialized_aliases = set( alias for alias, serialize in databases.items() if serialize ) with self.time_keeper.timed("Total database setup"): old_config = self.setup_databases( aliases=databases, serialized_aliases=serialized_aliases, ) run_failed = False try: self.run_checks(databases) result = self.run_suite(suite) except Exception: run_failed = True raise finally: try: with self.time_keeper.timed("Total database teardown"): self.teardown_databases(old_config) self.teardown_test_environment() except Exception: # Silence teardown exceptions if an exception was raised during # runs to avoid shadowing it. if not run_failed: raise self.time_keeper.print_results() return self.suite_result(suite, result) def try_importing(label): """ Try importing a test label, and return (is_importable, is_package). Relative labels like "." and ".." are seen as directories. """ try: mod = import_module(label) except (ImportError, TypeError): return (False, False) return (True, hasattr(mod, "__path__")) def find_top_level(top_level): # Try to be a bit smarter than unittest about finding the default top-level # for a given directory path, to avoid breaking relative imports. # (Unittest's default is to set top-level equal to the path, which means # relative imports will result in "Attempted relative import in # non-package."). # We'd be happy to skip this and require dotted module paths (which don't # cause this problem) instead of file paths (which do), but in the case of # a directory in the cwd, which would be equally valid if considered as a # top-level module or as a directory path, unittest unfortunately prefers # the latter. while True: init_py = os.path.join(top_level, "__init__.py") if not os.path.exists(init_py): break try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give up. break top_level = try_next return top_level def _class_shuffle_key(cls): return f"{cls.__module__}.{cls.__qualname__}" def shuffle_tests(tests, shuffler): """ Return an iterator over the given tests in a shuffled order, keeping tests next to other tests of their class. `tests` should be an iterable of tests. """ tests_by_type = {} for _, class_tests in itertools.groupby(tests, type): class_tests = list(class_tests) test_type = type(class_tests[0]) class_tests = shuffler.shuffle(class_tests, key=lambda test: test.id()) tests_by_type[test_type] = class_tests classes = shuffler.shuffle(tests_by_type, key=_class_shuffle_key) return itertools.chain(*(tests_by_type[cls] for cls in classes)) def reorder_test_bin(tests, shuffler=None, reverse=False): """ Return an iterator that reorders the given tests, keeping tests next to other tests of their class. `tests` should be an iterable of tests that supports reversed(). """ if shuffler is None: if reverse: return reversed(tests) # The function must return an iterator. return iter(tests) tests = shuffle_tests(tests, shuffler) if not reverse: return tests # Arguments to reversed() must be reversible. return reversed(list(tests)) def reorder_tests(tests, classes, reverse=False, shuffler=None): """ Reorder an iterable of tests, grouping by the given TestCase classes. This function also removes any duplicates and reorders so that tests of the same type are consecutive. The result is returned as an iterator. `classes` is a sequence of types. Tests that are instances of `classes[0]` are grouped first, followed by instances of `classes[1]`, etc. Tests that are not instances of any of the classes are grouped last. If `reverse` is True, the tests within each `classes` group are reversed, but without reversing the order of `classes` itself. The `shuffler` argument is an optional instance of this module's `Shuffler` class. If provided, tests will be shuffled within each `classes` group, but keeping tests with other tests of their TestCase class. Reversing is applied after shuffling to allow reversing the same random order. """ # Each bin maps TestCase class to OrderedSet of tests. This permits tests # to be grouped by TestCase class even if provided non-consecutively. bins = [defaultdict(OrderedSet) for i in range(len(classes) + 1)] *class_bins, last_bin = bins for test in tests: for test_bin, test_class in zip(class_bins, classes): if isinstance(test, test_class): break else: test_bin = last_bin test_bin[type(test)].add(test) for test_bin in bins: # Call list() since reorder_test_bin()'s input must support reversed(). tests = list(itertools.chain.from_iterable(test_bin.values())) yield from reorder_test_bin(tests, shuffler=shuffler, reverse=reverse) def partition_suite_by_case(suite): """Partition a test suite by test case, preserving the order of tests.""" suite_class = type(suite) all_tests = iter_test_cases(suite) return [suite_class(tests) for _, tests in itertools.groupby(all_tests, type)] def test_match_tags(test, tags, exclude_tags): if isinstance(test, unittest.loader._FailedTest): # Tests that couldn't load always match to prevent tests from falsely # passing due e.g. to syntax errors. return True test_tags = set(getattr(test, "tags", [])) test_fn_name = getattr(test, "_testMethodName", str(test)) if hasattr(test, test_fn_name): test_fn = getattr(test, test_fn_name) test_fn_tags = list(getattr(test_fn, "tags", [])) test_tags = test_tags.union(test_fn_tags) if tags and test_tags.isdisjoint(tags): return False return test_tags.isdisjoint(exclude_tags) def filter_tests_by_tags(tests, tags, exclude_tags): """Return the matching tests as an iterator.""" return (test for test in tests if test_match_tags(test, tags, exclude_tags))
64dc29ad8b8477916ea86f5f431079b8424f2ecf11ee615050914310b4b93754
import json import mimetypes import os import sys from copy import copy from functools import partial from http import HTTPStatus from importlib import import_module from io import BytesIO from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit from asgiref.sync import sync_to_async from django.conf import settings from django.core.handlers.asgi import ASGIRequest from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import WSGIRequest from django.core.serializers.json import DjangoJSONEncoder from django.core.signals import got_request_exception, request_finished, request_started from django.db import close_old_connections from django.http import HttpRequest, QueryDict, SimpleCookie from django.test import signals from django.test.utils import ContextList from django.urls import resolve from django.utils.encoding import force_bytes from django.utils.functional import SimpleLazyObject from django.utils.http import urlencode from django.utils.itercompat import is_iterable from django.utils.regex_helper import _lazy_re_compile __all__ = ( "AsyncClient", "AsyncRequestFactory", "Client", "RedirectCycleError", "RequestFactory", "encode_file", "encode_multipart", ) BOUNDARY = "BoUnDaRyStRiNg" MULTIPART_CONTENT = "multipart/form-data; boundary=%s" % BOUNDARY CONTENT_TYPE_RE = _lazy_re_compile(r".*; charset=([\w-]+);?") # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8 JSON_CONTENT_TYPE_RE = _lazy_re_compile(r"^application\/(.+\+)?json") class RedirectCycleError(Exception): """The test client has been asked to follow a redirect loop.""" def __init__(self, message, last_response): super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain class FakePayload: """ A wrapper around BytesIO that restricts what can be read since data from the network can't be sought and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life. """ def __init__(self, content=None): self.__content = BytesIO() self.__len = 0 self.read_started = False if content is not None: self.write(content) def __len__(self): return self.__len def read(self, num_bytes=None): if not self.read_started: self.__content.seek(0) self.read_started = True if num_bytes is None: num_bytes = self.__len or 0 assert ( self.__len >= num_bytes ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(num_bytes) self.__len -= num_bytes return content def write(self, content): if self.read_started: raise ValueError("Unable to write a payload after it's been read") content = force_bytes(content) self.__content.write(content) self.__len += len(content) def closing_iterator_wrapper(iterable, close): try: yield from iterable finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) def conditional_content_removal(request, response): """ Simulate the behavior of most web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensure compliance with RFC 7230, section 3.3.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): if response.streaming: response.streaming_content = [] else: response.content = b"" if request.method == "HEAD": if response.streaming: response.streaming_content = [] else: response.content = b"" return response class ClientHandler(BaseHandler): """ An HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # Emulate a WSGI server by calling the close method on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response class AsyncClientHandler(BaseHandler): """An async version of ClientHandler.""" def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) async def __call__(self, scope): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware(is_async=True) # Extract body file from the scope, if provided. if "_body_file" in scope: body_file = scope.pop("_body_file") else: body_file = FakePayload("") request_started.disconnect(close_old_connections) await sync_to_async(request_started.send, thread_sensitive=False)( sender=self.__class__, scope=scope ) request_started.connect(close_old_connections) request = ASGIRequest(scope, body_file) # Sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably required # for backwards compatibility with external tests against admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = await self.get_response_async(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating ASGI request to the response so that it could # be later retrieved. response.asgi_request = request # Emulate a server by calling the close method on completion. if response.streaming: response.streaming_content = await sync_to_async( closing_iterator_wrapper, thread_sensitive=False )( response.streaming_content, response.close, ) else: request_finished.disconnect(close_old_connections) # Will fire request_finished. await sync_to_async(response.close, thread_sensitive=False)() request_finished.connect(close_old_connections) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """ store.setdefault("templates", []).append(template) if "context" not in store: store["context"] = ContextList() store["context"].append(copy(context)) def encode_multipart(boundary, data): """ Encode multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. def is_file(thing): return hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for (key, value) in data.items(): if value is None: raise TypeError( "Cannot encode None for key '%s' as POST data. Did you mean " "to pass an empty string or omit the value?" % key ) elif is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, str) and is_iterable(value): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", item, ] ) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", value, ] ) lines.extend( [ to_bytes("--%s--" % boundary), b"", ] ) return b"\r\n".join(lines) def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # file.name might not be a string. For example, it's an int for # tempfile.TemporaryFile(). file_has_string_name = hasattr(file, "name") and isinstance(file.name, str) filename = os.path.basename(file.name) if file_has_string_name else "" if hasattr(file, "content_type"): content_type = file.content_type elif filename: content_type = mimetypes.guess_type(filename)[0] else: content_type = None if content_type is None: content_type = "application/octet-stream" filename = filename or key return [ to_bytes("--%s" % boundary), to_bytes( 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ), to_bytes("Content-Type: %s" % content_type), b"", to_bytes(file.read()), ] class RequestFactory: """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults): self.json_encoder = json_encoder self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See https://www.python.org/dev/peps/pep-3333/#environ-variables return { "HTTP_COOKIE": "; ".join( sorted( "%s=%s" % (morsel.key, morsel.coded_value) for morsel in self.cookies.values() ) ), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, **self.defaults, **request, } def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match[1] else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _encode_json(self, data, content_type): """ Return encoded JSON if data is a dict, list, or tuple and content_type is application/json. """ should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance( data, (dict, list, tuple) ) return json.dumps(data, cls=self.json_encoder) if should_encode else data def _get_path(self, parsed): path = parsed.path # If there are parameters, add them if parsed.params: path += ";" + parsed.params path = unquote_to_bytes(path) # Replace the behavior where non-ASCII values in the WSGI environ are # arbitrarily decoded with ISO-8859-1. # Refs comment in `get_bytes_from_wsgi()`. return path.decode("iso-8859-1") def get(self, path, data=None, secure=False, **extra): """Construct a GET request.""" data = {} if data is None else data return self.generic( "GET", path, secure=secure, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def post( self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, **extra ): """Construct a POST request.""" data = self._encode_json({} if data is None else data, content_type) post_data = self._encode_data(data, content_type) return self.generic( "POST", path, post_data, content_type, secure=secure, **extra ) def head(self, path, data=None, secure=False, **extra): """Construct a HEAD request.""" data = {} if data is None else data return self.generic( "HEAD", path, secure=secure, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def trace(self, path, secure=False, **extra): """Construct a TRACE request.""" return self.generic("TRACE", path, secure=secure, **extra) def options( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): "Construct an OPTIONS request." return self.generic("OPTIONS", path, data, content_type, secure=secure, **extra) def put( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct a PUT request.""" data = self._encode_json(data, content_type) return self.generic("PUT", path, data, content_type, secure=secure, **extra) def patch( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct a PATCH request.""" data = self._encode_json(data, content_type) return self.generic("PATCH", path, data, content_type, secure=secure, **extra) def delete( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct a DELETE request.""" data = self._encode_json(data, content_type) return self.generic("DELETE", path, data, content_type, secure=secure, **extra) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { "PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": method, "SERVER_PORT": "443" if secure else "80", "wsgi.url_scheme": "https" if secure else "http", } if data: r.update( { "CONTENT_LENGTH": str(len(data)), "CONTENT_TYPE": content_type, "wsgi.input": FakePayload(data), } ) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get("QUERY_STRING"): # WSGI requires latin-1 encoded strings. See get_path_info(). query_string = parsed[4].encode().decode("iso-8859-1") r["QUERY_STRING"] = query_string return self.request(**r) class AsyncRequestFactory(RequestFactory): """ Class that lets you create mock ASGI-like Request objects for use in testing. Usage: rf = AsyncRequestFactory() get_request = await rf.get('/hello/') post_request = await rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, including synchronous ones. The reason we have a separate class here is: a) this makes ASGIRequest subclasses, and b) AsyncTestClient can subclass it. """ def _base_scope(self, **request): """The base scope for a request.""" # This is a minimal valid ASGI scope, plus: # - headers['cookie'] for cookie support, # - 'client' often useful, see #8551. scope = { "asgi": {"version": "3.0"}, "type": "http", "http_version": "1.1", "client": ["127.0.0.1", 0], "server": ("testserver", "80"), "scheme": "http", "method": "GET", "headers": [], **self.defaults, **request, } scope["headers"].append( ( b"cookie", b"; ".join( sorted( ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii") for morsel in self.cookies.values() ) ), ) ) return scope def request(self, **request): """Construct a generic request object.""" # This is synchronous, which means all methods on this class are. # AsyncClient, however, has an async request function, which makes all # its methods async. if "_body_file" in request: body_file = request.pop("_body_file") else: body_file = FakePayload("") return ASGIRequest(self._base_scope(**request), body_file) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy. data = force_bytes(data, settings.DEFAULT_CHARSET) s = { "method": method, "path": self._get_path(parsed), "server": ("127.0.0.1", "443" if secure else "80"), "scheme": "https" if secure else "http", "headers": [(b"host", b"testserver")], } if data: s["headers"].extend( [ (b"content-length", str(len(data)).encode("ascii")), (b"content-type", content_type.encode("ascii")), ] ) s["_body_file"] = FakePayload(data) follow = extra.pop("follow", None) if follow is not None: s["follow"] = follow if query_string := extra.pop("QUERY_STRING", None): s["query_string"] = query_string s["headers"] += [ (key.lower().encode("ascii"), value.encode("latin1")) for key, value in extra.items() ] # If QUERY_STRING is absent or empty, we want to extract it from the # URL. if not s.get("query_string"): s["query_string"] = parsed[4] return self.request(**s) class ClientMixin: """ Mixin with common methods between Client and AsyncClient. """ def store_exc_info(self, **kwargs): """Store exceptions when they are generated by a view.""" self.exc_info = sys.exc_info() def check_exception(self, response): """ Look for a signaled exception, clear the current context exception data, re-raise the signaled exception, and clear the signaled exception from the local cache. """ response.exc_info = self.exc_info if self.exc_info: _, exc_value, _ = self.exc_info self.exc_info = None if self.raise_request_exception: raise exc_value @property def session(self): """Return the current session variables.""" engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session def login(self, **credentials): """ Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible or False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True return False def force_login(self, user, backend=None): def get_backend(): from django.contrib.auth import load_backend for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) if hasattr(backend, "get_user"): return backend_path if backend is None: backend = get_backend() user.backend = backend self._login(user, backend) def _login(self, user, backend=None): from django.contrib.auth import login # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() login(request, user, backend) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } self.cookies[session_cookie].update(cookie_data) def logout(self): """Log out the user by removing the cookies and session object.""" from django.contrib.auth import get_user, logout request = HttpRequest() if self.session: request.session = self.session request.user = get_user(request) else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie() def _parse_json(self, response, **extra): if not hasattr(response, "_json"): if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")): raise ValueError( 'Content-Type header is "%s", not "application/json"' % response.get("Content-Type") ) response._json = json.loads( response.content.decode(response.charset), **extra ) return response._json class Client(ClientMixin, RequestFactory): """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, **defaults ): super().__init__(**defaults) self.handler = ClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None def request(self, **request): """ The master request method. Compose the environment dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ environ = self._base_environ(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = self.handler(environ) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.wsgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["PATH_INFO"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get(self, path, data=None, follow=False, secure=False, **extra): """Request a response from the server using GET.""" self.extra = extra response = super().get(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def post( self, path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra, ): """Request a response from the server using POST.""" self.extra = extra response = super().post( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def head(self, path, data=None, follow=False, secure=False, **extra): """Request a response from the server using HEAD.""" self.extra = extra response = super().head(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def options( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Request a response from the server using OPTIONS.""" self.extra = extra response = super().options( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def put( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Send a resource to the server using PUT.""" self.extra = extra response = super().put( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def patch( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Send a resource to the server using PATCH.""" self.extra = extra response = super().patch( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def delete( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Send a DELETE request to the server.""" self.extra = extra response = super().delete( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def trace(self, path, data="", follow=False, secure=False, **extra): """Send a TRACE request to the server.""" self.extra = extra response = super().trace(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def _handle_redirects(self, response, data="", content_type="", **extra): """ Follow any redirects by requesting responses from the server using GET. """ response.redirect_chain = [] redirect_status_codes = ( HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.FOUND, HTTPStatus.SEE_OTHER, HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ) while response.status_code in redirect_status_codes: response_url = response.url redirect_chain = response.redirect_chain redirect_chain.append((response_url, response.status_code)) url = urlsplit(response_url) if url.scheme: extra["wsgi.url_scheme"] = url.scheme if url.hostname: extra["SERVER_NAME"] = url.hostname if url.port: extra["SERVER_PORT"] = str(url.port) path = url.path # RFC 2616: bare domains without path are treated as the root. if not path and url.netloc: path = "/" # Prepend the request path to handle relative path redirects if not path.startswith("/"): path = urljoin(response.request["PATH_INFO"], path) if response.status_code in ( HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ): # Preserve request method and query string (if needed) # post-redirect for 307/308 responses. request_method = response.request["REQUEST_METHOD"].lower() if request_method not in ("get", "head"): extra["QUERY_STRING"] = url.query request_method = getattr(self, request_method) else: request_method = self.get data = QueryDict(url.query) content_type = None response = request_method( path, data=data, content_type=content_type, follow=False, **extra ) response.redirect_chain = redirect_chain if redirect_chain[-1] in redirect_chain[:-1]: # Check that we're not redirecting to somewhere we've already # been to, to prevent loops. raise RedirectCycleError( "Redirect loop detected.", last_response=response ) if len(redirect_chain) > 20: # Such a lengthy chain likely also means a loop, but one with # a growing path, changing view, or changing query argument; # 20 is the value of "network.http.redirection-limit" from Firefox. raise RedirectCycleError("Too many redirects.", last_response=response) return response class AsyncClient(ClientMixin, AsyncRequestFactory): """ An async version of Client that creates ASGIRequests and calls through an async request path. Does not currently support "follow" on its methods. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, **defaults ): super().__init__(**defaults) self.handler = AsyncClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None async def request(self, **request): """ The master request method. Compose the scope dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ if "follow" in request: raise NotImplementedError( "AsyncClient request methods do not accept the follow parameter." ) scope = self._base_scope(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = await self.handler(scope) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.asgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["path"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response
a7a77578806cbbcd2cad04d6cc12b39beeec09479320e845fcada37fd7512dd1
import asyncio import difflib import json import logging import posixpath import sys import threading import unittest import warnings from collections import Counter from contextlib import contextmanager from copy import copy, deepcopy from difflib import get_close_matches from functools import wraps from unittest.suite import _DebugResult from unittest.util import safe_repr from urllib.parse import ( parse_qsl, unquote, urlencode, urljoin, urlparse, urlsplit, urlunparse, ) from urllib.request import url2pathname from asgiref.sync import async_to_sync from django.apps import apps from django.conf import settings from django.core import mail from django.core.exceptions import ImproperlyConfigured, ValidationError from django.core.files import locks from django.core.handlers.wsgi import WSGIHandler, get_path_info from django.core.management import call_command from django.core.management.color import no_style from django.core.management.sql import emit_post_migrate_signal from django.core.servers.basehttp import ThreadedWSGIServer, WSGIRequestHandler from django.core.signals import setting_changed from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction from django.forms.fields import CharField from django.http import QueryDict from django.http.request import split_domain_port, validate_host from django.test.client import AsyncClient, Client from django.test.html import HTMLParseError, parse_html from django.test.signals import template_rendered from django.test.utils import ( CaptureQueriesContext, ContextList, compare_xml, modify_settings, override_settings, ) from django.utils.deprecation import RemovedInDjango50Warning from django.utils.functional import classproperty from django.utils.version import PY310 from django.views.static import serve __all__ = ( "TestCase", "TransactionTestCase", "SimpleTestCase", "skipIfDBFeature", "skipUnlessDBFeature", ) def to_list(value): """Put value into a list if it's not already one.""" if not isinstance(value, list): value = [value] return value def assert_and_parse_html(self, html, user_msg, msg): try: dom = parse_html(html) except HTMLParseError as e: standardMsg = "%s\n%s" % (msg, e) self.fail(self._formatMessage(user_msg, standardMsg)) return dom class _AssertNumQueriesContext(CaptureQueriesContext): def __init__(self, test_case, num, connection): self.test_case = test_case self.num = num super().__init__(connection) def __exit__(self, exc_type, exc_value, traceback): super().__exit__(exc_type, exc_value, traceback) if exc_type is not None: return executed = len(self) self.test_case.assertEqual( executed, self.num, "%d queries executed, %d expected\nCaptured queries were:\n%s" % ( executed, self.num, "\n".join( "%d. %s" % (i, query["sql"]) for i, query in enumerate(self.captured_queries, start=1) ), ), ) class _AssertTemplateUsedContext: def __init__(self, test_case, template_name, msg_prefix="", count=None): self.test_case = test_case self.template_name = template_name self.msg_prefix = msg_prefix self.count = count self.rendered_templates = [] self.rendered_template_names = [] self.context = ContextList() def on_template_render(self, sender, signal, template, context, **kwargs): self.rendered_templates.append(template) self.rendered_template_names.append(template.name) self.context.append(copy(context)) def test(self): self.test_case._assert_template_used( self.template_name, self.rendered_template_names, self.msg_prefix, self.count, ) def __enter__(self): template_rendered.connect(self.on_template_render) return self def __exit__(self, exc_type, exc_value, traceback): template_rendered.disconnect(self.on_template_render) if exc_type is not None: return self.test() class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext): def test(self): self.test_case.assertFalse( self.template_name in self.rendered_template_names, f"{self.msg_prefix}Template '{self.template_name}' was used " f"unexpectedly in rendering the response", ) class DatabaseOperationForbidden(AssertionError): pass class _DatabaseFailure: def __init__(self, wrapped, message): self.wrapped = wrapped self.message = message def __call__(self): raise DatabaseOperationForbidden(self.message) class SimpleTestCase(unittest.TestCase): # The class we'll use for the test client self.client. # Can be overridden in derived classes. client_class = Client async_client_class = AsyncClient _overridden_settings = None _modified_settings = None databases = set() _disallowed_database_msg = ( "Database %(operation)s to %(alias)r are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to ensure " "proper test isolation or add %(alias)r to %(test)s.databases to silence " "this failure." ) _disallowed_connection_methods = [ ("connect", "connections"), ("temporary_connection", "connections"), ("cursor", "queries"), ("chunked_cursor", "queries"), ] @classmethod def setUpClass(cls): super().setUpClass() if cls._overridden_settings: cls._cls_overridden_context = override_settings(**cls._overridden_settings) cls._cls_overridden_context.enable() cls.addClassCleanup(cls._cls_overridden_context.disable) if cls._modified_settings: cls._cls_modified_context = modify_settings(cls._modified_settings) cls._cls_modified_context.enable() cls.addClassCleanup(cls._cls_modified_context.disable) cls._add_databases_failures() cls.addClassCleanup(cls._remove_databases_failures) @classmethod def _validate_databases(cls): if cls.databases == "__all__": return frozenset(connections) for alias in cls.databases: if alias not in connections: message = ( "%s.%s.databases refers to %r which is not defined in " "settings.DATABASES." % ( cls.__module__, cls.__qualname__, alias, ) ) close_matches = get_close_matches(alias, list(connections)) if close_matches: message += " Did you mean %r?" % close_matches[0] raise ImproperlyConfigured(message) return frozenset(cls.databases) @classmethod def _add_databases_failures(cls): cls.databases = cls._validate_databases() for alias in connections: if alias in cls.databases: continue connection = connections[alias] for name, operation in cls._disallowed_connection_methods: message = cls._disallowed_database_msg % { "test": "%s.%s" % (cls.__module__, cls.__qualname__), "alias": alias, "operation": operation, } method = getattr(connection, name) setattr(connection, name, _DatabaseFailure(method, message)) @classmethod def _remove_databases_failures(cls): for alias in connections: if alias in cls.databases: continue connection = connections[alias] for name, _ in cls._disallowed_connection_methods: method = getattr(connection, name) setattr(connection, name, method.wrapped) def __call__(self, result=None): """ Wrapper around default __call__ method to perform common Django test set up. This means that user-defined Test Cases aren't required to include a call to super().setUp(). """ self._setup_and_call(result) def debug(self): """Perform the same as __call__(), without catching the exception.""" debug_result = _DebugResult() self._setup_and_call(debug_result, debug=True) def _setup_and_call(self, result, debug=False): """ Perform the following in order: pre-setup, run test, post-teardown, skipping pre/post hooks if test is set to be skipped. If debug=True, reraise any errors in setup and use super().debug() instead of __call__() to run the test. """ testMethod = getattr(self, self._testMethodName) skipped = getattr(self.__class__, "__unittest_skip__", False) or getattr( testMethod, "__unittest_skip__", False ) # Convert async test methods. if asyncio.iscoroutinefunction(testMethod): setattr(self, self._testMethodName, async_to_sync(testMethod)) if not skipped: try: self._pre_setup() except Exception: if debug: raise result.addError(self, sys.exc_info()) return if debug: super().debug() else: super().__call__(result) if not skipped: try: self._post_teardown() except Exception: if debug: raise result.addError(self, sys.exc_info()) return def _pre_setup(self): """ Perform pre-test setup: * Create a test client. * Clear the mail test outbox. """ self.client = self.client_class() self.async_client = self.async_client_class() mail.outbox = [] def _post_teardown(self): """Perform post-test things.""" pass def settings(self, **kwargs): """ A context manager that temporarily sets a setting and reverts to the original value when exiting the context. """ return override_settings(**kwargs) def modify_settings(self, **kwargs): """ A context manager that temporarily applies changes a list setting and reverts back to the original value when exiting the context. """ return modify_settings(**kwargs) def assertRedirects( self, response, expected_url, status_code=302, target_status_code=200, msg_prefix="", fetch_redirect_response=True, ): """ Assert that a response redirected to a specific URL and that the redirect URL can be loaded. Won't work for external links since it uses the test client to do a request (use fetch_redirect_response=False to check such links without fetching them). """ if msg_prefix: msg_prefix += ": " if hasattr(response, "redirect_chain"): # The request was a followed redirect self.assertTrue( response.redirect_chain, msg_prefix + ( "Response didn't redirect as expected: Response code was %d " "(expected %d)" ) % (response.status_code, status_code), ) self.assertEqual( response.redirect_chain[0][1], status_code, msg_prefix + ( "Initial response didn't redirect as expected: Response code was " "%d (expected %d)" ) % (response.redirect_chain[0][1], status_code), ) url, status_code = response.redirect_chain[-1] self.assertEqual( response.status_code, target_status_code, msg_prefix + ( "Response didn't redirect as expected: Final Response code was %d " "(expected %d)" ) % (response.status_code, target_status_code), ) else: # Not a followed redirect self.assertEqual( response.status_code, status_code, msg_prefix + ( "Response didn't redirect as expected: Response code was %d " "(expected %d)" ) % (response.status_code, status_code), ) url = response.url scheme, netloc, path, query, fragment = urlsplit(url) # Prepend the request path to handle relative path redirects. if not path.startswith("/"): url = urljoin(response.request["PATH_INFO"], url) path = urljoin(response.request["PATH_INFO"], path) if fetch_redirect_response: # netloc might be empty, or in cases where Django tests the # HTTP scheme, the convention is for netloc to be 'testserver'. # Trust both as "internal" URLs here. domain, port = split_domain_port(netloc) if domain and not validate_host(domain, settings.ALLOWED_HOSTS): raise ValueError( "The test client is unable to fetch remote URLs (got %s). " "If the host is served by Django, add '%s' to ALLOWED_HOSTS. " "Otherwise, use " "assertRedirects(..., fetch_redirect_response=False)." % (url, domain) ) # Get the redirection page, using the same client that was used # to obtain the original response. extra = response.client.extra or {} redirect_response = response.client.get( path, QueryDict(query), secure=(scheme == "https"), **extra, ) self.assertEqual( redirect_response.status_code, target_status_code, msg_prefix + ( "Couldn't retrieve redirection page '%s': response code was %d " "(expected %d)" ) % (path, redirect_response.status_code, target_status_code), ) self.assertURLEqual( url, expected_url, msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url), ) def assertURLEqual(self, url1, url2, msg_prefix=""): """ Assert that two URLs are the same, ignoring the order of query string parameters except for parameters with the same name. For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but /path/?a=1&a=2 isn't equal to /path/?a=2&a=1. """ def normalize(url): """Sort the URL's query string parameters.""" url = str(url) # Coerce reverse_lazy() URLs. scheme, netloc, path, params, query, fragment = urlparse(url) query_parts = sorted(parse_qsl(query)) return urlunparse( (scheme, netloc, path, params, urlencode(query_parts), fragment) ) self.assertEqual( normalize(url1), normalize(url2), msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2), ) def _assert_contains(self, response, text, status_code, msg_prefix, html): # If the response supports deferred rendering and hasn't been rendered # yet, then ensure that it does get rendered before proceeding further. if ( hasattr(response, "render") and callable(response.render) and not response.is_rendered ): response.render() if msg_prefix: msg_prefix += ": " self.assertEqual( response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code), ) if response.streaming: content = b"".join(response.streaming_content) else: content = response.content if not isinstance(text, bytes) or html: text = str(text) content = content.decode(response.charset) text_repr = "'%s'" % text else: text_repr = repr(text) if html: content = assert_and_parse_html( self, content, None, "Response's content is not valid HTML:" ) text = assert_and_parse_html( self, text, None, "Second argument is not valid HTML:" ) real_count = content.count(text) return (text_repr, real_count, msg_prefix) def assertContains( self, response, text, count=None, status_code=200, msg_prefix="", html=False ): """ Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ text_repr, real_count, msg_prefix = self._assert_contains( response, text, status_code, msg_prefix, html ) if count is not None: self.assertEqual( real_count, count, msg_prefix + "Found %d instances of %s in response (expected %d)" % (real_count, text_repr, count), ) else: self.assertTrue( real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr ) def assertNotContains( self, response, text, status_code=200, msg_prefix="", html=False ): """ Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that ``text`` doesn't occur in the content of the response. """ text_repr, real_count, msg_prefix = self._assert_contains( response, text, status_code, msg_prefix, html ) self.assertEqual( real_count, 0, msg_prefix + "Response should not contain %s" % text_repr ) def _check_test_client_response(self, response, attribute, method_name): """ Raise a ValueError if the given response doesn't have the required attribute. """ if not hasattr(response, attribute): raise ValueError( f"{method_name}() is only usable on responses fetched using " "the Django test Client." ) def _assert_form_error(self, form, field, errors, msg_prefix, form_repr): if not form.is_bound: self.fail( f"{msg_prefix}The {form_repr} is not bound, it will never have any " f"errors." ) if field is not None and field not in form.fields: self.fail( f"{msg_prefix}The {form_repr} does not contain the field {field!r}." ) if field is None: field_errors = form.non_field_errors() failure_message = f"The non-field errors of {form_repr} don't match." else: field_errors = form.errors.get(field, []) failure_message = ( f"The errors of field {field!r} on {form_repr} don't match." ) self.assertEqual(field_errors, errors, msg_prefix + failure_message) def assertFormError(self, response, form, field, errors, msg_prefix=""): """ Assert that a form used to render the response has a specific field error. """ self._check_test_client_response(response, "context", "assertFormError") if msg_prefix: msg_prefix += ": " # Put context(s) into a list to simplify processing. contexts = [] if response.context is None else to_list(response.context) if not contexts: self.fail( msg_prefix + "Response did not use any contexts to render the response" ) if errors is None: warnings.warn( "Passing errors=None to assertFormError() is deprecated, use " "errors=[] instead.", RemovedInDjango50Warning, stacklevel=2, ) errors = [] # Put error(s) into a list to simplify processing. errors = to_list(errors) # Search all contexts for the error. found_form = False for i, context in enumerate(contexts): if form in context: found_form = True self._assert_form_error( context[form], field, errors, msg_prefix, "form %r" % context[form] ) if not found_form: self.fail( msg_prefix + "The form '%s' was not used to render the response" % form ) def assertFormsetError( self, response, formset, form_index, field, errors, msg_prefix="" ): """ Assert that a formset used to render the response has a specific error. For field errors, specify the ``form_index`` and the ``field``. For non-field errors, specify the ``form_index`` and the ``field`` as None. For non-form errors, specify ``form_index`` as None and the ``field`` as None. """ self._check_test_client_response(response, "context", "assertFormsetError") # Add punctuation to msg_prefix if msg_prefix: msg_prefix += ": " # Put context(s) into a list to simplify processing. contexts = [] if response.context is None else to_list(response.context) if not contexts: self.fail( msg_prefix + "Response did not use any contexts to " "render the response" ) if errors is None: warnings.warn( "Passing errors=None to assertFormsetError() is deprecated, " "use errors=[] instead.", RemovedInDjango50Warning, stacklevel=2, ) errors = [] if form_index is None and field is not None: raise ValueError("You must use field=None with form_index=None.") # Put error(s) into a list to simplify processing. errors = to_list(errors) # Search all contexts for the error. found_formset = False for i, context in enumerate(contexts): if formset not in context or not hasattr(context[formset], "forms"): continue formset_repr = repr(context[formset]) if not context[formset].is_bound: self.fail( f"{msg_prefix}The formset {formset_repr} is not bound, it will " f"never have any errors." ) found_formset = True if form_index is not None: form_count = context[formset].total_form_count() if form_index >= form_count: form_or_forms = "forms" if form_count > 1 else "form" self.fail( f"{msg_prefix}The formset {formset_repr} only has " f"{form_count} {form_or_forms}." ) if form_index is not None: form_repr = f"form {form_index} of formset {formset_repr}" self._assert_form_error( context[formset].forms[form_index], field, errors, msg_prefix, form_repr, ) else: failure_message = ( f"{msg_prefix}The non-form errors of formset {formset_repr} don't " f"match." ) self.assertEqual( context[formset].non_form_errors(), errors, failure_message ) if not found_formset: self.fail( msg_prefix + "The formset '%s' was not used to render the response" % formset ) def _get_template_used(self, response, template_name, msg_prefix, method_name): if response is None and template_name is None: raise TypeError("response and/or template_name argument must be provided") if msg_prefix: msg_prefix += ": " if template_name is not None and response is not None: self._check_test_client_response(response, "templates", method_name) if not hasattr(response, "templates") or (response is None and template_name): if response: template_name = response response = None # use this template with context manager return template_name, None, msg_prefix template_names = [t.name for t in response.templates if t.name is not None] return None, template_names, msg_prefix def _assert_template_used(self, template_name, template_names, msg_prefix, count): if not template_names: self.fail(msg_prefix + "No templates used to render the response") self.assertTrue( template_name in template_names, msg_prefix + "Template '%s' was not a template used to render" " the response. Actual template(s) used: %s" % (template_name, ", ".join(template_names)), ) if count is not None: self.assertEqual( template_names.count(template_name), count, msg_prefix + "Template '%s' was expected to be rendered %d " "time(s) but was actually rendered %d time(s)." % (template_name, count, template_names.count(template_name)), ) def assertTemplateUsed( self, response=None, template_name=None, msg_prefix="", count=None ): """ Assert that the template with the provided name was used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._get_template_used( response, template_name, msg_prefix, "assertTemplateUsed", ) if context_mgr_template: # Use assertTemplateUsed as context manager. return _AssertTemplateUsedContext( self, context_mgr_template, msg_prefix, count ) self._assert_template_used(template_name, template_names, msg_prefix, count) def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=""): """ Assert that the template with the provided name was NOT used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._get_template_used( response, template_name, msg_prefix, "assertTemplateNotUsed", ) if context_mgr_template: # Use assertTemplateNotUsed as context manager. return _AssertTemplateNotUsedContext(self, context_mgr_template, msg_prefix) self.assertFalse( template_name in template_names, msg_prefix + "Template '%s' was used unexpectedly in rendering the response" % template_name, ) @contextmanager def _assert_raises_or_warns_cm( self, func, cm_attr, expected_exception, expected_message ): with func(expected_exception) as cm: yield cm self.assertIn(expected_message, str(getattr(cm, cm_attr))) def _assertFooMessage( self, func, cm_attr, expected_exception, expected_message, *args, **kwargs ): callable_obj = None if args: callable_obj, *args = args cm = self._assert_raises_or_warns_cm( func, cm_attr, expected_exception, expected_message ) # Assertion used in context manager fashion. if callable_obj is None: return cm # Assertion was passed a callable. with cm: callable_obj(*args, **kwargs) def assertRaisesMessage( self, expected_exception, expected_message, *args, **kwargs ): """ Assert that expected_message is found in the message of a raised exception. Args: expected_exception: Exception class expected to be raised. expected_message: expected error message string value. args: Function to be called and extra positional args. kwargs: Extra kwargs. """ return self._assertFooMessage( self.assertRaises, "exception", expected_exception, expected_message, *args, **kwargs, ) def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs): """ Same as assertRaisesMessage but for assertWarns() instead of assertRaises(). """ return self._assertFooMessage( self.assertWarns, "warning", expected_warning, expected_message, *args, **kwargs, ) # A similar method is available in Python 3.10+. if not PY310: @contextmanager def assertNoLogs(self, logger, level=None): """ Assert no messages are logged on the logger, with at least the given level. """ if isinstance(level, int): level = logging.getLevelName(level) elif level is None: level = "INFO" try: with self.assertLogs(logger, level) as cm: yield except AssertionError as e: msg = e.args[0] expected_msg = ( f"no logs of level {level} or higher triggered on {logger}" ) if msg != expected_msg: raise e else: self.fail(f"Unexpected logs found: {cm.output!r}") def assertFieldOutput( self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value="", ): """ Assert that a form field behaves correctly with various inputs. Args: fieldclass: the class of the field to be tested. valid: a dictionary mapping valid inputs to their expected cleaned values. invalid: a dictionary mapping invalid inputs to one or more raised error messages. field_args: the args passed to instantiate the field field_kwargs: the kwargs passed to instantiate the field empty_value: the expected clean output for inputs in empty_values """ if field_args is None: field_args = [] if field_kwargs is None: field_kwargs = {} required = fieldclass(*field_args, **field_kwargs) optional = fieldclass(*field_args, **{**field_kwargs, "required": False}) # test valid inputs for input, output in valid.items(): self.assertEqual(required.clean(input), output) self.assertEqual(optional.clean(input), output) # test invalid inputs for input, errors in invalid.items(): with self.assertRaises(ValidationError) as context_manager: required.clean(input) self.assertEqual(context_manager.exception.messages, errors) with self.assertRaises(ValidationError) as context_manager: optional.clean(input) self.assertEqual(context_manager.exception.messages, errors) # test required inputs error_required = [required.error_messages["required"]] for e in required.empty_values: with self.assertRaises(ValidationError) as context_manager: required.clean(e) self.assertEqual(context_manager.exception.messages, error_required) self.assertEqual(optional.clean(e), empty_value) # test that max_length and min_length are always accepted if issubclass(fieldclass, CharField): field_kwargs.update({"min_length": 2, "max_length": 20}) self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass) def assertHTMLEqual(self, html1, html2, msg=None): """ Assert that two HTML snippets are semantically the same. Whitespace in most cases is ignored, and attribute ordering is not significant. The arguments must be valid HTML. """ dom1 = assert_and_parse_html( self, html1, msg, "First argument is not valid HTML:" ) dom2 = assert_and_parse_html( self, html2, msg, "Second argument is not valid HTML:" ) if dom1 != dom2: standardMsg = "%s != %s" % (safe_repr(dom1, True), safe_repr(dom2, True)) diff = "\n" + "\n".join( difflib.ndiff( str(dom1).splitlines(), str(dom2).splitlines(), ) ) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertHTMLNotEqual(self, html1, html2, msg=None): """Assert that two HTML snippets are not semantically equivalent.""" dom1 = assert_and_parse_html( self, html1, msg, "First argument is not valid HTML:" ) dom2 = assert_and_parse_html( self, html2, msg, "Second argument is not valid HTML:" ) if dom1 == dom2: standardMsg = "%s == %s" % (safe_repr(dom1, True), safe_repr(dom2, True)) self.fail(self._formatMessage(msg, standardMsg)) def assertInHTML(self, needle, haystack, count=None, msg_prefix=""): needle = assert_and_parse_html( self, needle, None, "First argument is not valid HTML:" ) haystack = assert_and_parse_html( self, haystack, None, "Second argument is not valid HTML:" ) real_count = haystack.count(needle) if count is not None: self.assertEqual( real_count, count, msg_prefix + "Found %d instances of '%s' in response (expected %d)" % (real_count, needle, count), ) else: self.assertTrue( real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle ) def assertJSONEqual(self, raw, expected_data, msg=None): """ Assert that the JSON fragments raw and expected_data are equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except json.JSONDecodeError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, str): try: expected_data = json.loads(expected_data) except ValueError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertEqual(data, expected_data, msg=msg) def assertJSONNotEqual(self, raw, expected_data, msg=None): """ Assert that the JSON fragments raw and expected_data are not equal. Usual JSON non-significant whitespace rules apply as the heavyweight is delegated to the json library. """ try: data = json.loads(raw) except json.JSONDecodeError: self.fail("First argument is not valid JSON: %r" % raw) if isinstance(expected_data, str): try: expected_data = json.loads(expected_data) except json.JSONDecodeError: self.fail("Second argument is not valid JSON: %r" % expected_data) self.assertNotEqual(data, expected_data, msg=msg) def assertXMLEqual(self, xml1, xml2, msg=None): """ Assert that two XML snippets are semantically the same. Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML. """ try: result = compare_xml(xml1, xml2) except Exception as e: standardMsg = "First or second argument is not valid XML\n%s" % e self.fail(self._formatMessage(msg, standardMsg)) else: if not result: standardMsg = "%s != %s" % ( safe_repr(xml1, True), safe_repr(xml2, True), ) diff = "\n" + "\n".join( difflib.ndiff(xml1.splitlines(), xml2.splitlines()) ) standardMsg = self._truncateMessage(standardMsg, diff) self.fail(self._formatMessage(msg, standardMsg)) def assertXMLNotEqual(self, xml1, xml2, msg=None): """ Assert that two XML snippets are not semantically equivalent. Whitespace in most cases is ignored and attribute ordering is not significant. The arguments must be valid XML. """ try: result = compare_xml(xml1, xml2) except Exception as e: standardMsg = "First or second argument is not valid XML\n%s" % e self.fail(self._formatMessage(msg, standardMsg)) else: if result: standardMsg = "%s == %s" % ( safe_repr(xml1, True), safe_repr(xml2, True), ) self.fail(self._formatMessage(msg, standardMsg)) class TransactionTestCase(SimpleTestCase): # Subclasses can ask for resetting of auto increment sequence before each # test case reset_sequences = False # Subclasses can enable only a subset of apps for faster tests available_apps = None # Subclasses can define fixtures which will be automatically installed. fixtures = None databases = {DEFAULT_DB_ALIAS} _disallowed_database_msg = ( "Database %(operation)s to %(alias)r are not allowed in this test. " "Add %(alias)r to %(test)s.databases to ensure proper test isolation " "and silence this failure." ) # If transactions aren't available, Django will serialize the database # contents into a fixture during setup and flush and reload them # during teardown (as flush does not restore data from migrations). # This can be slow; this flag allows enabling on a per-case basis. serialized_rollback = False def _pre_setup(self): """ Perform pre-test setup: * If the class has an 'available_apps' attribute, restrict the app registry to these applications, then fire the post_migrate signal -- it must run with the correct set of applications for the test case. * If the class has a 'fixtures' attribute, install those fixtures. """ super()._pre_setup() if self.available_apps is not None: apps.set_available_apps(self.available_apps) setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=self.available_apps, enter=True, ) for db_name in self._databases_names(include_mirrors=False): emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name) try: self._fixture_setup() except Exception: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=settings.INSTALLED_APPS, enter=False, ) raise # Clear the queries_log so that it's less likely to overflow (a single # test probably won't execute 9K queries). If queries_log overflows, # then assertNumQueries() doesn't work. for db_name in self._databases_names(include_mirrors=False): connections[db_name].queries_log.clear() @classmethod def _databases_names(cls, include_mirrors=True): # Only consider allowed database aliases, including mirrors or not. return [ alias for alias in connections if alias in cls.databases and ( include_mirrors or not connections[alias].settings_dict["TEST"]["MIRROR"] ) ] def _reset_sequences(self, db_name): conn = connections[db_name] if conn.features.supports_sequence_reset: sql_list = conn.ops.sequence_reset_by_name_sql( no_style(), conn.introspection.sequence_list() ) if sql_list: with transaction.atomic(using=db_name): with conn.cursor() as cursor: for sql in sql_list: cursor.execute(sql) def _fixture_setup(self): for db_name in self._databases_names(include_mirrors=False): # Reset sequences if self.reset_sequences: self._reset_sequences(db_name) # Provide replica initial data from migrated apps, if needed. if self.serialized_rollback and hasattr( connections[db_name], "_test_serialized_contents" ): if self.available_apps is not None: apps.unset_available_apps() connections[db_name].creation.deserialize_db_from_string( connections[db_name]._test_serialized_contents ) if self.available_apps is not None: apps.set_available_apps(self.available_apps) if self.fixtures: # We have to use this slightly awkward syntax due to the fact # that we're using *args and **kwargs together. call_command( "loaddata", *self.fixtures, **{"verbosity": 0, "database": db_name} ) def _should_reload_connections(self): return True def _post_teardown(self): """ Perform post-test things: * Flush the contents of the database to leave a clean slate. If the class has an 'available_apps' attribute, don't fire post_migrate. * Force-close the connection so the next test gets a clean cursor. """ try: self._fixture_teardown() super()._post_teardown() if self._should_reload_connections(): # Some DB cursors include SQL statements as part of cursor # creation. If you have a test that does a rollback, the effect # of these statements is lost, which can affect the operation of # tests (e.g., losing a timezone setting causing objects to be # created with the wrong time). To make sure this doesn't # happen, get a clean connection at the start of every test. for conn in connections.all(): conn.close() finally: if self.available_apps is not None: apps.unset_available_apps() setting_changed.send( sender=settings._wrapped.__class__, setting="INSTALLED_APPS", value=settings.INSTALLED_APPS, enter=False, ) def _fixture_teardown(self): # Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal # when flushing only a subset of the apps for db_name in self._databases_names(include_mirrors=False): # Flush the database inhibit_post_migrate = ( self.available_apps is not None or ( # Inhibit the post_migrate signal when using serialized # rollback to avoid trying to recreate the serialized data. self.serialized_rollback and hasattr(connections[db_name], "_test_serialized_contents") ) ) call_command( "flush", verbosity=0, interactive=False, database=db_name, reset_sequences=False, allow_cascade=self.available_apps is not None, inhibit_post_migrate=inhibit_post_migrate, ) def assertQuerysetEqual(self, qs, values, transform=None, ordered=True, msg=None): values = list(values) items = qs if transform is not None: items = map(transform, items) if not ordered: return self.assertDictEqual(Counter(items), Counter(values), msg=msg) # For example qs.iterator() could be passed as qs, but it does not # have 'ordered' attribute. if len(values) > 1 and hasattr(qs, "ordered") and not qs.ordered: raise ValueError( "Trying to compare non-ordered queryset against more than one " "ordered value." ) return self.assertEqual(list(items), values, msg=msg) def assertNumQueries(self, num, func=None, *args, using=DEFAULT_DB_ALIAS, **kwargs): conn = connections[using] context = _AssertNumQueriesContext(self, num, conn) if func is None: return context with context: func(*args, **kwargs) def connections_support_transactions(aliases=None): """ Return whether or not all (or specified) connections support transactions. """ conns = ( connections.all() if aliases is None else (connections[alias] for alias in aliases) ) return all(conn.features.supports_transactions for conn in conns) class TestData: """ Descriptor to provide TestCase instance isolation for attributes assigned during the setUpTestData() phase. Allow safe alteration of objects assigned in setUpTestData() by test methods by exposing deep copies instead of the original objects. Objects are deep copied using a memo kept on the test case instance in order to maintain their original relationships. """ memo_attr = "_testdata_memo" def __init__(self, name, data): self.name = name self.data = data def get_memo(self, testcase): try: memo = getattr(testcase, self.memo_attr) except AttributeError: memo = {} setattr(testcase, self.memo_attr, memo) return memo def __get__(self, instance, owner): if instance is None: return self.data memo = self.get_memo(instance) data = deepcopy(self.data, memo) setattr(instance, self.name, data) return data def __repr__(self): return "<TestData: name=%r, data=%r>" % (self.name, self.data) class TestCase(TransactionTestCase): """ Similar to TransactionTestCase, but use `transaction.atomic()` to achieve test isolation. In most situations, TestCase should be preferred to TransactionTestCase as it allows faster execution. However, there are some situations where using TransactionTestCase might be necessary (e.g. testing some transactional behavior). On database backends with no transaction support, TestCase behaves as TransactionTestCase. """ @classmethod def _enter_atomics(cls): """Open atomic blocks for multiple databases.""" atomics = {} for db_name in cls._databases_names(): atomic = transaction.atomic(using=db_name) atomic._from_testcase = True atomic.__enter__() atomics[db_name] = atomic return atomics @classmethod def _rollback_atomics(cls, atomics): """Rollback atomic blocks opened by the previous method.""" for db_name in reversed(cls._databases_names()): transaction.set_rollback(True, using=db_name) atomics[db_name].__exit__(None, None, None) @classmethod def _databases_support_transactions(cls): return connections_support_transactions(cls.databases) @classmethod def setUpClass(cls): super().setUpClass() if not cls._databases_support_transactions(): return cls.cls_atomics = cls._enter_atomics() if cls.fixtures: for db_name in cls._databases_names(include_mirrors=False): try: call_command( "loaddata", *cls.fixtures, **{"verbosity": 0, "database": db_name}, ) except Exception: cls._rollback_atomics(cls.cls_atomics) raise pre_attrs = cls.__dict__.copy() try: cls.setUpTestData() except Exception: cls._rollback_atomics(cls.cls_atomics) raise for name, value in cls.__dict__.items(): if value is not pre_attrs.get(name): setattr(cls, name, TestData(name, value)) @classmethod def tearDownClass(cls): if cls._databases_support_transactions(): cls._rollback_atomics(cls.cls_atomics) for conn in connections.all(): conn.close() super().tearDownClass() @classmethod def setUpTestData(cls): """Load initial data for the TestCase.""" pass def _should_reload_connections(self): if self._databases_support_transactions(): return False return super()._should_reload_connections() def _fixture_setup(self): if not self._databases_support_transactions(): # If the backend does not support transactions, we should reload # class data before each test self.setUpTestData() return super()._fixture_setup() if self.reset_sequences: raise TypeError("reset_sequences cannot be used on TestCase instances") self.atomics = self._enter_atomics() def _fixture_teardown(self): if not self._databases_support_transactions(): return super()._fixture_teardown() try: for db_name in reversed(self._databases_names()): if self._should_check_constraints(connections[db_name]): connections[db_name].check_constraints() finally: self._rollback_atomics(self.atomics) def _should_check_constraints(self, connection): return ( connection.features.can_defer_constraint_checks and not connection.needs_rollback and connection.is_usable() ) @classmethod @contextmanager def captureOnCommitCallbacks(cls, *, using=DEFAULT_DB_ALIAS, execute=False): """Context manager to capture transaction.on_commit() callbacks.""" callbacks = [] start_count = len(connections[using].run_on_commit) try: yield callbacks finally: while True: callback_count = len(connections[using].run_on_commit) for _, callback in connections[using].run_on_commit[start_count:]: callbacks.append(callback) if execute: callback() if callback_count == len(connections[using].run_on_commit): break start_count = callback_count class CheckCondition: """Descriptor class for deferred condition checking.""" def __init__(self, *conditions): self.conditions = conditions def add_condition(self, condition, reason): return self.__class__(*self.conditions, (condition, reason)) def __get__(self, instance, cls=None): # Trigger access for all bases. if any(getattr(base, "__unittest_skip__", False) for base in cls.__bases__): return True for condition, reason in self.conditions: if condition(): # Override this descriptor's value and set the skip reason. cls.__unittest_skip__ = True cls.__unittest_skip_why__ = reason return True return False def _deferredSkip(condition, reason, name): def decorator(test_func): nonlocal condition if not ( isinstance(test_func, type) and issubclass(test_func, unittest.TestCase) ): @wraps(test_func) def skip_wrapper(*args, **kwargs): if ( args and isinstance(args[0], unittest.TestCase) and connection.alias not in getattr(args[0], "databases", {}) ): raise ValueError( "%s cannot be used on %s as %s doesn't allow queries " "against the %r database." % ( name, args[0], args[0].__class__.__qualname__, connection.alias, ) ) if condition(): raise unittest.SkipTest(reason) return test_func(*args, **kwargs) test_item = skip_wrapper else: # Assume a class is decorated test_item = test_func databases = getattr(test_item, "databases", None) if not databases or connection.alias not in databases: # Defer raising to allow importing test class's module. def condition(): raise ValueError( "%s cannot be used on %s as it doesn't allow queries " "against the '%s' database." % ( name, test_item, connection.alias, ) ) # Retrieve the possibly existing value from the class's dict to # avoid triggering the descriptor. skip = test_func.__dict__.get("__unittest_skip__") if isinstance(skip, CheckCondition): test_item.__unittest_skip__ = skip.add_condition(condition, reason) elif skip is not True: test_item.__unittest_skip__ = CheckCondition((condition, reason)) return test_item return decorator def skipIfDBFeature(*features): """Skip a test if a database has at least one of the named features.""" return _deferredSkip( lambda: any( getattr(connection.features, feature, False) for feature in features ), "Database has feature(s) %s" % ", ".join(features), "skipIfDBFeature", ) def skipUnlessDBFeature(*features): """Skip a test unless a database has all the named features.""" return _deferredSkip( lambda: not all( getattr(connection.features, feature, False) for feature in features ), "Database doesn't support feature(s): %s" % ", ".join(features), "skipUnlessDBFeature", ) def skipUnlessAnyDBFeature(*features): """Skip a test unless a database has any of the named features.""" return _deferredSkip( lambda: not any( getattr(connection.features, feature, False) for feature in features ), "Database doesn't support any of the feature(s): %s" % ", ".join(features), "skipUnlessAnyDBFeature", ) class QuietWSGIRequestHandler(WSGIRequestHandler): """ A WSGIRequestHandler that doesn't log to standard output any of the requests received, so as to not clutter the test result output. """ def log_message(*args): pass class FSFilesHandler(WSGIHandler): """ WSGI middleware that intercepts calls to a directory, as defined by one of the *_ROOT settings, and serves those files, publishing them under *_URL. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super().__init__() def _should_handle(self, path): """ Check if the path should be handled. Ignore the path if: * the host is provided as part of the base_url * the request's path isn't under the media path (or equal) """ return path.startswith(self.base_url[2]) and not self.base_url[1] def file_path(self, url): """Return the relative path to the file on disk for the given URL.""" relative_url = url[len(self.base_url[2]) :] return url2pathname(relative_url) def get_response(self, request): from django.http import Http404 if self._should_handle(request.path): try: return self.serve(request) except Http404: pass return super().get_response(request) def serve(self, request): os_rel_path = self.file_path(request.path) os_rel_path = posixpath.normpath(unquote(os_rel_path)) # Emulate behavior of django.contrib.staticfiles.views.serve() when it # invokes staticfiles' finders functionality. # TODO: Modify if/when that internal API is refactored final_rel_path = os_rel_path.replace("\\", "/").lstrip("/") return serve(request, final_rel_path, document_root=self.get_base_dir()) def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) return super().__call__(environ, start_response) class _StaticFilesHandler(FSFilesHandler): """ Handler for serving static files. A private class that is meant to be used solely as a convenience by LiveServerThread. """ def get_base_dir(self): return settings.STATIC_ROOT def get_base_url(self): return settings.STATIC_URL class _MediaFilesHandler(FSFilesHandler): """ Handler for serving the media files. A private class that is meant to be used solely as a convenience by LiveServerThread. """ def get_base_dir(self): return settings.MEDIA_ROOT def get_base_url(self): return settings.MEDIA_URL class LiveServerThread(threading.Thread): """Thread for running a live HTTP server while the tests are running.""" server_class = ThreadedWSGIServer def __init__(self, host, static_handler, connections_override=None, port=0): self.host = host self.port = port self.is_ready = threading.Event() self.error = None self.static_handler = static_handler self.connections_override = connections_override super().__init__() def run(self): """ Set up the live server and databases, and then loop over handling HTTP requests. """ if self.connections_override: # Override this thread's database connections with the ones # provided by the main thread. for alias, conn in self.connections_override.items(): connections[alias] = conn try: # Create the handler for serving static and media files handler = self.static_handler(_MediaFilesHandler(WSGIHandler())) self.httpd = self._create_server() # If binding to port zero, assign the port allocated by the OS. if self.port == 0: self.port = self.httpd.server_address[1] self.httpd.set_app(handler) self.is_ready.set() self.httpd.serve_forever() except Exception as e: self.error = e self.is_ready.set() finally: connections.close_all() def _create_server(self, connections_override=None): return self.server_class( (self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False, connections_override=connections_override, ) def terminate(self): if hasattr(self, "httpd"): # Stop the WSGI server self.httpd.shutdown() self.httpd.server_close() self.join() class LiveServerTestCase(TransactionTestCase): """ Do basically the same as TransactionTestCase but also launch a live HTTP server in a separate thread so that the tests may use another testing framework, such as Selenium for example, instead of the built-in dummy client. It inherits from TransactionTestCase instead of TestCase because the threads don't share the same transactions (unless if using in-memory sqlite) and each thread needs to commit all their transactions so that the other thread can see the changes. """ host = "localhost" port = 0 server_thread_class = LiveServerThread static_handler = _StaticFilesHandler @classproperty def live_server_url(cls): return "http://%s:%s" % (cls.host, cls.server_thread.port) @classproperty def allowed_host(cls): return cls.host @classmethod def _make_connections_override(cls): connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if conn.vendor == "sqlite" and conn.is_in_memory_db(): connections_override[conn.alias] = conn return connections_override @classmethod def setUpClass(cls): super().setUpClass() cls._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={"append": cls.allowed_host}, ) cls._live_server_modified_settings.enable() cls.addClassCleanup(cls._live_server_modified_settings.disable) cls._start_server_thread() @classmethod def _start_server_thread(cls): connections_override = cls._make_connections_override() for conn in connections_override.values(): # Explicitly enable thread-shareability for this connection. conn.inc_thread_sharing() cls.server_thread = cls._create_server_thread(connections_override) cls.server_thread.daemon = True cls.server_thread.start() cls.addClassCleanup(cls._terminate_thread) # Wait for the live server to be ready cls.server_thread.is_ready.wait() if cls.server_thread.error: raise cls.server_thread.error @classmethod def _create_server_thread(cls, connections_override): return cls.server_thread_class( cls.host, cls.static_handler, connections_override=connections_override, port=cls.port, ) @classmethod def _terminate_thread(cls): # Terminate the live server's thread. cls.server_thread.terminate() # Restore shared connections' non-shareability. for conn in cls.server_thread.connections_override.values(): conn.dec_thread_sharing() class SerializeMixin: """ Enforce serialization of TestCases that share a common resource. Define a common 'lockfile' for each set of TestCases to serialize. This file must exist on the filesystem. Place it early in the MRO in order to isolate setUpClass()/tearDownClass(). """ lockfile = None def __init_subclass__(cls, /, **kwargs): super().__init_subclass__(**kwargs) if cls.lockfile is None: raise ValueError( "{}.lockfile isn't set. Set it to a unique value " "in the base class.".format(cls.__name__) ) @classmethod def setUpClass(cls): cls._lockfile = open(cls.lockfile) cls.addClassCleanup(cls._lockfile.close) locks.lock(cls._lockfile, locks.LOCK_EX) super().setUpClass()
2f801ffea935ba45685e75bd7df913120e0af89bdd1c46799a2c4d457cd20cdf
"""Compare two HTML documents.""" import html from html.parser import HTMLParser from django.utils.regex_helper import _lazy_re_compile # ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 # SPACE. # https://infra.spec.whatwg.org/#ascii-whitespace ASCII_WHITESPACE = _lazy_re_compile(r"[\t\n\f\r ]+") # https://html.spec.whatwg.org/#attributes-3 BOOLEAN_ATTRIBUTES = { "allowfullscreen", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer ", "disabled", "formnovalidate", "hidden", "ismap", "itemscope", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected", # Attributes for deprecated tags. "truespeed", } def normalize_whitespace(string): return ASCII_WHITESPACE.sub(" ", string) def normalize_attributes(attributes): normalized = [] for name, value in attributes: if name == "class" and value: # Special case handling of 'class' attribute, so that comparisons # of DOM instances are not sensitive to ordering of classes. value = " ".join( sorted(value for value in ASCII_WHITESPACE.split(value) if value) ) # Boolean attributes without a value is same as attribute with value # that equals the attributes name. For example: # <input checked> == <input checked="checked"> if name in BOOLEAN_ATTRIBUTES: if not value or value == name: value = None elif value is None: value = "" normalized.append((name, value)) return normalized class Element: def __init__(self, name, attributes): self.name = name self.attributes = sorted(attributes) self.children = [] def append(self, element): if isinstance(element, str): element = normalize_whitespace(element) if self.children and isinstance(self.children[-1], str): self.children[-1] += element self.children[-1] = normalize_whitespace(self.children[-1]) return elif self.children: # removing last children if it is only whitespace # this can result in incorrect dom representations since # whitespace between inline tags like <span> is significant if isinstance(self.children[-1], str) and self.children[-1].isspace(): self.children.pop() if element: self.children.append(element) def finalize(self): def rstrip_last_element(children): if children and isinstance(children[-1], str): children[-1] = children[-1].rstrip() if not children[-1]: children.pop() children = rstrip_last_element(children) return children rstrip_last_element(self.children) for i, child in enumerate(self.children): if isinstance(child, str): self.children[i] = child.strip() elif hasattr(child, "finalize"): child.finalize() def __eq__(self, element): if not hasattr(element, "name") or self.name != element.name: return False if self.attributes != element.attributes: return False return self.children == element.children def __hash__(self): return hash((self.name, *self.attributes)) def _count(self, element, count=True): if not isinstance(element, str) and self == element: return 1 if isinstance(element, RootElement) and self.children == element.children: return 1 i = 0 elem_child_idx = 0 for child in self.children: # child is text content and element is also text content, then # make a simple "text" in "text" if isinstance(child, str): if isinstance(element, str): if count: i += child.count(element) elif element in child: return 1 else: # Look for element wholly within this child. i += child._count(element, count=count) if not count and i: return i # Also look for a sequence of element's children among self's # children. self.children == element.children is tested above, # but will fail if self has additional children. Ex: '<a/><b/>' # is contained in '<a/><b/><c/>'. if isinstance(element, RootElement) and element.children: elem_child = element.children[elem_child_idx] # Start or continue match, advance index. if elem_child == child: elem_child_idx += 1 # Match found, reset index. if elem_child_idx == len(element.children): i += 1 elem_child_idx = 0 # No match, reset index. else: elem_child_idx = 0 return i def __contains__(self, element): return self._count(element, count=False) > 0 def count(self, element): return self._count(element, count=True) def __getitem__(self, key): return self.children[key] def __str__(self): output = "<%s" % self.name for key, value in self.attributes: if value is not None: output += ' %s="%s"' % (key, value) else: output += " %s" % key if self.children: output += ">\n" output += "".join( [ html.escape(c) if isinstance(c, str) else str(c) for c in self.children ] ) output += "\n</%s>" % self.name else: output += ">" return output def __repr__(self): return str(self) class RootElement(Element): def __init__(self): super().__init__(None, ()) def __str__(self): return "".join( [html.escape(c) if isinstance(c, str) else str(c) for c in self.children] ) class HTMLParseError(Exception): pass class Parser(HTMLParser): # https://html.spec.whatwg.org/#void-elements SELF_CLOSING_TAGS = { "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", # Deprecated tags "frame", "spacer", } def __init__(self): super().__init__() self.root = RootElement() self.open_tags = [] self.element_positions = {} def error(self, msg): raise HTMLParseError(msg, self.getpos()) def format_position(self, position=None, element=None): if not position and element: position = self.element_positions[element] if position is None: position = self.getpos() if hasattr(position, "lineno"): position = position.lineno, position.offset return "Line %d, Column %d" % position @property def current(self): if self.open_tags: return self.open_tags[-1] else: return self.root def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) if tag not in self.SELF_CLOSING_TAGS: self.handle_endtag(tag) def handle_starttag(self, tag, attrs): attrs = normalize_attributes(attrs) element = Element(tag, attrs) self.current.append(element) if tag not in self.SELF_CLOSING_TAGS: self.open_tags.append(element) self.element_positions[element] = self.getpos() def handle_endtag(self, tag): if not self.open_tags: self.error("Unexpected end tag `%s` (%s)" % (tag, self.format_position())) element = self.open_tags.pop() while element.name != tag: if not self.open_tags: self.error( "Unexpected end tag `%s` (%s)" % (tag, self.format_position()) ) element = self.open_tags.pop() def handle_data(self, data): self.current.append(data) def parse_html(html): """ Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.feed(html) parser.close() document = parser.root document.finalize() # Removing ROOT element if it's not necessary if len(document.children) == 1 and not isinstance(document.children[0], str): document = document.children[0] return document
0d5b0f70502b02eeff98b2c84c1accd3b35756215077f7f5025cf7645dd08053
import asyncio import collections import logging import os import re import sys import time import warnings from contextlib import contextmanager from functools import wraps from io import StringIO from itertools import chain from types import SimpleNamespace from unittest import TestCase, skipIf, skipUnless from xml.dom.minidom import Node, parseString from django.apps import apps from django.apps.registry import Apps from django.conf import UserSettingsHolder, settings from django.core import mail from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started, setting_changed from django.db import DEFAULT_DB_ALIAS, connections, reset_queries from django.db.models.options import Options from django.template import Template from django.test.signals import template_rendered from django.urls import get_script_prefix, set_script_prefix from django.utils.deprecation import RemovedInDjango50Warning from django.utils.translation import deactivate try: import jinja2 except ImportError: jinja2 = None __all__ = ( "Approximate", "ContextList", "isolate_lru_cache", "get_runner", "CaptureQueriesContext", "ignore_warnings", "isolate_apps", "modify_settings", "override_settings", "override_system_checks", "tag", "requires_tz_support", "setup_databases", "setup_test_environment", "teardown_test_environment", ) TZ_SUPPORT = hasattr(time, "tzset") class Approximate: def __init__(self, val, places=7): self.val = val self.places = places def __repr__(self): return repr(self.val) def __eq__(self, other): return self.val == other or round(abs(self.val - other), self.places) == 0 class ContextList(list): """ A wrapper that provides direct key access to context items contained in a list of context objects. """ def __getitem__(self, key): if isinstance(key, str): for subcontext in self: if key in subcontext: return subcontext[key] raise KeyError(key) else: return super().__getitem__(key) def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default def __contains__(self, key): try: self[key] except KeyError: return False return True def keys(self): """ Flattened keys of subcontexts. """ return set(chain.from_iterable(d for subcontext in self for d in subcontext)) def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test Client. """ template_rendered.send(sender=self, template=self, context=context) return self.nodelist.render(context) class _TestState: pass def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_TestState, "saved_data"): # Executing this function twice would overwrite the saved values. raise RuntimeError( "setup_test_environment() was already called and can't be called " "again without first calling teardown_test_environment()." ) if debug is None: debug = settings.DEBUG saved_data = SimpleNamespace() _TestState.saved_data = saved_data saved_data.allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. settings.ALLOWED_HOSTS = [*settings.ALLOWED_HOSTS, "testserver"] saved_data.debug = settings.DEBUG settings.DEBUG = debug saved_data.email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" saved_data.template_render = Template._render Template._render = instrumented_test_render mail.outbox = [] deactivate() def teardown_test_environment(): """ Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions. """ saved_data = _TestState.saved_data settings.ALLOWED_HOSTS = saved_data.allowed_hosts settings.DEBUG = saved_data.debug settings.EMAIL_BACKEND = saved_data.email_backend Template._render = saved_data.template_render del _TestState.saved_data del mail.outbox def setup_databases( verbosity, interactive, *, time_keeper=None, keepdb=False, debug_sql=False, parallel=0, aliases=None, serialized_aliases=None, **kwargs, ): """Create the test databases.""" if time_keeper is None: time_keeper = NullTimeKeeper() test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) old_names = [] for db_name, aliases in test_databases.values(): first_alias = None for alias in aliases: connection = connections[alias] old_names.append((connection, db_name, first_alias is None)) # Actually create the database for the first connection if first_alias is None: first_alias = alias with time_keeper.timed(" Creating '%s'" % alias): # RemovedInDjango50Warning: when the deprecation ends, # replace with: # serialize_alias = ( # serialized_aliases is None # or alias in serialized_aliases # ) try: serialize_alias = connection.settings_dict["TEST"]["SERIALIZE"] except KeyError: serialize_alias = ( serialized_aliases is None or alias in serialized_aliases ) else: warnings.warn( "The SERIALIZE test database setting is " "deprecated as it can be inferred from the " "TestCase/TransactionTestCase.databases that " "enable the serialized_rollback feature.", category=RemovedInDjango50Warning, ) connection.creation.create_test_db( verbosity=verbosity, autoclobber=not interactive, keepdb=keepdb, serialize=serialize_alias, ) if parallel > 1: for index in range(parallel): with time_keeper.timed(" Cloning '%s'" % alias): connection.creation.clone_test_db( suffix=str(index + 1), verbosity=verbosity, keepdb=keepdb, ) # Configure all other connections as mirrors of the first one else: connections[alias].creation.set_as_test_mirror( connections[first_alias].settings_dict ) # Configure the test mirrors. for alias, mirror_alias in mirrored_aliases.items(): connections[alias].creation.set_as_test_mirror( connections[mirror_alias].settings_dict ) if debug_sql: for alias in connections: connections[alias].force_debug_cursor = True return old_names def iter_test_cases(tests): """ Return an iterator over a test suite's unittest.TestCase objects. The tests argument can also be an iterable of TestCase objects. """ for test in tests: if isinstance(test, str): # Prevent an unfriendly RecursionError that can happen with # strings. raise TypeError( f"Test {test!r} must be a test case or test suite not string " f"(was found in {tests!r})." ) if isinstance(test, TestCase): yield test else: # Otherwise, assume it is a test suite. yield from iter_test_cases(test) def dependency_ordered(test_databases, dependencies): """ Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES]. """ ordered_test_databases = [] resolved_databases = set() # Maps db signature to dependencies of all its aliases dependencies_map = {} # Check that no database depends on its own alias for sig, (_, aliases) in test_databases: all_deps = set() for alias in aliases: all_deps.update(dependencies.get(alias, [])) if not all_deps.isdisjoint(aliases): raise ImproperlyConfigured( "Circular dependency: databases %r depend on each other, " "but are aliases." % aliases ) dependencies_map[sig] = all_deps while test_databases: changed = False deferred = [] # Try to find a DB that has all its dependencies met for signature, (db_name, aliases) in test_databases: if dependencies_map[signature].issubset(resolved_databases): resolved_databases.update(aliases) ordered_test_databases.append((signature, (db_name, aliases))) changed = True else: deferred.append((signature, (db_name, aliases))) if not changed: raise ImproperlyConfigured("Circular dependency in TEST[DEPENDENCIES]") test_databases = deferred return ordered_test_databases def get_unique_databases_and_mirrors(aliases=None): """ Figure out which databases actually need to be created. Deduplicate entries in DATABASES that correspond the same database or are configured as test mirrors. Return two values: - test_databases: ordered mapping of signatures to (name, list of aliases) where all aliases share the same underlying database. - mirrored_aliases: mapping of mirror aliases to original aliases. """ if aliases is None: aliases = connections mirrored_aliases = {} test_databases = {} dependencies = {} default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() for alias in connections: connection = connections[alias] test_settings = connection.settings_dict["TEST"] if test_settings["MIRROR"]: # If the database is marked as a test mirror, save the alias. mirrored_aliases[alias] = test_settings["MIRROR"] elif alias in aliases: # Store a tuple with DB parameters that uniquely identify it. # If we have two aliases with the same values for that tuple, # we only need to create the test database once. item = test_databases.setdefault( connection.creation.test_db_signature(), (connection.settings_dict["NAME"], []), ) # The default database must be the first because data migrations # use the default alias by default. if alias == DEFAULT_DB_ALIAS: item[1].insert(0, alias) else: item[1].append(alias) if "DEPENDENCIES" in test_settings: dependencies[alias] = test_settings["DEPENDENCIES"] else: if ( alias != DEFAULT_DB_ALIAS and connection.creation.test_db_signature() != default_sig ): dependencies[alias] = test_settings.get( "DEPENDENCIES", [DEFAULT_DB_ALIAS] ) test_databases = dict(dependency_ordered(test_databases.items(), dependencies)) return test_databases, mirrored_aliases def teardown_databases(old_config, verbosity, parallel=0, keepdb=False): """Destroy all the non-mirror databases.""" for connection, old_name, destroy in old_config: if destroy: if parallel > 1: for index in range(parallel): connection.creation.destroy_test_db( suffix=str(index + 1), verbosity=verbosity, keepdb=keepdb, ) connection.creation.destroy_test_db(old_name, verbosity, keepdb) def get_runner(settings, test_runner_class=None): test_runner_class = test_runner_class or settings.TEST_RUNNER test_path = test_runner_class.split(".") # Allow for relative paths if len(test_path) > 1: test_module_name = ".".join(test_path[:-1]) else: test_module_name = "." test_module = __import__(test_module_name, {}, {}, test_path[-1]) return getattr(test_module, test_path[-1]) class TestContextDecorator: """ A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations. `attr_name`: attribute assigned the return value of enable() if used as a class decorator. `kwarg_name`: keyword argument passing the return value of enable() if used as a function decorator. """ def __init__(self, attr_name=None, kwarg_name=None): self.attr_name = attr_name self.kwarg_name = kwarg_name def enable(self): raise NotImplementedError def disable(self): raise NotImplementedError def __enter__(self): return self.enable() def __exit__(self, exc_type, exc_value, traceback): self.disable() def decorate_class(self, cls): if issubclass(cls, TestCase): decorated_setUp = cls.setUp def setUp(inner_self): context = self.enable() inner_self.addCleanup(self.disable) if self.attr_name: setattr(inner_self, self.attr_name, context) decorated_setUp(inner_self) cls.setUp = setUp return cls raise TypeError("Can only decorate subclasses of unittest.TestCase") def decorate_callable(self, func): if asyncio.iscoroutinefunction(func): # If the inner function is an async function, we must execute async # as well so that the `with` statement executes at the right time. @wraps(func) async def inner(*args, **kwargs): with self as context: if self.kwarg_name: kwargs[self.kwarg_name] = context return await func(*args, **kwargs) else: @wraps(func) def inner(*args, **kwargs): with self as context: if self.kwarg_name: kwargs[self.kwarg_name] = context return func(*args, **kwargs) return inner def __call__(self, decorated): if isinstance(decorated, type): return self.decorate_class(decorated) elif callable(decorated): return self.decorate_callable(decorated) raise TypeError("Cannot decorate object of type %s" % type(decorated)) class override_settings(TestContextDecorator): """ Act as either a decorator or a context manager. If it's a decorator, take a function and return a wrapped function. If it's a contextmanager, use it with the ``with`` statement. In either event, entering/exiting are called before and after, respectively, the function/block is executed. """ enable_exception = None def __init__(self, **kwargs): self.options = kwargs super().__init__() def enable(self): # Keep this code at the beginning to leave the settings unchanged # in case it raises an exception because INSTALLED_APPS is invalid. if "INSTALLED_APPS" in self.options: try: apps.set_installed_apps(self.options["INSTALLED_APPS"]) except Exception: apps.unset_installed_apps() raise override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) self.wrapped = settings._wrapped settings._wrapped = override for key, new_value in self.options.items(): try: setting_changed.send( sender=settings._wrapped.__class__, setting=key, value=new_value, enter=True, ) except Exception as exc: self.enable_exception = exc self.disable() def disable(self): if "INSTALLED_APPS" in self.options: apps.unset_installed_apps() settings._wrapped = self.wrapped del self.wrapped responses = [] for key in self.options: new_value = getattr(settings, key, None) responses_for_setting = setting_changed.send_robust( sender=settings._wrapped.__class__, setting=key, value=new_value, enter=False, ) responses.extend(responses_for_setting) if self.enable_exception is not None: exc = self.enable_exception self.enable_exception = None raise exc for _, response in responses: if isinstance(response, Exception): raise response def save_options(self, test_func): if test_func._overridden_settings is None: test_func._overridden_settings = self.options else: # Duplicate dict to prevent subclasses from altering their parent. test_func._overridden_settings = { **test_func._overridden_settings, **self.options, } def decorate_class(self, cls): from django.test import SimpleTestCase if not issubclass(cls, SimpleTestCase): raise ValueError( "Only subclasses of Django SimpleTestCase can be decorated " "with override_settings" ) self.save_options(cls) return cls class modify_settings(override_settings): """ Like override_settings, but makes it possible to append, prepend, or remove items instead of redefining the entire list. """ def __init__(self, *args, **kwargs): if args: # Hack used when instantiating from SimpleTestCase.setUpClass. assert not kwargs self.operations = args[0] else: assert not args self.operations = list(kwargs.items()) super(override_settings, self).__init__() def save_options(self, test_func): if test_func._modified_settings is None: test_func._modified_settings = self.operations else: # Duplicate list to prevent subclasses from altering their parent. test_func._modified_settings = ( list(test_func._modified_settings) + self.operations ) def enable(self): self.options = {} for name, operations in self.operations: try: # When called from SimpleTestCase.setUpClass, values may be # overridden several times; cumulate changes. value = self.options[name] except KeyError: value = list(getattr(settings, name, [])) for action, items in operations.items(): # items my be a single value or an iterable. if isinstance(items, str): items = [items] if action == "append": value = value + [item for item in items if item not in value] elif action == "prepend": value = [item for item in items if item not in value] + value elif action == "remove": value = [item for item in value if item not in items] else: raise ValueError("Unsupported action: %s" % action) self.options[name] = value super().enable() class override_system_checks(TestContextDecorator): """ Act as a decorator. Override list of registered system checks. Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app, you also need to exclude its system checks. """ def __init__(self, new_checks, deployment_checks=None): from django.core.checks.registry import registry self.registry = registry self.new_checks = new_checks self.deployment_checks = deployment_checks super().__init__() def enable(self): self.old_checks = self.registry.registered_checks self.registry.registered_checks = set() for check in self.new_checks: self.registry.register(check, *getattr(check, "tags", ())) self.old_deployment_checks = self.registry.deployment_checks if self.deployment_checks is not None: self.registry.deployment_checks = set() for check in self.deployment_checks: self.registry.register(check, *getattr(check, "tags", ()), deploy=True) def disable(self): self.registry.registered_checks = self.old_checks self.registry.deployment_checks = self.old_deployment_checks def compare_xml(want, got): """ Try to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Ignore comment nodes, processing instructions, document type node, and leading and trailing whitespaces. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py """ _norm_whitespace_re = re.compile(r"[ \t\n][ \t\n]+") def norm_whitespace(v): return _norm_whitespace_re.sub(" ", v) def child_text(element): return "".join( c.data for c in element.childNodes if c.nodeType == Node.TEXT_NODE ) def children(element): return [c for c in element.childNodes if c.nodeType == Node.ELEMENT_NODE] def norm_child_text(element): return norm_whitespace(child_text(element)) def attrs_dict(element): return dict(element.attributes.items()) def check_element(want_element, got_element): if want_element.tagName != got_element.tagName: return False if norm_child_text(want_element) != norm_child_text(got_element): return False if attrs_dict(want_element) != attrs_dict(got_element): return False want_children = children(want_element) got_children = children(got_element) if len(want_children) != len(got_children): return False return all( check_element(want, got) for want, got in zip(want_children, got_children) ) def first_node(document): for node in document.childNodes: if node.nodeType not in ( Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE, Node.PROCESSING_INSTRUCTION_NODE, ): return node want = want.strip().replace("\\n", "\n") got = got.strip().replace("\\n", "\n") # If the string is not a complete xml document, we may need to add a # root element. This allow us to compare fragments, like "<foo/><bar/>" if not want.startswith("<?xml"): wrapper = "<root>%s</root>" want = wrapper % want got = wrapper % got # Parse the want and got strings, and compare the parsings. want_root = first_node(parseString(want)) got_root = first_node(parseString(got)) return check_element(want_root, got_root) class CaptureQueriesContext: """ Context manager that captures queries executed by the specified connection. """ def __init__(self, connection): self.connection = connection def __iter__(self): return iter(self.captured_queries) def __getitem__(self, index): return self.captured_queries[index] def __len__(self): return len(self.captured_queries) @property def captured_queries(self): return self.connection.queries[self.initial_queries : self.final_queries] def __enter__(self): self.force_debug_cursor = self.connection.force_debug_cursor self.connection.force_debug_cursor = True # Run any initialization queries if needed so that they won't be # included as part of the count. self.connection.ensure_connection() self.initial_queries = len(self.connection.queries_log) self.final_queries = None request_started.disconnect(reset_queries) return self def __exit__(self, exc_type, exc_value, traceback): self.connection.force_debug_cursor = self.force_debug_cursor request_started.connect(reset_queries) if exc_type is not None: return self.final_queries = len(self.connection.queries_log) class ignore_warnings(TestContextDecorator): def __init__(self, **kwargs): self.ignore_kwargs = kwargs if "message" in self.ignore_kwargs or "module" in self.ignore_kwargs: self.filter_func = warnings.filterwarnings else: self.filter_func = warnings.simplefilter super().__init__() def enable(self): self.catch_warnings = warnings.catch_warnings() self.catch_warnings.__enter__() self.filter_func("ignore", **self.ignore_kwargs) def disable(self): self.catch_warnings.__exit__(*sys.exc_info()) # On OSes that don't provide tzset (Windows), we can't set the timezone # in which the program runs. As a consequence, we must skip tests that # don't enforce a specific timezone (with timezone.override or equivalent), # or attempt to interpret naive datetimes in the default timezone. requires_tz_support = skipUnless( TZ_SUPPORT, "This test relies on the ability to run a program in an arbitrary " "time zone, but your operating system isn't able to do that.", ) @contextmanager def extend_sys_path(*paths): """Context manager to temporarily add paths to sys.path.""" _orig_sys_path = sys.path[:] sys.path.extend(paths) try: yield finally: sys.path = _orig_sys_path @contextmanager def isolate_lru_cache(lru_cache_object): """Clear the cache of an LRU cache object on entering and exiting.""" lru_cache_object.cache_clear() try: yield finally: lru_cache_object.cache_clear() @contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Note: This function and the following ``captured_std*`` are copied from CPython's ``test.support`` module.""" orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, StringIO()) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") """ return captured_output("stdout") def captured_stderr(): """Capture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") """ return captured_output("stderr") def captured_stdin(): """Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello") """ return captured_output("stdin") @contextmanager def freeze_time(t): """ Context manager to temporarily freeze time.time(). This temporarily modifies the time function of the time module. Modules which import the time function directly (e.g. `from time import time`) won't be affected This isn't meant as a public API, but helps reduce some repetitive code in Django's test suite. """ _real_time = time.time time.time = lambda: t try: yield finally: time.time = _real_time def require_jinja2(test_func): """ Decorator to enable a Jinja2 template engine in addition to the regular Django template engine for a test or skip it if Jinja2 isn't available. """ test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func) return override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, }, { "BACKEND": "django.template.backends.jinja2.Jinja2", "APP_DIRS": True, "OPTIONS": {"keep_trailing_newline": True}, }, ] )(test_func) class override_script_prefix(TestContextDecorator): """Decorator or context manager to temporary override the script prefix.""" def __init__(self, prefix): self.prefix = prefix super().__init__() def enable(self): self.old_prefix = get_script_prefix() set_script_prefix(self.prefix) def disable(self): set_script_prefix(self.old_prefix) class LoggingCaptureMixin: """ Capture the output from the 'django' logger and store it on the class's logger_output attribute. """ def setUp(self): self.logger = logging.getLogger("django") self.old_stream = self.logger.handlers[0].stream self.logger_output = StringIO() self.logger.handlers[0].stream = self.logger_output def tearDown(self): self.logger.handlers[0].stream = self.old_stream class isolate_apps(TestContextDecorator): """ Act as either a decorator or a context manager to register models defined in its wrapped context to an isolated registry. The list of installed apps the isolated registry should contain must be passed as arguments. Two optional keyword arguments can be specified: `attr_name`: attribute assigned the isolated registry if used as a class decorator. `kwarg_name`: keyword argument passing the isolated registry if used as a function decorator. """ def __init__(self, *installed_apps, **kwargs): self.installed_apps = installed_apps super().__init__(**kwargs) def enable(self): self.old_apps = Options.default_apps apps = Apps(self.installed_apps) setattr(Options, "default_apps", apps) return apps def disable(self): setattr(Options, "default_apps", self.old_apps) class TimeKeeper: def __init__(self): self.records = collections.defaultdict(list) @contextmanager def timed(self, name): self.records[name] start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() - start_time self.records[name].append(end_time) def print_results(self): for name, end_times in self.records.items(): for record_time in end_times: record = "%s took %.3fs" % (name, record_time) sys.stderr.write(record + os.linesep) class NullTimeKeeper: @contextmanager def timed(self, name): yield def print_results(self): pass def tag(*tags): """Decorator to add tags to a test class or method.""" def decorator(obj): if hasattr(obj, "tags"): obj.tags = obj.tags.union(tags) else: setattr(obj, "tags", set(tags)) return obj return decorator @contextmanager def register_lookup(field, *lookups, lookup_name=None): """ Context manager to temporarily register lookups on a model field using lookup_name (or the lookup's lookup_name if not provided). """ try: for lookup in lookups: field.register_lookup(lookup, lookup_name) yield finally: for lookup in lookups: field._unregister_lookup(lookup, lookup_name)
efbdd61ae1bbf24e39075a87b5d22d53caa2d48a2db6fbe290a0fa8ae0bb86f5
import os import time import warnings from asgiref.local import Local from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.db import connections, router from django.db.utils import ConnectionRouter from django.dispatch import Signal, receiver from django.utils import timezone from django.utils.formats import FORMAT_SETTINGS, reset_format_cache from django.utils.functional import empty template_rendered = Signal() # Most setting_changed receivers are supposed to be added below, # except for cases where the receiver is related to a contrib app. # Settings that may not work well when using 'override_settings' (#19031) COMPLEX_OVERRIDE_SETTINGS = {"DATABASES"} @receiver(setting_changed) def clear_cache_handlers(*, setting, **kwargs): if setting == "CACHES": from django.core.cache import caches, close_caches close_caches() caches._settings = caches.settings = caches.configure_settings(None) caches._connections = Local() @receiver(setting_changed) def update_installed_apps(*, setting, **kwargs): if setting == "INSTALLED_APPS": # Rebuild any AppDirectoriesFinder instance. from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() # Rebuild management commands cache from django.core.management import get_commands get_commands.cache_clear() # Rebuild get_app_template_dirs cache. from django.template.utils import get_app_template_dirs get_app_template_dirs.cache_clear() # Rebuild translations cache. from django.utils.translation import trans_real trans_real._translations = {} @receiver(setting_changed) def update_connections_time_zone(*, setting, **kwargs): if setting == "TIME_ZONE": # Reset process time zone if hasattr(time, "tzset"): if kwargs["value"]: os.environ["TZ"] = kwargs["value"] else: os.environ.pop("TZ", None) time.tzset() # Reset local time zone cache timezone.get_default_timezone.cache_clear() # Reset the database connections' time zone if setting in {"TIME_ZONE", "USE_TZ"}: for conn in connections.all(): try: del conn.timezone except AttributeError: pass try: del conn.timezone_name except AttributeError: pass conn.ensure_timezone() @receiver(setting_changed) def clear_routers_cache(*, setting, **kwargs): if setting == "DATABASE_ROUTERS": router.routers = ConnectionRouter().routers @receiver(setting_changed) def reset_template_engines(*, setting, **kwargs): if setting in { "TEMPLATES", "DEBUG", "INSTALLED_APPS", }: from django.template import engines try: del engines.templates except AttributeError: pass engines._templates = None engines._engines = {} from django.template.engine import Engine Engine.get_default.cache_clear() from django.forms.renderers import get_default_renderer get_default_renderer.cache_clear() @receiver(setting_changed) def clear_serializers_cache(*, setting, **kwargs): if setting == "SERIALIZATION_MODULES": from django.core import serializers serializers._serializers = {} @receiver(setting_changed) def language_changed(*, setting, **kwargs): if setting in {"LANGUAGES", "LANGUAGE_CODE", "LOCALE_PATHS"}: from django.utils.translation import trans_real trans_real._default = None trans_real._active = Local() if setting in {"LANGUAGES", "LOCALE_PATHS"}: from django.utils.translation import trans_real trans_real._translations = {} trans_real.check_for_language.cache_clear() @receiver(setting_changed) def localize_settings_changed(*, setting, **kwargs): if setting in FORMAT_SETTINGS or setting == "USE_THOUSAND_SEPARATOR": reset_format_cache() @receiver(setting_changed) def file_storage_changed(*, setting, **kwargs): if setting == "DEFAULT_FILE_STORAGE": from django.core.files.storage import default_storage default_storage._wrapped = empty @receiver(setting_changed) def complex_setting_changed(*, enter, setting, **kwargs): if enter and setting in COMPLEX_OVERRIDE_SETTINGS: # Considering the current implementation of the signals framework, # this stacklevel shows the line containing the override_settings call. warnings.warn( f"Overriding setting {setting} can lead to unexpected behavior.", stacklevel=6, ) @receiver(setting_changed) def root_urlconf_changed(*, setting, **kwargs): if setting == "ROOT_URLCONF": from django.urls import clear_url_caches, set_urlconf clear_url_caches() set_urlconf(None) @receiver(setting_changed) def static_storage_changed(*, setting, **kwargs): if setting in { "STATICFILES_STORAGE", "STATIC_ROOT", "STATIC_URL", }: from django.contrib.staticfiles.storage import staticfiles_storage staticfiles_storage._wrapped = empty @receiver(setting_changed) def static_finders_changed(*, setting, **kwargs): if setting in { "STATICFILES_DIRS", "STATIC_ROOT", }: from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() @receiver(setting_changed) def auth_password_validators_changed(*, setting, **kwargs): if setting == "AUTH_PASSWORD_VALIDATORS": from django.contrib.auth.password_validation import ( get_default_password_validators, ) get_default_password_validators.cache_clear() @receiver(setting_changed) def user_model_swapped(*, setting, **kwargs): if setting == "AUTH_USER_MODEL": apps.clear_cache() try: from django.contrib.auth import get_user_model UserModel = get_user_model() except ImproperlyConfigured: # Some tests set an invalid AUTH_USER_MODEL. pass else: from django.contrib.auth import backends backends.UserModel = UserModel from django.contrib.auth import forms forms.UserModel = UserModel from django.contrib.auth.handlers import modwsgi modwsgi.UserModel = UserModel from django.contrib.auth.management.commands import changepassword changepassword.UserModel = UserModel from django.contrib.auth import views views.UserModel = UserModel
d2922d2c53f4830fc43dba9e19dbd56d291896378ae94553da12f4787ef20dd8
import functools import sys import threading import warnings from collections import Counter, defaultdict from functools import partial from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured from .config import AppConfig class Apps: """ A registry that stores the configuration of installed applications. It also keeps track of models, e.g. to provide reverse relations. """ def __init__(self, installed_apps=()): # installed_apps is set to None when creating the master registry # because it cannot be populated at that point. Other registries must # provide a list of installed apps and are populated immediately. if installed_apps is None and hasattr(sys.modules[__name__], "apps"): raise RuntimeError("You must supply an installed_apps argument.") # Mapping of app labels => model names => model classes. Every time a # model is imported, ModelBase.__new__ calls apps.register_model which # creates an entry in all_models. All imported models are registered, # regardless of whether they're defined in an installed application # and whether the registry has been populated. Since it isn't possible # to reimport a module safely (it could reexecute initialization code) # all_models is never overridden or reset. self.all_models = defaultdict(dict) # Mapping of labels to AppConfig instances for installed apps. self.app_configs = {} # Stack of app_configs. Used to store the current state in # set_available_apps and set_installed_apps. self.stored_app_configs = [] # Whether the registry is populated. self.apps_ready = self.models_ready = self.ready = False # For the autoreloader. self.ready_event = threading.Event() # Lock for thread-safe population. self._lock = threading.RLock() self.loading = False # Maps ("app_label", "modelname") tuples to lists of functions to be # called when the corresponding model is ready. Used by this class's # `lazy_model_operation()` and `do_pending_operations()` methods. self._pending_operations = defaultdict(list) # Populate apps and models, unless it's the master registry. if installed_apps is not None: self.populate(installed_apps) def populate(self, installed_apps=None): """ Load application configurations and models. Import each application module and then each model module. It is thread-safe and idempotent, but not reentrant. """ if self.ready: return # populate() might be called by two threads in parallel on servers # that create threads before initializing the WSGI callable. with self._lock: if self.ready: return # An RLock prevents other threads from entering this section. The # compare and set operation below is atomic. if self.loading: # Prevent reentrant calls to avoid running AppConfig.ready() # methods twice. raise RuntimeError("populate() isn't reentrant") self.loading = True # Phase 1: initialize app configs and import app modules. for entry in installed_apps: if isinstance(entry, AppConfig): app_config = entry else: app_config = AppConfig.create(entry) if app_config.label in self.app_configs: raise ImproperlyConfigured( "Application labels aren't unique, " "duplicates: %s" % app_config.label ) self.app_configs[app_config.label] = app_config app_config.apps = self # Check for duplicate app names. counts = Counter( app_config.name for app_config in self.app_configs.values() ) duplicates = [name for name, count in counts.most_common() if count > 1] if duplicates: raise ImproperlyConfigured( "Application names aren't unique, " "duplicates: %s" % ", ".join(duplicates) ) self.apps_ready = True # Phase 2: import models modules. for app_config in self.app_configs.values(): app_config.import_models() self.clear_cache() self.models_ready = True # Phase 3: run ready() methods of app configs. for app_config in self.get_app_configs(): app_config.ready() self.ready = True self.ready_event.set() def check_apps_ready(self): """Raise an exception if all apps haven't been imported yet.""" if not self.apps_ready: from django.conf import settings # If "not ready" is due to unconfigured settings, accessing # INSTALLED_APPS raises a more helpful ImproperlyConfigured # exception. settings.INSTALLED_APPS raise AppRegistryNotReady("Apps aren't loaded yet.") def check_models_ready(self): """Raise an exception if all models haven't been imported yet.""" if not self.models_ready: raise AppRegistryNotReady("Models aren't loaded yet.") def get_app_configs(self): """Import applications and return an iterable of app configs.""" self.check_apps_ready() return self.app_configs.values() def get_app_config(self, app_label): """ Import applications and returns an app config for the given label. Raise LookupError if no application exists with this label. """ self.check_apps_ready() try: return self.app_configs[app_label] except KeyError: message = "No installed app with label '%s'." % app_label for app_config in self.get_app_configs(): if app_config.name == app_label: message += " Did you mean '%s'?" % app_config.label break raise LookupError(message) # This method is performance-critical at least for Django's test suite. @functools.lru_cache(maxsize=None) def get_models(self, include_auto_created=False, include_swapped=False): """ Return a list of all installed models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models that have been swapped out. Set the corresponding keyword argument to True to include such models. """ self.check_models_ready() result = [] for app_config in self.app_configs.values(): result.extend(app_config.get_models(include_auto_created, include_swapped)) return result def get_model(self, app_label, model_name=None, require_ready=True): """ Return the model matching the given app_label and model_name. As a shortcut, app_label may be in the form <app_label>.<model_name>. model_name is case-insensitive. Raise LookupError if no application exists with this label, or no model exists with this name in the application. Raise ValueError if called with a single argument that doesn't contain exactly one dot. """ if require_ready: self.check_models_ready() else: self.check_apps_ready() if model_name is None: app_label, model_name = app_label.split(".") app_config = self.get_app_config(app_label) if not require_ready and app_config.models is None: app_config.import_models() return app_config.get_model(model_name, require_ready=require_ready) def register_model(self, app_label, model): # Since this method is called when models are imported, it cannot # perform imports because of the risk of import loops. It mustn't # call get_app_config(). model_name = model._meta.model_name app_models = self.all_models[app_label] if model_name in app_models: if ( model.__name__ == app_models[model_name].__name__ and model.__module__ == app_models[model_name].__module__ ): warnings.warn( "Model '%s.%s' was already registered. Reloading models is not " "advised as it can lead to inconsistencies, most notably with " "related models." % (app_label, model_name), RuntimeWarning, stacklevel=2, ) else: raise RuntimeError( "Conflicting '%s' models in application '%s': %s and %s." % (model_name, app_label, app_models[model_name], model) ) app_models[model_name] = model self.do_pending_operations(model) self.clear_cache() def is_installed(self, app_name): """ Check whether an application with this name exists in the registry. app_name is the full name of the app e.g. 'django.contrib.admin'. """ self.check_apps_ready() return any(ac.name == app_name for ac in self.app_configs.values()) def get_containing_app_config(self, object_name): """ Look for an app config containing a given object. object_name is the dotted Python path to the object. Return the app config for the inner application in case of nesting. Return None if the object isn't in any registered app config. """ self.check_apps_ready() candidates = [] for app_config in self.app_configs.values(): if object_name.startswith(app_config.name): subpath = object_name[len(app_config.name) :] if subpath == "" or subpath[0] == ".": candidates.append(app_config) if candidates: return sorted(candidates, key=lambda ac: -len(ac.name))[0] def get_registered_model(self, app_label, model_name): """ Similar to get_model(), but doesn't require that an app exists with the given app_label. It's safe to call this method at import time, even while the registry is being populated. """ model = self.all_models[app_label].get(model_name.lower()) if model is None: raise LookupError("Model '%s.%s' not registered." % (app_label, model_name)) return model @functools.lru_cache(maxsize=None) def get_swappable_settings_name(self, to_string): """ For a given model string (e.g. "auth.User"), return the name of the corresponding settings name if it refers to a swappable model. If the referred model is not swappable, return None. This method is decorated with lru_cache because it's performance critical when it comes to migrations. Since the swappable settings don't change after Django has loaded the settings, there is no reason to get the respective settings attribute over and over again. """ to_string = to_string.lower() for model in self.get_models(include_swapped=True): swapped = model._meta.swapped # Is this model swapped out for the model given by to_string? if swapped and swapped.lower() == to_string: return model._meta.swappable # Is this model swappable and the one given by to_string? if model._meta.swappable and model._meta.label_lower == to_string: return model._meta.swappable return None def set_available_apps(self, available): """ Restrict the set of installed apps used by get_app_config[s]. available must be an iterable of application names. set_available_apps() must be balanced with unset_available_apps(). Primarily used for performance optimization in TransactionTestCase. This method is safe in the sense that it doesn't trigger any imports. """ available = set(available) installed = {app_config.name for app_config in self.get_app_configs()} if not available.issubset(installed): raise ValueError( "Available apps isn't a subset of installed apps, extra apps: %s" % ", ".join(available - installed) ) self.stored_app_configs.append(self.app_configs) self.app_configs = { label: app_config for label, app_config in self.app_configs.items() if app_config.name in available } self.clear_cache() def unset_available_apps(self): """Cancel a previous call to set_available_apps().""" self.app_configs = self.stored_app_configs.pop() self.clear_cache() def set_installed_apps(self, installed): """ Enable a different set of installed apps for get_app_config[s]. installed must be an iterable in the same format as INSTALLED_APPS. set_installed_apps() must be balanced with unset_installed_apps(), even if it exits with an exception. Primarily used as a receiver of the setting_changed signal in tests. This method may trigger new imports, which may add new models to the registry of all imported models. They will stay in the registry even after unset_installed_apps(). Since it isn't possible to replay imports safely (e.g. that could lead to registering listeners twice), models are registered when they're imported and never removed. """ if not self.ready: raise AppRegistryNotReady("App registry isn't ready yet.") self.stored_app_configs.append(self.app_configs) self.app_configs = {} self.apps_ready = self.models_ready = self.loading = self.ready = False self.clear_cache() self.populate(installed) def unset_installed_apps(self): """Cancel a previous call to set_installed_apps().""" self.app_configs = self.stored_app_configs.pop() self.apps_ready = self.models_ready = self.ready = True self.clear_cache() def clear_cache(self): """ Clear all internal caches, for methods that alter the app registry. This is mostly used in tests. """ # Call expire cache on each model. This will purge # the relation tree and the fields cache. self.get_models.cache_clear() if self.ready: # Circumvent self.get_models() to prevent that the cache is refilled. # This particularly prevents that an empty value is cached while cloning. for app_config in self.app_configs.values(): for model in app_config.get_models(include_auto_created=True): model._meta._expire_cache() def lazy_model_operation(self, function, *model_keys): """ Take a function and a number of ("app_label", "modelname") tuples, and when all the corresponding models have been imported and registered, call the function with the model classes as its arguments. The function passed to this method must accept exactly n models as arguments, where n=len(model_keys). """ # Base case: no arguments, just execute the function. if not model_keys: function() # Recursive case: take the head of model_keys, wait for the # corresponding model class to be imported and registered, then apply # that argument to the supplied function. Pass the resulting partial # to lazy_model_operation() along with the remaining model args and # repeat until all models are loaded and all arguments are applied. else: next_model, *more_models = model_keys # This will be executed after the class corresponding to next_model # has been imported and registered. The `func` attribute provides # duck-type compatibility with partials. def apply_next_model(model): next_function = partial(apply_next_model.func, model) self.lazy_model_operation(next_function, *more_models) apply_next_model.func = function # If the model has already been imported and registered, partially # apply it to the function now. If not, add it to the list of # pending operations for the model, where it will be executed with # the model class as its sole argument once the model is ready. try: model_class = self.get_registered_model(*next_model) except LookupError: self._pending_operations[next_model].append(apply_next_model) else: apply_next_model(model_class) def do_pending_operations(self, model): """ Take a newly-prepared model and pass it to each function waiting for it. This is called at the very end of Apps.register_model(). """ key = model._meta.app_label, model._meta.model_name for function in self._pending_operations.pop(key, []): function(model) apps = Apps(installed_apps=None)
f1665323f26736e3f8b727ee8a61f7fe929061b0c0cb685aabec64413d545e47
from .config import AppConfig from .registry import apps __all__ = ["AppConfig", "apps"]
d59871b783abc119ce9ac4ff07f06eac89b3de88bcdf7d13246d2b451279f1b4
import inspect import os from importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.utils.functional import cached_property from django.utils.module_loading import import_string, module_has_submodule APPS_MODULE_NAME = "apps" MODELS_MODULE_NAME = "models" class AppConfig: """Class representing a Django application and its configuration.""" def __init__(self, app_name, app_module): # Full Python path to the application e.g. 'django.contrib.admin'. self.name = app_name # Root module for the application e.g. <module 'django.contrib.admin' # from 'django/contrib/admin/__init__.py'>. self.module = app_module # Reference to the Apps registry that holds this AppConfig. Set by the # registry when it registers the AppConfig instance. self.apps = None # The following attributes could be defined at the class level in a # subclass, hence the test-and-set pattern. # Last component of the Python path to the application e.g. 'admin'. # This value must be unique across a Django project. if not hasattr(self, "label"): self.label = app_name.rpartition(".")[2] if not self.label.isidentifier(): raise ImproperlyConfigured( "The app label '%s' is not a valid Python identifier." % self.label ) # Human-readable name for the application e.g. "Admin". if not hasattr(self, "verbose_name"): self.verbose_name = self.label.title() # Filesystem path to the application directory e.g. # '/path/to/django/contrib/admin'. if not hasattr(self, "path"): self.path = self._path_from_module(app_module) # Module containing models e.g. <module 'django.contrib.admin.models' # from 'django/contrib/admin/models.py'>. Set by import_models(). # None if the application doesn't have a models module. self.models_module = None # Mapping of lowercase model names to model classes. Initially set to # None to prevent accidental access before import_models() runs. self.models = None def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.label) @cached_property def default_auto_field(self): from django.conf import settings return settings.DEFAULT_AUTO_FIELD @property def _is_default_auto_field_overridden(self): return self.__class__.default_auto_field is not AppConfig.default_auto_field def _path_from_module(self, module): """Attempt to determine app's filesystem path from its module.""" # See #21874 for extended discussion of the behavior of this method in # various cases. # Convert to list because __path__ may not support indexing. paths = list(getattr(module, "__path__", [])) if len(paths) != 1: filename = getattr(module, "__file__", None) if filename is not None: paths = [os.path.dirname(filename)] else: # For unknown reasons, sometimes the list returned by __path__ # contains duplicates that must be removed (#25246). paths = list(set(paths)) if len(paths) > 1: raise ImproperlyConfigured( "The app module %r has multiple filesystem locations (%r); " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % (module, paths) ) elif not paths: raise ImproperlyConfigured( "The app module %r has no filesystem location, " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % module ) return paths[0] @classmethod def create(cls, entry): """ Factory that creates an app config from an entry in INSTALLED_APPS. """ # create() eventually returns app_config_class(app_name, app_module). app_config_class = None app_name = None app_module = None # If import_module succeeds, entry points to the app module. try: app_module = import_module(entry) except Exception: pass else: # If app_module has an apps submodule that defines a single # AppConfig subclass, use it automatically. # To prevent this, an AppConfig subclass can declare a class # variable default = False. # If the apps module defines more than one AppConfig subclass, # the default one can declare default = True. if module_has_submodule(app_module, APPS_MODULE_NAME): mod_path = "%s.%s" % (entry, APPS_MODULE_NAME) mod = import_module(mod_path) # Check if there's exactly one AppConfig candidate, # excluding those that explicitly define default = False. app_configs = [ (name, candidate) for name, candidate in inspect.getmembers(mod, inspect.isclass) if ( issubclass(candidate, cls) and candidate is not cls and getattr(candidate, "default", True) ) ] if len(app_configs) == 1: app_config_class = app_configs[0][1] else: # Check if there's exactly one AppConfig subclass, # among those that explicitly define default = True. app_configs = [ (name, candidate) for name, candidate in app_configs if getattr(candidate, "default", False) ] if len(app_configs) > 1: candidates = [repr(name) for name, _ in app_configs] raise RuntimeError( "%r declares more than one default AppConfig: " "%s." % (mod_path, ", ".join(candidates)) ) elif len(app_configs) == 1: app_config_class = app_configs[0][1] # Use the default app config class if we didn't find anything. if app_config_class is None: app_config_class = cls app_name = entry # If import_string succeeds, entry is an app config class. if app_config_class is None: try: app_config_class = import_string(entry) except Exception: pass # If both import_module and import_string failed, it means that entry # doesn't have a valid value. if app_module is None and app_config_class is None: # If the last component of entry starts with an uppercase letter, # then it was likely intended to be an app config class; if not, # an app module. Provide a nice error message in both cases. mod_path, _, cls_name = entry.rpartition(".") if mod_path and cls_name[0].isupper(): # We could simply re-trigger the string import exception, but # we're going the extra mile and providing a better error # message for typos in INSTALLED_APPS. # This may raise ImportError, which is the best exception # possible if the module at mod_path cannot be imported. mod = import_module(mod_path) candidates = [ repr(name) for name, candidate in inspect.getmembers(mod, inspect.isclass) if issubclass(candidate, cls) and candidate is not cls ] msg = "Module '%s' does not contain a '%s' class." % ( mod_path, cls_name, ) if candidates: msg += " Choices are: %s." % ", ".join(candidates) raise ImportError(msg) else: # Re-trigger the module import exception. import_module(entry) # Check for obvious errors. (This check prevents duck typing, but # it could be removed if it became a problem in practice.) if not issubclass(app_config_class, AppConfig): raise ImproperlyConfigured("'%s' isn't a subclass of AppConfig." % entry) # Obtain app name here rather than in AppClass.__init__ to keep # all error checking for entries in INSTALLED_APPS in one place. if app_name is None: try: app_name = app_config_class.name except AttributeError: raise ImproperlyConfigured("'%s' must supply a name attribute." % entry) # Ensure app_name points to a valid module. try: app_module = import_module(app_name) except ImportError: raise ImproperlyConfigured( "Cannot import '%s'. Check that '%s.%s.name' is correct." % ( app_name, app_config_class.__module__, app_config_class.__qualname__, ) ) # Entry is a path to an app config class. return app_config_class(app_name, app_module) def get_model(self, model_name, require_ready=True): """ Return the model with the given case-insensitive model_name. Raise LookupError if no model exists with this name. """ if require_ready: self.apps.check_models_ready() else: self.apps.check_apps_ready() try: return self.models[model_name.lower()] except KeyError: raise LookupError( "App '%s' doesn't have a '%s' model." % (self.label, model_name) ) def get_models(self, include_auto_created=False, include_swapped=False): """ Return an iterable of models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models that have been swapped out. Set the corresponding keyword argument to True to include such models. Keyword arguments aren't documented; they're a private API. """ self.apps.check_models_ready() for model in self.models.values(): if model._meta.auto_created and not include_auto_created: continue if model._meta.swapped and not include_swapped: continue yield model def import_models(self): # Dictionary of models for this app, primarily maintained in the # 'all_models' attribute of the Apps this AppConfig is attached to. self.models = self.apps.all_models[self.label] if module_has_submodule(self.module, MODELS_MODULE_NAME): models_module_name = "%s.%s" % (self.name, MODELS_MODULE_NAME) self.models_module = import_module(models_module_name) def ready(self): """ Override this method in subclasses to run code when Django starts. """
188aba08a50109b1a9415c8ae312286805033eb991bdb04f497fca48793405be
from django.views.generic.base import View __all__ = ["View"]
f0a93011aca207c40a0703fe7943a9b204e94c644c3c16ac708656557cff882f
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import mimetypes import posixpath import re from pathlib import Path from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path).lstrip("/") fullpath = Path(safe_join(document_root, path)) if fullpath.is_dir(): if show_indexes: return directory_index(path, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not fullpath.exists(): raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) # Respect the If-Modified-Since header. statobj = fullpath.stat() if not was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime, statobj.st_size ): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(str(fullpath)) content_type = content_type or "application/octet-stream" response = FileResponse(fullpath.open("rb"), content_type=content_type) response.headers["Last-Modified"] = http_date(statobj.st_mtime) if encoding: response.headers["Content-Encoding"] = encoding return response DEFAULT_DIRECTORY_INDEX_TEMPLATE = """ {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Language" content="en-us"> <meta name="robots" content="NONE,NOARCHIVE"> <title>{% blocktranslate %}Index of {{ directory }}{% endblocktranslate %}</title> </head> <body> <h1>{% blocktranslate %}Index of {{ directory }}{% endblocktranslate %}</h1> <ul> {% if directory != "/" %} <li><a href="../">../</a></li> {% endif %} {% for f in file_list %} <li><a href="{{ f|urlencode }}">{{ f }}</a></li> {% endfor %} </ul> </body> </html> """ template_translatable = gettext_lazy("Index of %(directory)s") def directory_index(path, fullpath): try: t = loader.select_template( [ "static/directory_index.html", "static/directory_index", ] ) except TemplateDoesNotExist: t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string( DEFAULT_DIRECTORY_INDEX_TEMPLATE ) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith("."): url = str(f.relative_to(fullpath)) if f.is_dir(): url += "/" files.append(url) c.update( { "directory": path + "/", "file_list": files, } ) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0, size=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. size This is the size of the item we're talking about. """ try: if header is None: raise ValueError matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE) header_mtime = parse_http_date(matches[1]) header_len = matches[3] if header_len and int(header_len) != size: raise ValueError if int(mtime) > header_mtime: raise ValueError except (AttributeError, ValueError, OverflowError): return True return False
2f9e249d97a78512b5b0b5ef8c32f123b8e3c2a6255be802f05484d05b1d5c92
import itertools import json import os import re from django.apps import apps from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.template import Context, Engine from django.urls import translate_url from django.utils.formats import get_format from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import check_for_language, get_language from django.utils.translation.trans_real import DjangoTranslation from django.views.generic import View LANGUAGE_QUERY_PARAMETER = "language" def set_language(request): """ Redirect to a given URL while setting the chosen language in the session (if enabled) and in a cookie. The URL and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next_url = request.POST.get("next", request.GET.get("next")) if ( next_url or request.accepts("text/html") ) and not url_has_allowed_host_and_scheme( url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): next_url = request.META.get("HTTP_REFERER") if not url_has_allowed_host_and_scheme( url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): next_url = "/" response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204) if request.method == "POST": lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): if next_url: next_trans = translate_url(next_url, lang_code) if next_trans != next_url: response = HttpResponseRedirect(next_trans) response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, secure=settings.LANGUAGE_COOKIE_SECURE, httponly=settings.LANGUAGE_COOKIE_HTTPONLY, samesite=settings.LANGUAGE_COOKIE_SAMESITE, ) return response def get_formats(): """Return all formats strings required for i18n to work.""" FORMAT_SETTINGS = ( "DATE_FORMAT", "DATETIME_FORMAT", "TIME_FORMAT", "YEAR_MONTH_FORMAT", "MONTH_DAY_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "FIRST_DAY_OF_WEEK", "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ) return {attr: get_format(attr) for attr in FORMAT_SETTINGS} js_catalog_template = r""" {% autoescape off %} 'use strict'; { const globals = this; const django = globals.django || (globals.django = {}); {% if plural %} django.pluralidx = function(n) { const v = {{ plural }}; if (typeof v === 'boolean') { return v ? 1 : 0; } else { return v; } }; {% else %} django.pluralidx = function(count) { return (count == 1) ? 0 : 1; }; {% endif %} /* gettext library */ django.catalog = django.catalog || {}; {% if catalog_str %} const newcatalog = {{ catalog_str }}; for (const key in newcatalog) { django.catalog[key] = newcatalog[key]; } {% endif %} if (!django.jsi18n_initialized) { django.gettext = function(msgid) { const value = django.catalog[msgid]; if (typeof value === 'undefined') { return msgid; } else { return (typeof value === 'string') ? value : value[0]; } }; django.ngettext = function(singular, plural, count) { const value = django.catalog[singular]; if (typeof value === 'undefined') { return (count == 1) ? singular : plural; } else { return value.constructor === Array ? value[django.pluralidx(count)] : value; } }; django.gettext_noop = function(msgid) { return msgid; }; django.pgettext = function(context, msgid) { let value = django.gettext(context + '\x04' + msgid); if (value.includes('\x04')) { value = msgid; } return value; }; django.npgettext = function(context, singular, plural, count) { let value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count); if (value.includes('\x04')) { value = django.ngettext(singular, plural, count); } return value; }; django.interpolate = function(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } }; /* formatting library */ django.formats = {{ formats_str }}; django.get_format = function(format_type) { const value = django.formats[format_type]; if (typeof value === 'undefined') { return format_type; } else { return value; } }; /* add to global namespace */ globals.pluralidx = django.pluralidx; globals.gettext = django.gettext; globals.ngettext = django.ngettext; globals.gettext_noop = django.gettext_noop; globals.pgettext = django.pgettext; globals.npgettext = django.npgettext; globals.interpolate = django.interpolate; globals.get_format = django.get_format; django.jsi18n_initialized = true; } }; {% endautoescape %} """ # NOQA class JavaScriptCatalog(View): """ Return the selected language catalog as a JavaScript library. Receive the list of packages to check for translations in the `packages` kwarg either from the extra dictionary passed to the path() function or as a plus-sign delimited string from the request. Default is 'django.conf'. You can override the gettext domain for this view, but usually you don't want to do that as JavaScript messages go to the djangojs domain. This might be needed if you deliver your JavaScript source from Django templates. """ domain = "djangojs" packages = None def get(self, request, *args, **kwargs): locale = get_language() domain = kwargs.get("domain", self.domain) # If packages are not provided, default to all installed packages, as # DjangoTranslation without localedirs harvests them all. packages = kwargs.get("packages", "") packages = packages.split("+") if packages else self.packages paths = self.get_paths(packages) if packages else None self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) context = self.get_context_data(**kwargs) return self.render_to_response(context) def get_paths(self, packages): allowable_packages = { app_config.name: app_config for app_config in apps.get_app_configs() } app_configs = [ allowable_packages[p] for p in packages if p in allowable_packages ] if len(app_configs) < len(packages): excluded = [p for p in packages if p not in allowable_packages] raise ValueError( "Invalid package(s) provided to JavaScriptCatalog: %s" % ",".join(excluded) ) # paths of requested packages return [os.path.join(app.path, "locale") for app in app_configs] @property def _num_plurals(self): """ Return the number of plurals for this catalog language, or 2 if no plural string is available. """ match = re.search(r"nplurals=\s*(\d+)", self._plural_string or "") if match: return int(match[1]) return 2 @property def _plural_string(self): """ Return the plural string (including nplurals) for this catalog language, or None if no plural string is available. """ if "" in self.translation._catalog: for line in self.translation._catalog[""].split("\n"): if line.startswith("Plural-Forms:"): return line.split(":", 1)[1].strip() return None def get_plural(self): plural = self._plural_string if plural is not None: # This should be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : # n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; plural = [ el.strip() for el in plural.split(";") if el.strip().startswith("plural=") ][0].split("=", 1)[1] return plural def get_catalog(self): pdict = {} num_plurals = self._num_plurals catalog = {} trans_cat = self.translation._catalog trans_fallback_cat = ( self.translation._fallback._catalog if self.translation._fallback else {} ) seen_keys = set() for key, value in itertools.chain( trans_cat.items(), trans_fallback_cat.items() ): if key == "" or key in seen_keys: continue if isinstance(key, str): catalog[key] = value elif isinstance(key, tuple): msgid, cnt = key pdict.setdefault(msgid, {})[cnt] = value else: raise TypeError(key) seen_keys.add(key) for k, v in pdict.items(): catalog[k] = [v.get(i, "") for i in range(num_plurals)] return catalog def get_context_data(self, **kwargs): return { "catalog": self.get_catalog(), "formats": get_formats(), "plural": self.get_plural(), } def render_to_response(self, context, **response_kwargs): def indent(s): return s.replace("\n", "\n ") template = Engine().from_string(js_catalog_template) context["catalog_str"] = ( indent(json.dumps(context["catalog"], sort_keys=True, indent=2)) if context["catalog"] else None ) context["formats_str"] = indent( json.dumps(context["formats"], sort_keys=True, indent=2) ) return HttpResponse( template.render(Context(context)), 'text/javascript; charset="utf-8"' ) class JSONCatalog(JavaScriptCatalog): """ Return the selected language catalog as a JSON object. Receive the same parameters as JavaScriptCatalog and return a response with a JSON object of the following format: { "catalog": { # Translations catalog }, "formats": { # Language formats for date, time, etc. }, "plural": '...' # Expression for plural forms, or null. } """ def render_to_response(self, context, **response_kwargs): return JsonResponse(context)
1fbe36ba40d081017d99c28a68764f03a5e4f8e66b0e40d4c3f27f5cc4a3d73f
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = "404.html" ERROR_403_TEMPLATE_NAME = "403.html" ERROR_400_TEMPLATE_NAME = "400.html" ERROR_500_TEMPLATE_NAME = "500.html" ERROR_PAGE_TEMPLATE = """ <!doctype html> <html lang="en"> <head> <title>%(title)s</title> </head> <body> <h1>%(title)s</h1><p>%(details)s</p> </body> </html> """ # These views can be called when CsrfViewMiddleware.process_view() not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, str): exception_repr = message context = { "request_path": quote(request.path), "exception": exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use 'text/html'. except TemplateDoesNotExist: if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise # Render template (even though there are no substitutions) to allow # inspecting the context in tests. template = Engine().from_string( ERROR_PAGE_TEMPLATE % { "title": "Not Found", "details": "The requested resource was not found on this server.", }, ) body = template.render(Context(context)) content_type = "text/html" return HttpResponseNotFound(body, content_type=content_type) @requires_csrf_token def server_error(request, template_name=ERROR_500_TEMPLATE_NAME): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_500_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return HttpResponseServerError( ERROR_PAGE_TEMPLATE % {"title": "Server Error (500)", "details": ""}, content_type="text/html", ) return HttpResponseServerError(template.render()) @requires_csrf_token def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME): """ 400 error handler. Templates: :template:`400.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_400_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return HttpResponseBadRequest( ERROR_PAGE_TEMPLATE % {"title": "Bad Request (400)", "details": ""}, content_type="text/html", ) # No exception content is passed to the template, to not disclose any # sensitive information. return HttpResponseBadRequest(template.render()) @requires_csrf_token def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME): """ Permission denied (403) handler. Templates: :template:`403.html` Context: exception The message from the exception which triggered the 403 (if one was supplied). If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 7231) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_403_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return HttpResponseForbidden( ERROR_PAGE_TEMPLATE % {"title": "403 Forbidden", "details": ""}, content_type="text/html", ) return HttpResponseForbidden( template.render(request=request, context={"exception": str(exception)}) )
c8c2e42c1e987a9b1e7335c9cf07ddd53a04b8e90fa1558ebd2aa3c8ec6cb59e
import functools import re import sys import types import warnings from pathlib import Path from django.conf import settings from django.http import Http404, HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import pprint from django.urls import resolve from django.utils import timezone from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str from django.utils.module_loading import import_string from django.utils.regex_helper import _lazy_re_compile from django.utils.version import get_docs_version # Minimal Django templates engine to render the error templates # regardless of the project's TEMPLATES setting. Templates are # read directly from the filesystem so that the error handler # works even if the template loader is broken. DEBUG_ENGINE = Engine( debug=True, libraries={"i18n": "django.templatetags.i18n"}, ) def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name class ExceptionCycleWarning(UserWarning): pass class CallableSettingWrapper: """ Object to wrap callable appearing in settings. * Not to call in the debug page (#21345). * Not to break the debug page if the callable forbidding to set attributes (#23070). """ def __init__(self, callable_setting): self._wrapped = callable_setting def __repr__(self): return repr(self._wrapped) def technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. """ reporter = get_exception_reporter_class(request)(request, exc_type, exc_value, tb) if request.accepts("text/html"): html = reporter.get_traceback_html() return HttpResponse(html, status=status_code, content_type="text/html") else: text = reporter.get_traceback_text() return HttpResponse( text, status=status_code, content_type="text/plain; charset=utf-8" ) @functools.lru_cache def get_default_exception_reporter_filter(): # Instantiate the default filter for the first time and cache it. return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)() def get_exception_reporter_filter(request): default_filter = get_default_exception_reporter_filter() return getattr(request, "exception_reporter_filter", default_filter) def get_exception_reporter_class(request): default_exception_reporter_class = import_string( settings.DEFAULT_EXCEPTION_REPORTER ) return getattr( request, "exception_reporter_class", default_exception_reporter_class ) def get_caller(request): resolver_match = request.resolver_match if resolver_match is None: try: resolver_match = resolve(request.path) except Http404: pass return "" if resolver_match is None else resolver_match._func_path class SafeExceptionReporterFilter: """ Use annotations made by the sensitive_post_parameters and sensitive_variables decorators to filter out sensitive information. """ cleansed_substitute = "********************" hidden_settings = _lazy_re_compile( "API|TOKEN|KEY|SECRET|PASS|SIGNATURE", flags=re.I ) def cleanse_setting(self, key, value): """ Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, recursively cleanse the keys in that dictionary. """ try: is_sensitive = self.hidden_settings.search(key) except TypeError: is_sensitive = False if is_sensitive: cleansed = self.cleansed_substitute elif isinstance(value, dict): cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()} elif isinstance(value, list): cleansed = [self.cleanse_setting("", v) for v in value] elif isinstance(value, tuple): cleansed = tuple([self.cleanse_setting("", v) for v in value]) else: cleansed = value if callable(cleansed): cleansed = CallableSettingWrapper(cleansed) return cleansed def get_safe_settings(self): """ Return a dictionary of the settings module with values of sensitive settings replaced with stars (*********). """ settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = self.cleanse_setting(k, getattr(settings, k)) return settings_dict def get_safe_request_meta(self, request): """ Return a dictionary of request.META with sensitive values redacted. """ if not hasattr(request, "META"): return {} return {k: self.cleanse_setting(k, v) for k, v in request.META.items()} def is_active(self, request): """ This filter is to add safety in production environments (i.e. DEBUG is False). If DEBUG is True then your site is not safe anyway. This hook is provided as a convenience to easily activate or deactivate the filter on a per request basis. """ return settings.DEBUG is False def get_cleansed_multivaluedict(self, request, multivaluedict): """ Replace the keys in a MultiValueDict marked as sensitive with stars. This mitigates leaking sensitive POST parameters if something like request.POST['nonexistent_key'] throws an exception (#21098). """ sensitive_post_parameters = getattr(request, "sensitive_post_parameters", []) if self.is_active(request) and sensitive_post_parameters: multivaluedict = multivaluedict.copy() for param in sensitive_post_parameters: if param in multivaluedict: multivaluedict[param] = self.cleansed_substitute return multivaluedict def get_post_parameters(self, request): """ Replace the values of POST parameters marked as sensitive with stars (*********). """ if request is None: return {} else: sensitive_post_parameters = getattr( request, "sensitive_post_parameters", [] ) if self.is_active(request) and sensitive_post_parameters: cleansed = request.POST.copy() if sensitive_post_parameters == "__ALL__": # Cleanse all parameters. for k in cleansed: cleansed[k] = self.cleansed_substitute return cleansed else: # Cleanse only the specified parameters. for param in sensitive_post_parameters: if param in cleansed: cleansed[param] = self.cleansed_substitute return cleansed else: return request.POST def cleanse_special_types(self, request, value): try: # If value is lazy or a complex object of another kind, this check # might raise an exception. isinstance checks that lazy # MultiValueDicts will have a return value. is_multivalue_dict = isinstance(value, MultiValueDict) except Exception as e: return "{!r} while evaluating {!r}".format(e, value) if is_multivalue_dict: # Cleanse MultiValueDicts (request.POST is the one we usually care about) value = self.get_cleansed_multivaluedict(request, value) return value def get_traceback_frame_variables(self, request, tb_frame): """ Replace the values of variables marked as sensitive with stars (*********). """ # Loop through the frame's callers to see if the sensitive_variables # decorator was used. current_frame = tb_frame.f_back sensitive_variables = None while current_frame is not None: if ( current_frame.f_code.co_name == "sensitive_variables_wrapper" and "sensitive_variables_wrapper" in current_frame.f_locals ): # The sensitive_variables decorator was used, so we take note # of the sensitive variables' names. wrapper = current_frame.f_locals["sensitive_variables_wrapper"] sensitive_variables = getattr(wrapper, "sensitive_variables", None) break current_frame = current_frame.f_back cleansed = {} if self.is_active(request) and sensitive_variables: if sensitive_variables == "__ALL__": # Cleanse all variables for name in tb_frame.f_locals: cleansed[name] = self.cleansed_substitute else: # Cleanse specified variables for name, value in tb_frame.f_locals.items(): if name in sensitive_variables: value = self.cleansed_substitute else: value = self.cleanse_special_types(request, value) cleansed[name] = value else: # Potentially cleanse the request and any MultiValueDicts if they # are one of the frame variables. for name, value in tb_frame.f_locals.items(): cleansed[name] = self.cleanse_special_types(request, value) if ( tb_frame.f_code.co_name == "sensitive_variables_wrapper" and "sensitive_variables_wrapper" in tb_frame.f_locals ): # For good measure, obfuscate the decorated function's arguments in # the sensitive_variables decorator's frame, in case the variables # associated with those arguments were meant to be obfuscated from # the decorated function's frame. cleansed["func_args"] = self.cleansed_substitute cleansed["func_kwargs"] = self.cleansed_substitute return cleansed.items() class ExceptionReporter: """Organize and coordinate reporting on exceptions.""" @property def html_template_path(self): return builtin_template_path("technical_500.html") @property def text_template_path(self): return builtin_template_path("technical_500.txt") def __init__(self, request, exc_type, exc_value, tb, is_email=False): self.request = request self.filter = get_exception_reporter_filter(self.request) self.exc_type = exc_type self.exc_value = exc_value self.tb = tb self.is_email = is_email self.template_info = getattr(self.exc_value, "template_debug", None) self.template_does_not_exist = False self.postmortem = None def _get_raw_insecure_uri(self): """ Return an absolute URI from variables available in this request. Skip allowed hosts protection, so may return insecure URI. """ return "{scheme}://{host}{path}".format( scheme=self.request.scheme, host=self.request._get_raw_host(), path=self.request.get_full_path(), ) def get_traceback_data(self): """Return a dictionary containing traceback information.""" if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): self.template_does_not_exist = True self.postmortem = self.exc_value.chain or [self.exc_value] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if "vars" in frame: frame_vars = [] for k, v in frame["vars"]: v = pprint(v) # Trim large blobs of data if len(v) > 4096: v = "%s… <trimmed %d bytes string>" % (v[0:4096], len(v)) frame_vars.append((k, v)) frame["vars"] = frame_vars frames[i] = frame unicode_hint = "" if self.exc_type and issubclass(self.exc_type, UnicodeError): start = getattr(self.exc_value, "start", None) end = getattr(self.exc_value, "end", None) if start is not None and end is not None: unicode_str = self.exc_value.args[1] unicode_hint = force_str( unicode_str[max(start - 5, 0) : min(end + 5, len(unicode_str))], "ascii", errors="replace", ) from django import get_version if self.request is None: user_str = None else: try: user_str = str(self.request.user) except Exception: # request.user may raise OperationalError if the database is # unavailable, for example. user_str = "[unable to retrieve the current user]" c = { "is_email": self.is_email, "unicode_hint": unicode_hint, "frames": frames, "request": self.request, "request_meta": self.filter.get_safe_request_meta(self.request), "user_str": user_str, "filtered_POST_items": list( self.filter.get_post_parameters(self.request).items() ), "settings": self.filter.get_safe_settings(), "sys_executable": sys.executable, "sys_version_info": "%d.%d.%d" % sys.version_info[0:3], "server_time": timezone.now(), "django_version_info": get_version(), "sys_path": sys.path, "template_info": self.template_info, "template_does_not_exist": self.template_does_not_exist, "postmortem": self.postmortem, } if self.request is not None: c["request_GET_items"] = self.request.GET.items() c["request_FILES_items"] = self.request.FILES.items() c["request_COOKIES_items"] = self.request.COOKIES.items() c["request_insecure_uri"] = self._get_raw_insecure_uri() c["raising_view_name"] = get_caller(self.request) # Check whether exception info is available if self.exc_type: c["exception_type"] = self.exc_type.__name__ if self.exc_value: c["exception_value"] = str(self.exc_value) if frames: c["lastframe"] = frames[-1] return c def get_traceback_html(self): """Return HTML version of debug 500 HTTP error page.""" with self.html_template_path.open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context(self.get_traceback_data(), use_l10n=False) return t.render(c) def get_traceback_text(self): """Return plain text version of debug 500 HTTP error page.""" with self.text_template_path.open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) return t.render(c) def _get_source(self, filename, loader, module_name): source = None if hasattr(loader, "get_source"): try: source = loader.get_source(module_name) except ImportError: pass if source is not None: source = source.splitlines() if source is None: try: with open(filename, "rb") as fp: source = fp.read().splitlines() except OSError: pass return source def _get_lines_from_file( self, filename, lineno, context_lines, loader=None, module_name=None ): """ Return context_lines before and after lineno from file. Return (pre_context_lineno, pre_context, context_line, post_context). """ source = self._get_source(filename, loader, module_name) if source is None: return None, [], None, [] # If we just read the source from a file, or if the loader did not # apply tokenize.detect_encoding to decode the source into a # string, then we should do that ourselves. if isinstance(source[0], bytes): encoding = "ascii" for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 # (https://www.python.org/dev/peps/pep-0263/) match = re.search(rb"coding[:=]\s*([-\w.]+)", line) if match: encoding = match[1].decode("ascii") break source = [str(sline, encoding, "replace") for sline in source] lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines try: pre_context = source[lower_bound:lineno] context_line = source[lineno] post_context = source[lineno + 1 : upper_bound] except IndexError: return None, [], None, [] return lower_bound, pre_context, context_line, post_context def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, "__cause__", None) suppress_context = getattr(exc_value, "__suppress_context__", None) implicit = getattr(exc_value, "__context__", None) return explicit or (None if suppress_context else implicit) def get_traceback_frames(self): # Get the exception and all its causes exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( "Cycle in the exception chain detected: exception '%s' " "encountered again." % exc_value, ExceptionCycleWarning, ) # Avoid infinite loop if there's a cyclic reference (#29393). break frames = [] # No exceptions were supplied to ExceptionReporter if not exceptions: return frames # In case there's just one exception, take the traceback from self.tb exc_value = exceptions.pop() tb = self.tb if not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except IndexError: break tb = exc_value.__traceback__ return frames def get_exception_traceback_frames(self, exc_value, tb): exc_cause = self._get_explicit_or_implicit_cause(exc_value) exc_cause_explicit = getattr(exc_value, "__cause__", True) if tb is None: yield { "exc_cause": exc_cause, "exc_cause_explicit": exc_cause_explicit, "tb": None, "type": "user", } while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get("__traceback_hide__"): tb = tb.tb_next continue filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name lineno = tb.tb_lineno - 1 loader = tb.tb_frame.f_globals.get("__loader__") module_name = tb.tb_frame.f_globals.get("__name__") or "" ( pre_context_lineno, pre_context, context_line, post_context, ) = self._get_lines_from_file( filename, lineno, 7, loader, module_name, ) if pre_context_lineno is None: pre_context_lineno = lineno pre_context = [] context_line = "<source code not available>" post_context = [] yield { "exc_cause": exc_cause, "exc_cause_explicit": exc_cause_explicit, "tb": tb, "type": "django" if module_name.startswith("django.") else "user", "filename": filename, "function": function, "lineno": lineno + 1, "vars": self.filter.get_traceback_frame_variables( self.request, tb.tb_frame ), "id": id(tb), "pre_context": pre_context, "context_line": context_line, "post_context": post_context, "pre_context_lineno": pre_context_lineno + 1, } tb = tb.tb_next def technical_404_response(request, exception): """Create a technical 404 error response. `exception` is the Http404.""" try: error_url = exception.args[0]["path"] except (IndexError, TypeError, KeyError): error_url = request.path_info[1:] # Trim leading slash try: tried = exception.args[0]["tried"] except (IndexError, TypeError, KeyError): resolved = True tried = request.resolver_match.tried if request.resolver_match else None else: resolved = False if not tried or ( # empty URLconf request.path == "/" and len(tried) == 1 and len(tried[0]) == 1 # default URLconf and getattr(tried[0][0], "app_name", "") == getattr(tried[0][0], "namespace", "") == "admin" ): return default_urlconf(request) urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) if isinstance(urlconf, types.ModuleType): urlconf = urlconf.__name__ with builtin_template_path("technical_404.html").open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) reporter_filter = get_default_exception_reporter_filter() c = Context( { "urlconf": urlconf, "root_urlconf": settings.ROOT_URLCONF, "request_path": error_url, "urlpatterns": tried, "resolved": resolved, "reason": str(exception), "request": request, "settings": reporter_filter.get_safe_settings(), "raising_view_name": get_caller(request), } ) return HttpResponseNotFound(t.render(c), content_type="text/html") def default_urlconf(request): """Create an empty URLconf 404 error response.""" with builtin_template_path("default_urlconf.html").open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context( { "version": get_docs_version(), } ) return HttpResponse(t.render(c), content_type="text/html")
95ee595230df405318bb11c87e4ad99b8d656ecebf93d61e369ca964783b9d50
from django.conf import settings from django.http import HttpResponseForbidden from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.translation import gettext as _ from django.utils.version import get_docs_version # We include the template inline since we need to be able to reliably display # this error message, especially for the sake of developers, and there isn't any # other way of making it available independent of what is in the settings file. # Only the text appearing with DEBUG=False is translated. Normal translation # tags cannot be used with this inline templates as makemessages would not be # able to discover the strings. CSRF_FAILURE_TEMPLATE = """ <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>{{ title }} <span>(403)</span></h1> <p>{{ main }}</p> {% if no_referer %} <p>{{ no_referer1 }}</p> <p>{{ no_referer2 }}</p> <p>{{ no_referer3 }}</p> {% endif %} {% if no_cookie %} <p>{{ no_cookie1 }}</p> <p>{{ no_cookie2 }}</p> {% endif %} </div> {% if DEBUG %} <div id="info"> <h2>Help</h2> {% if reason %} <p>Reason given for failure:</p> <pre> {{ reason }} </pre> {% endif %} <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/{{ docs_version }}/ref/csrf/">Django’s CSRF mechanism</a> has not been used correctly. For POST forms, you need to ensure:</p> <ul> <li>Your browser is accepting cookies.</li> <li>The view function passes a <code>request</code> to the template’s <a href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a> method.</li> <li>In the template, there is a <code>{% templatetag openblock %} csrf_token {% templatetag closeblock %}</code> template tag inside each POST form that targets an internal URL.</li> <li>If you are not using <code>CsrfViewMiddleware</code>, then you must use <code>csrf_protect</code> on any views that use the <code>csrf_token</code> template tag, as well as those that accept the POST data.</li> <li>The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.</li> </ul> <p>You’re seeing the help section of this page because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and only the initial error message will be displayed. </p> <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p> </div> {% else %} <div id="explanation"> <p><small>{{ more }}</small></p> </div> {% endif %} </body> </html> """ # NOQA CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER c = { "title": _("Forbidden"), "main": _("CSRF verification failed. Request aborted."), "reason": reason, "no_referer": reason == REASON_NO_REFERER, "no_referer1": _( "You are seeing this message because this HTTPS site requires a " "“Referer header” to be sent by your web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties." ), "no_referer2": _( "If you have configured your browser to disable “Referer” headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for “same-origin” requests." ), "no_referer3": _( 'If you are using the <meta name="referrer" ' 'content="no-referrer"> tag or including the “Referrer-Policy: ' "no-referrer” header, please remove them. The CSRF protection " "requires the “Referer” header to do strict referer checking. If " "you’re concerned about privacy, use alternatives like " '<a rel="noreferrer" …> for links to third-party sites.' ), "no_cookie": reason == REASON_NO_CSRF_COOKIE, "no_cookie1": _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties." ), "no_cookie2": _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for “same-origin” " "requests." ), "DEBUG": settings.DEBUG, "docs_version": get_docs_version(), "more": _("More information is available with DEBUG=True."), } try: t = loader.get_template(template_name) except TemplateDoesNotExist: if template_name == CSRF_FAILURE_TEMPLATE_NAME: # If the default template doesn't exist, use the string template. t = Engine().from_string(CSRF_FAILURE_TEMPLATE) c = Context(c) else: # Raise if a developer-specified template doesn't exist. raise return HttpResponseForbidden(t.render(c), content_type="text/html")
97f041f98ecc3596805897aa7a940116191956b537c27154e29ae4448c71b1fa
""" Settings and configuration for Django. Read values from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global_settings.py for a list of all possible variables. """ import importlib import os import time import traceback import warnings from pathlib import Path import django from django.conf import global_settings from django.core.exceptions import ImproperlyConfigured from django.utils.deprecation import RemovedInDjango50Warning from django.utils.functional import LazyObject, empty ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" # RemovedInDjango50Warning USE_DEPRECATED_PYTZ_DEPRECATED_MSG = ( "The USE_DEPRECATED_PYTZ setting, and support for pytz timezones is " "deprecated in favor of the stdlib zoneinfo module. Please update your " "code to use zoneinfo and remove the USE_DEPRECATED_PYTZ setting." ) USE_L10N_DEPRECATED_MSG = ( "The USE_L10N setting is deprecated. Starting with Django 5.0, localized " "formatting of data will always be enabled. For example Django will " "display numbers and dates using the format of the current locale." ) CSRF_COOKIE_MASKED_DEPRECATED_MSG = ( "The CSRF_COOKIE_MASKED transitional setting is deprecated. Support for " "it will be removed in Django 5.0." ) class SettingsReference(str): """ String subclass which references a current settings value. It's treated as the value in memory but serializes to a settings.NAME attribute reference. """ def __new__(self, value, setting_name): return str.__new__(self, value) def __init__(self, value, setting_name): self.setting_name = setting_name class LazySettings(LazyObject): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def _setup(self, name=None): """ Load the settings module pointed to by the environment variable. This is used the first time settings are needed, if the user hasn't configured settings manually. """ settings_module = os.environ.get(ENVIRONMENT_VARIABLE) if not settings_module: desc = ("setting %s" % name) if name else "settings" raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " "or call settings.configure() before accessing settings." % (desc, ENVIRONMENT_VARIABLE) ) self._wrapped = Settings(settings_module) def __repr__(self): # Hardcode the class name as otherwise it yields 'Settings'. if self._wrapped is empty: return "<LazySettings [Unevaluated]>" return '<LazySettings "%(settings_module)s">' % { "settings_module": self._wrapped.SETTINGS_MODULE, } def __getattr__(self, name): """Return the value of a setting and cache it in self.__dict__.""" if self._wrapped is empty: self._setup(name) val = getattr(self._wrapped, name) # Special case some settings which require further modification. # This is done here for performance reasons so the modified value is cached. if name in {"MEDIA_URL", "STATIC_URL"} and val is not None: val = self._add_script_prefix(val) elif name == "SECRET_KEY" and not val: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") self.__dict__[name] = val return val def __setattr__(self, name, value): """ Set the value of setting. Clear all cached values if _wrapped changes (@override_settings does this) or clear single values when set. """ if name == "_wrapped": self.__dict__.clear() else: self.__dict__.pop(name, None) super().__setattr__(name, value) def __delattr__(self, name): """Delete a setting and clear it from cache if needed.""" super().__delattr__(name) self.__dict__.pop(name, None) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._wrapped is not empty: raise RuntimeError("Settings already configured.") holder = UserSettingsHolder(default_settings) for name, value in options.items(): if not name.isupper(): raise TypeError("Setting %r must be uppercase." % name) setattr(holder, name, value) self._wrapped = holder @staticmethod def _add_script_prefix(value): """ Add SCRIPT_NAME prefix to relative paths. Useful when the app is being served at a subpath and manually prefixing subpath to STATIC_URL and MEDIA_URL in settings is inconvenient. """ # Don't apply prefix to absolute paths and URLs. if value.startswith(("http://", "https://", "/")): return value from django.urls import get_script_prefix return "%s%s" % (get_script_prefix(), value) @property def configured(self): """Return True if the settings have already been configured.""" return self._wrapped is not empty @property def USE_L10N(self): stack = traceback.extract_stack() # Show a warning if the setting is used outside of Django. # Stack index: -1 this line, -2 the LazyObject __getattribute__(), # -3 the caller. filename, _, _, _ = stack[-3] if not filename.startswith(os.path.dirname(django.__file__)): warnings.warn( USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning, stacklevel=2, ) return self.__getattr__("USE_L10N") # RemovedInDjango50Warning. @property def _USE_L10N_INTERNAL(self): # Special hook to avoid checking a traceback in internal use on hot # paths. return self.__getattr__("USE_L10N") class Settings: def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting.isupper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "ALLOWED_HOSTS", "INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS", "SECRET_KEY_FALLBACKS", ) self._explicit_settings = set() for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if setting in tuple_settings and not isinstance( setting_value, (list, tuple) ): raise ImproperlyConfigured( "The %s setting must be a list or a tuple." % setting ) setattr(self, setting, setting_value) self._explicit_settings.add(setting) if self.USE_TZ is False and not self.is_overridden("USE_TZ"): warnings.warn( "The default value of USE_TZ will change from False to True " "in Django 5.0. Set USE_TZ to False in your project settings " "if you want to keep the current default behavior.", category=RemovedInDjango50Warning, ) if self.is_overridden("USE_DEPRECATED_PYTZ"): warnings.warn(USE_DEPRECATED_PYTZ_DEPRECATED_MSG, RemovedInDjango50Warning) if self.is_overridden("CSRF_COOKIE_MASKED"): warnings.warn(CSRF_COOKIE_MASKED_DEPRECATED_MSG, RemovedInDjango50Warning) if hasattr(time, "tzset") and self.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = Path("/usr/share/zoneinfo") zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split("/")) if zoneinfo_root.exists() and not zone_info_file.exists(): raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ["TZ"] = self.TIME_ZONE time.tzset() if self.is_overridden("USE_L10N"): warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning) def is_overridden(self, setting): return setting in self._explicit_settings def __repr__(self): return '<%(cls)s "%(settings_module)s">' % { "cls": self.__class__.__name__, "settings_module": self.SETTINGS_MODULE, } class UserSettingsHolder: """Holder for user configured settings.""" # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__["_deleted"] = set() self.default_settings = default_settings def __getattr__(self, name): if not name.isupper() or name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) if name == "USE_L10N": warnings.warn(USE_L10N_DEPRECATED_MSG, RemovedInDjango50Warning) if name == "CSRF_COOKIE_MASKED": warnings.warn(CSRF_COOKIE_MASKED_DEPRECATED_MSG, RemovedInDjango50Warning) super().__setattr__(name, value) if name == "USE_DEPRECATED_PYTZ": warnings.warn(USE_DEPRECATED_PYTZ_DEPRECATED_MSG, RemovedInDjango50Warning) def __delattr__(self, name): self._deleted.add(name) if hasattr(self, name): super().__delattr__(name) def __dir__(self): return sorted( s for s in [*self.__dict__, *dir(self.default_settings)] if s not in self._deleted ) def is_overridden(self, setting): deleted = setting in self._deleted set_locally = setting in self.__dict__ set_on_default = getattr( self.default_settings, "is_overridden", lambda s: False )(setting) return deleted or set_locally or set_on_default def __repr__(self): return "<%(cls)s>" % { "cls": self.__class__.__name__, } settings = LazySettings()
ce889664169dd12df9047a945b483e932983e01d1ba08d5cead5b61267ddd4dc
""" Default Django settings. Override these with settings in the module pointed to by the DJANGO_SETTINGS_MODULE environment variable. """ # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. def gettext_noop(s): return s #################### # CORE # #################### DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing situations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # People who get code error notifications. In the format # [('Full Name', '[email protected]'), ('Full Name', '[email protected]')] ADMINS = [] # List of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = [] # Hosts/domain names that are valid for this site. # "*" matches anything, ".example.com" matches example.com and all subdomains ALLOWED_HOSTS = [] # Local time zone for this installation. All choices can be found here: # https://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). When USE_TZ is True, this is # interpreted as the default user time zone. TIME_ZONE = "America/Chicago" # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = False # RemovedInDjango50Warning: It's a transitional setting helpful in migrating # from pytz tzinfo to ZoneInfo(). Set True to continue using pytz tzinfo # objects during the Django 4.x release cycle. USE_DEPRECATED_PYTZ = False # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en-us" # Languages we provide translations for, out of the box. LANGUAGES = [ ("af", gettext_noop("Afrikaans")), ("ar", gettext_noop("Arabic")), ("ar-dz", gettext_noop("Algerian Arabic")), ("ast", gettext_noop("Asturian")), ("az", gettext_noop("Azerbaijani")), ("bg", gettext_noop("Bulgarian")), ("be", gettext_noop("Belarusian")), ("bn", gettext_noop("Bengali")), ("br", gettext_noop("Breton")), ("bs", gettext_noop("Bosnian")), ("ca", gettext_noop("Catalan")), ("cs", gettext_noop("Czech")), ("cy", gettext_noop("Welsh")), ("da", gettext_noop("Danish")), ("de", gettext_noop("German")), ("dsb", gettext_noop("Lower Sorbian")), ("el", gettext_noop("Greek")), ("en", gettext_noop("English")), ("en-au", gettext_noop("Australian English")), ("en-gb", gettext_noop("British English")), ("eo", gettext_noop("Esperanto")), ("es", gettext_noop("Spanish")), ("es-ar", gettext_noop("Argentinian Spanish")), ("es-co", gettext_noop("Colombian Spanish")), ("es-mx", gettext_noop("Mexican Spanish")), ("es-ni", gettext_noop("Nicaraguan Spanish")), ("es-ve", gettext_noop("Venezuelan Spanish")), ("et", gettext_noop("Estonian")), ("eu", gettext_noop("Basque")), ("fa", gettext_noop("Persian")), ("fi", gettext_noop("Finnish")), ("fr", gettext_noop("French")), ("fy", gettext_noop("Frisian")), ("ga", gettext_noop("Irish")), ("gd", gettext_noop("Scottish Gaelic")), ("gl", gettext_noop("Galician")), ("he", gettext_noop("Hebrew")), ("hi", gettext_noop("Hindi")), ("hr", gettext_noop("Croatian")), ("hsb", gettext_noop("Upper Sorbian")), ("hu", gettext_noop("Hungarian")), ("hy", gettext_noop("Armenian")), ("ia", gettext_noop("Interlingua")), ("id", gettext_noop("Indonesian")), ("ig", gettext_noop("Igbo")), ("io", gettext_noop("Ido")), ("is", gettext_noop("Icelandic")), ("it", gettext_noop("Italian")), ("ja", gettext_noop("Japanese")), ("ka", gettext_noop("Georgian")), ("kab", gettext_noop("Kabyle")), ("kk", gettext_noop("Kazakh")), ("km", gettext_noop("Khmer")), ("kn", gettext_noop("Kannada")), ("ko", gettext_noop("Korean")), ("ky", gettext_noop("Kyrgyz")), ("lb", gettext_noop("Luxembourgish")), ("lt", gettext_noop("Lithuanian")), ("lv", gettext_noop("Latvian")), ("mk", gettext_noop("Macedonian")), ("ml", gettext_noop("Malayalam")), ("mn", gettext_noop("Mongolian")), ("mr", gettext_noop("Marathi")), ("ms", gettext_noop("Malay")), ("my", gettext_noop("Burmese")), ("nb", gettext_noop("Norwegian Bokmål")), ("ne", gettext_noop("Nepali")), ("nl", gettext_noop("Dutch")), ("nn", gettext_noop("Norwegian Nynorsk")), ("os", gettext_noop("Ossetic")), ("pa", gettext_noop("Punjabi")), ("pl", gettext_noop("Polish")), ("pt", gettext_noop("Portuguese")), ("pt-br", gettext_noop("Brazilian Portuguese")), ("ro", gettext_noop("Romanian")), ("ru", gettext_noop("Russian")), ("sk", gettext_noop("Slovak")), ("sl", gettext_noop("Slovenian")), ("sq", gettext_noop("Albanian")), ("sr", gettext_noop("Serbian")), ("sr-latn", gettext_noop("Serbian Latin")), ("sv", gettext_noop("Swedish")), ("sw", gettext_noop("Swahili")), ("ta", gettext_noop("Tamil")), ("te", gettext_noop("Telugu")), ("tg", gettext_noop("Tajik")), ("th", gettext_noop("Thai")), ("tk", gettext_noop("Turkmen")), ("tr", gettext_noop("Turkish")), ("tt", gettext_noop("Tatar")), ("udm", gettext_noop("Udmurt")), ("uk", gettext_noop("Ukrainian")), ("ur", gettext_noop("Urdu")), ("uz", gettext_noop("Uzbek")), ("vi", gettext_noop("Vietnamese")), ("zh-hans", gettext_noop("Simplified Chinese")), ("zh-hant", gettext_noop("Traditional Chinese")), ] # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ["he", "ar", "ar-dz", "fa", "ur"] # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = [] # Settings for language cookie LANGUAGE_COOKIE_NAME = "django_language" LANGUAGE_COOKIE_AGE = None LANGUAGE_COOKIE_DOMAIN = None LANGUAGE_COOKIE_PATH = "/" LANGUAGE_COOKIE_SECURE = False LANGUAGE_COOKIE_HTTPONLY = False LANGUAGE_COOKIE_SAMESITE = None # If you set this to True, Django will format dates, numbers and calendars # according to user current locale. USE_L10N = True # Not-necessarily-technical managers of the site. They get broken link # notifications and other various emails. MANAGERS = ADMINS # Default charset to use for all HttpResponse objects, if a MIME type isn't # manually specified. It's used to construct the Content-Type header. DEFAULT_CHARSET = "utf-8" # Email address that error messages come from. SERVER_EMAIL = "root@localhost" # Database connection info. If left empty, will default to the dummy backend. DATABASES = {} # Classes used to implement DB routing behavior. DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" # Host for sending email. EMAIL_HOST = "localhost" # Port for sending email. EMAIL_PORT = 25 # Whether to send SMTP 'Date' header in the local time zone or in UTC. EMAIL_USE_LOCALTIME = False # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" EMAIL_USE_TLS = False EMAIL_USE_SSL = False EMAIL_SSL_CERTFILE = None EMAIL_SSL_KEYFILE = None EMAIL_TIMEOUT = None # List of strings representing installed apps. INSTALLED_APPS = [] TEMPLATES = [] # Default form rendering class. FORM_RENDERER = "django.forms.renderers.DjangoTemplates" # Default email address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = "webmaster@localhost" # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = "[Django] " # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = [ # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search'), # ] DISALLOWED_USER_AGENTS = [] ABSOLUTE_URL_OVERRIDES = {} # List of compiled regular expression objects representing URLs that need not # be reported by BrokenLinkEmailsMiddleware. Here are a few examples: # import re # IGNORABLE_404_URLS = [ # re.compile(r'^/apple-touch-icon.*\.png$'), # re.compile(r'^/favicon.ico$'), # re.compile(r'^/robots.txt$'), # re.compile(r'^/phpmyadmin/'), # re.compile(r'\.(cgi|php|pl)$'), # ] IGNORABLE_404_URLS = [] # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = "" # List of secret keys used to verify the validity of signatures. This allows # secret key rotation. SECRET_KEY_FALLBACKS = [] # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage" # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = "" # URL that handles the media served from MEDIA_ROOT. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = "" # Absolute path to the directory static files should be collected to. # Example: "/var/www/example.com/static/" STATIC_ROOT = None # URL that handles the static files served from STATIC_ROOT. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = None # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = [ "django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler", ] # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum size in bytes of request data (excluding file uploads) that will be # read before a SuspiciousOperation (RequestDataTooBig) is raised. DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Maximum number of GET/POST parameters that will be read before a # SuspiciousOperation (TooManyFieldsSent) is raised. DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see # https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_PERMISSIONS = 0o644 # The numeric mode to assign to newly-created directories, when uploading files. # The value should be a mode as you'd pass to os.chmod; # see https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_DIRECTORY_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = "N j, Y" # Default formatting for datetime objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = "N j, Y, P" # Default formatting for time objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = "P" # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = "F Y" # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = "F j" # Default short formatting for date objects. See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = "m/d/Y" # Default short formatting for datetime objects. # See all available format strings here: # https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = "m/d/Y P" # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = [ "%Y-%m-%d", # '2006-10-25' "%m/%d/%Y", # '10/25/2006' "%m/%d/%y", # '10/25/06' "%b %d %Y", # 'Oct 25 2006' "%b %d, %Y", # 'Oct 25, 2006' "%d %b %Y", # '25 Oct 2006' "%d %b, %Y", # '25 Oct, 2006' "%B %d %Y", # 'October 25 2006' "%B %d, %Y", # 'October 25, 2006' "%d %B %Y", # '25 October 2006' "%d %B, %Y", # '25 October, 2006' ] # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = [ "%H:%M:%S", # '14:30:59' "%H:%M:%S.%f", # '14:30:59.000200' "%H:%M", # '14:30' ] # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # https://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = [ "%Y-%m-%d %H:%M:%S", # '2006-10-25 14:30:59' "%Y-%m-%d %H:%M:%S.%f", # '2006-10-25 14:30:59.000200' "%Y-%m-%d %H:%M", # '2006-10-25 14:30' "%m/%d/%Y %H:%M:%S", # '10/25/2006 14:30:59' "%m/%d/%Y %H:%M:%S.%f", # '10/25/2006 14:30:59.000200' "%m/%d/%Y %H:%M", # '10/25/2006 14:30' "%m/%d/%y %H:%M:%S", # '10/25/06 14:30:59' "%m/%d/%y %H:%M:%S.%f", # '10/25/06 14:30:59.000200' "%m/%d/%y %H:%M", # '10/25/06 14:30' ] # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = "." # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when splitting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = "," # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = "" DEFAULT_INDEX_TABLESPACE = "" # Default primary key field type. DEFAULT_AUTO_FIELD = "django.db.models.AutoField" # Default X-Frame-Options header value X_FRAME_OPTIONS = "DENY" USE_X_FORWARDED_HOST = False USE_X_FORWARDED_PORT = False # The Python dotted path to the WSGI application that Django's internal server # (runserver) will use. If `None`, the return value of # 'django.core.wsgi.get_wsgi_application' is used, thus preserving the same # behavior as previous versions of Django. Otherwise this should point to an # actual WSGI application object. WSGI_APPLICATION = None # If your Django app is behind a proxy that sets a header to specify secure # connections, AND that proxy ensures that user-submitted headers with the # same name are ignored (so that people can't spoof it), set this value to # a tuple of (header_name, header_value). For any requests that come in with # that header/value, request.is_secure() will return True. # WARNING! Only set this if you fully understand what you're doing. Otherwise, # you may be opening yourself up to a security risk. SECURE_PROXY_SSL_HEADER = None ############## # MIDDLEWARE # ############## # List of middleware to use. Order is important; in the request phase, these # middleware will be applied in the order given, and in the response # phase the middleware will be applied in reverse order. MIDDLEWARE = [] ############ # SESSIONS # ############ # Cache to store session data if using the cache session backend. SESSION_CACHE_ALIAS = "default" # Cookie name. This can be whatever you want. SESSION_COOKIE_NAME = "sessionid" # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # A string like "example.com", or None for standard domain cookie. SESSION_COOKIE_DOMAIN = None # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_SECURE = False # The path of the session cookie. SESSION_COOKIE_PATH = "/" # Whether to use the HttpOnly flag. SESSION_COOKIE_HTTPONLY = True # Whether to set the flag restricting cookie leaks on cross-site requests. # This can be 'Lax', 'Strict', 'None', or False to disable the flag. SESSION_COOKIE_SAMESITE = "Lax" # Whether to save the session data on every request. SESSION_SAVE_EVERY_REQUEST = False # Whether a user's session cookie expires when the web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # The module to store session data SESSION_ENGINE = "django.contrib.sessions.backends.db" # Directory to store session files if using the file session module. If None, # the backend will use a sensible default. SESSION_FILE_PATH = None # class to serialize session data SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer" ######### # CACHE # ######### # The cache backends to use. CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", } } CACHE_MIDDLEWARE_KEY_PREFIX = "" CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = "default" ################## # AUTHENTICATION # ################## AUTH_USER_MODEL = "auth.User" AUTHENTICATION_BACKENDS = ["django.contrib.auth.backends.ModelBackend"] LOGIN_URL = "/accounts/login/" LOGIN_REDIRECT_URL = "/accounts/profile/" LOGOUT_REDIRECT_URL = None # The number of seconds a password reset link is valid for (default: 3 days). PASSWORD_RESET_TIMEOUT = 60 * 60 * 24 * 3 # the first hasher in this list is the preferred algorithm. any # password using different algorithms will be converted automatically # upon login PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.Argon2PasswordHasher", "django.contrib.auth.hashers.BCryptSHA256PasswordHasher", "django.contrib.auth.hashers.ScryptPasswordHasher", ] AUTH_PASSWORD_VALIDATORS = [] ########### # SIGNING # ########### SIGNING_BACKEND = "django.core.signing.TimestampSigner" ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = "django.views.csrf.csrf_failure" # Settings for CSRF cookie. CSRF_COOKIE_NAME = "csrftoken" CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52 CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_PATH = "/" CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SAMESITE = "Lax" CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" CSRF_TRUSTED_ORIGINS = [] CSRF_USE_SESSIONS = False # Whether to mask CSRF cookie value. It's a transitional setting helpful in # migrating multiple instance of the same project to Django 4.1+. CSRF_COOKIE_MASKED = False ############ # MESSAGES # ############ # Class to use as messages backend MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage" # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = "logging.config.dictConfig" # Custom logging configuration. LOGGING = {} # Default exception reporter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER = "django.views.debug.ExceptionReporter" # Default exception reporter filter class used in case none has been # specifically assigned to the HttpRequest instance. DEFAULT_EXCEPTION_REPORTER_FILTER = "django.views.debug.SafeExceptionReporterFilter" ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = "django.test.runner.DiscoverRunner" # Apps that don't need to be serialized at test database creation time # (only apps with migrations are to start with) TEST_NON_SERIALIZED_APPS = [] ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = [] ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS = [] # The default file storage backend used during the build process STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage" # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ] ############## # MIGRATIONS # ############## # Migration module overrides for apps, by app label. MIGRATION_MODULES = {} ################# # SYSTEM CHECKS # ################# # List of all issues generated by system checks that should be silenced. Light # issues like warnings, infos or debugs will not generate a message. Silencing # serious issues like errors and criticals does not result in hiding the # message, but Django will not stop you from e.g. running server. SILENCED_SYSTEM_CHECKS = [] ####################### # SECURITY MIDDLEWARE # ####################### SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin" SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_HSTS_PRELOAD = False SECURE_HSTS_SECONDS = 0 SECURE_REDIRECT_EXEMPT = [] SECURE_REFERRER_POLICY = "same-origin" SECURE_SSL_HOST = None SECURE_SSL_REDIRECT = False
c5aea9d9e82ea4c258a5c5d516bb5e4c01d3f4389ab469becc61684369f150eb
"Functions that help with dynamically creating decorators for views." from functools import partial, update_wrapper, wraps class classonlymethod(classmethod): def __get__(self, instance, cls=None): if instance is not None: raise AttributeError( "This method is available only on the class, not on instances." ) return super().__get__(instance, cls) def _update_method_wrapper(_wrapper, decorator): # _multi_decorate()'s bound_method isn't available in this scope. Cheat by # using it on a dummy function. @decorator def dummy(*args, **kwargs): pass update_wrapper(_wrapper, dummy) def _multi_decorate(decorators, method): """ Decorate `method` with one or more function decorators. `decorators` can be a single decorator or an iterable of decorators. """ if hasattr(decorators, "__iter__"): # Apply a list/tuple of decorators if 'decorators' is one. Decorator # functions are applied so that the call order is the same as the # order in which they appear in the iterable. decorators = decorators[::-1] else: decorators = [decorators] def _wrapper(self, *args, **kwargs): # bound_method has the signature that 'decorator' expects i.e. no # 'self' argument, but it's a closure over self so it can call # 'func'. Also, wrap method.__get__() in a function because new # attributes can't be set on bound method objects, only on functions. bound_method = wraps(method)(partial(method.__get__(self, type(self)))) for dec in decorators: bound_method = dec(bound_method) return bound_method(*args, **kwargs) # Copy any attributes that a decorator adds to the function it decorates. for dec in decorators: _update_method_wrapper(_wrapper, dec) # Preserve any existing attributes of 'method', including the name. update_wrapper(_wrapper, method) return _wrapper def method_decorator(decorator, name=""): """ Convert a function decorator into a method decorator """ # 'obj' can be a class or a function. If 'obj' is a function at the time it # is passed to _dec, it will eventually be a method of the class it is # defined on. If 'obj' is a class, the 'name' is required to be the name # of the method that will be decorated. def _dec(obj): if not isinstance(obj, type): return _multi_decorate(decorator, obj) if not (name and hasattr(obj, name)): raise ValueError( "The keyword argument `name` must be the name of a method " "of the decorated class: %s. Got '%s' instead." % (obj, name) ) method = getattr(obj, name) if not callable(method): raise TypeError( "Cannot decorate '%s' as it isn't a callable attribute of " "%s (%s)." % (name, obj, method) ) _wrapper = _multi_decorate(decorator, method) setattr(obj, name, _wrapper) return obj # Don't worry about making _dec look similar to a list/tuple as it's rather # meaningless. if not hasattr(decorator, "__iter__"): update_wrapper(_dec, decorator) # Change the name to aid debugging. obj = decorator if hasattr(decorator, "__name__") else decorator.__class__ _dec.__name__ = "method_decorator(%s)" % obj.__name__ return _dec def decorator_from_middleware_with_args(middleware_class): """ Like decorator_from_middleware, but return a function that accepts the arguments to be passed to the middleware_class. Use like:: cache_page = decorator_from_middleware_with_args(CacheMiddleware) # ... @cache_page(3600) def my_view(request): # ... """ return make_middleware_decorator(middleware_class) def decorator_from_middleware(middleware_class): """ Given a middleware class (not an instance), return a view decorator. This lets you use middleware functionality on a per-view basis. The middleware is created with no params passed. """ return make_middleware_decorator(middleware_class)() def make_middleware_decorator(middleware_class): def _make_decorator(*m_args, **m_kwargs): def _decorator(view_func): middleware = middleware_class(view_func, *m_args, **m_kwargs) @wraps(view_func) def _wrapped_view(request, *args, **kwargs): if hasattr(middleware, "process_request"): result = middleware.process_request(request) if result is not None: return result if hasattr(middleware, "process_view"): result = middleware.process_view(request, view_func, args, kwargs) if result is not None: return result try: response = view_func(request, *args, **kwargs) except Exception as e: if hasattr(middleware, "process_exception"): result = middleware.process_exception(request, e) if result is not None: return result raise if hasattr(response, "render") and callable(response.render): if hasattr(middleware, "process_template_response"): response = middleware.process_template_response( request, response ) # Defer running of process_response until after the template # has been rendered: if hasattr(middleware, "process_response"): def callback(response): return middleware.process_response(request, response) response.add_post_render_callback(callback) else: if hasattr(middleware, "process_response"): return middleware.process_response(request, response) return response return _wrapped_view return _decorator return _make_decorator def sync_and_async_middleware(func): """ Mark a middleware factory as returning a hybrid middleware supporting both types of request. """ func.sync_capable = True func.async_capable = True return func def sync_only_middleware(func): """ Mark a middleware factory as returning a sync middleware. This is the default. """ func.sync_capable = True func.async_capable = False return func def async_only_middleware(func): """Mark a middleware factory as returning an async middleware.""" func.sync_capable = False func.async_capable = True return func
286e614be4b8342799d080302dddf482fb0e7b6f2b1e03744db5c47bdb778d5c
# These classes override date and datetime to ensure that strftime('%Y') # returns four digits (with leading zeros) on years < 1000. # https://bugs.python.org/issue13305 # # Based on code submitted to comp.lang.python by Andrew Dalke # # >>> datetime_safe.date(10, 8, 2).strftime("%Y/%m/%d was a %A") # '0010/08/02 was a Monday' import time import warnings from datetime import date as real_date from datetime import datetime as real_datetime from django.utils.deprecation import RemovedInDjango50Warning from django.utils.regex_helper import _lazy_re_compile warnings.warn( "The django.utils.datetime_safe module is deprecated.", category=RemovedInDjango50Warning, stacklevel=2, ) class date(real_date): def strftime(self, fmt): return strftime(self, fmt) class datetime(real_datetime): def strftime(self, fmt): return strftime(self, fmt) @classmethod def combine(cls, date, time): return cls( date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond, time.tzinfo, ) def date(self): return date(self.year, self.month, self.day) def new_date(d): "Generate a safe date from a datetime.date object." return date(d.year, d.month, d.day) def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw) # This library does not support strftime's "%s" or "%y" format strings. # Allowed if there's an even number of "%"s because they are escaped. _illegal_formatting = _lazy_re_compile(r"((^|[^%])(%%)*%[sy])") def _findall(text, substr): # Also finds overlaps sites = [] i = 0 while True: i = text.find(substr, i) if i == -1: break sites.append(i) i += 1 return sites def strftime(dt, fmt): if dt.year >= 1000: return super(type(dt), dt).strftime(fmt) illegal_formatting = _illegal_formatting.search(fmt) if illegal_formatting: raise TypeError( "strftime of dates before 1000 does not handle " + illegal_formatting[0] ) year = dt.year # For every non-leap year century, advance by # 6 years to get into the 28-year repeat cycle delta = 2000 - year off = 6 * (delta // 100 + delta // 400) year = year + off # Move to around the year 2000 year = year + ((2000 - year) // 28) * 28 timetuple = dt.timetuple() s1 = time.strftime(fmt, (year,) + timetuple[1:]) sites1 = _findall(s1, str(year)) s2 = time.strftime(fmt, (year + 28,) + timetuple[1:]) sites2 = _findall(s2, str(year + 28)) sites = [] for site in sites1: if site in sites2: sites.append(site) s = s1 syear = "%04d" % dt.year for site in sites: s = s[:site] + syear + s[site + 4 :] return s
03b09575e231976858eae7d9ba4af25369adce7f4b36293931796b1190e2a5df
import functools import itertools import logging import os import signal import subprocess import sys import threading import time import traceback import weakref from collections import defaultdict from pathlib import Path from types import ModuleType from zipimport import zipimporter import django from django.apps import apps from django.core.signals import request_finished from django.dispatch import Signal from django.utils.functional import cached_property from django.utils.version import get_version_tuple autoreload_started = Signal() file_changed = Signal() DJANGO_AUTORELOAD_ENV = "RUN_MAIN" logger = logging.getLogger("django.utils.autoreload") # If an error is raised while importing a file, it's not placed in sys.modules. # This means that any future modifications aren't caught. Keep a list of these # file paths to allow watching them in the future. _error_files = [] _exception = None try: import termios except ImportError: termios = None try: import pywatchman except ImportError: pywatchman = None def is_django_module(module): """Return True if the given module is nested under Django.""" return module.__name__.startswith("django.") def is_django_path(path): """Return True if the given file path is nested under Django.""" return Path(django.__file__).parent in Path(path).parents def check_errors(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): global _exception try: fn(*args, **kwargs) except Exception: _exception = sys.exc_info() et, ev, tb = _exception if getattr(ev, "filename", None) is None: # get the filename from the last item in the stack filename = traceback.extract_tb(tb)[-1][0] else: filename = ev.filename if filename not in _error_files: _error_files.append(filename) raise return wrapper def raise_last_exception(): global _exception if _exception is not None: raise _exception[1] def ensure_echo_on(): """ Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload. """ if not termios or not sys.stdin.isatty(): return attr_list = termios.tcgetattr(sys.stdin) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, "SIGTTOU"): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler) def iter_all_python_module_files(): # This is a hot path during reloading. Create a stable sorted list of # modules based on the module name and pass it to iter_modules_and_files(). # This ensures cached results are returned in the usual case that modules # aren't loaded on the fly. keys = sorted(sys.modules) modules = tuple( m for m in map(sys.modules.__getitem__, keys) if not isinstance(m, weakref.ProxyTypes) ) return iter_modules_and_files(modules, frozenset(_error_files)) @functools.lru_cache(maxsize=1) def iter_modules_and_files(modules, extra_files): """Iterate through all modules needed to be watched.""" sys_file_paths = [] for module in modules: # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to sys.modules, however they are types not modules and so # cause issues here. if not isinstance(module, ModuleType): continue if module.__name__ == "__main__": # __main__ (usually manage.py) doesn't always have a __spec__ set. # Handle this by falling back to using __file__, resolved below. # See https://docs.python.org/reference/import.html#main-spec # __file__ may not exists, e.g. when running ipdb debugger. if hasattr(module, "__file__"): sys_file_paths.append(module.__file__) continue if getattr(module, "__spec__", None) is None: continue spec = module.__spec__ # Modules could be loaded from places without a concrete location. If # this is the case, skip them. if spec.has_location: origin = ( spec.loader.archive if isinstance(spec.loader, zipimporter) else spec.origin ) sys_file_paths.append(origin) results = set() for filename in itertools.chain(sys_file_paths, extra_files): if not filename: continue path = Path(filename) try: if not path.exists(): # The module could have been removed, don't fail loudly if this # is the case. continue except ValueError as e: # Network filesystems may return null bytes in file paths. logger.debug('"%s" raised when resolving path: "%s"', e, path) continue resolved_path = path.resolve().absolute() results.add(resolved_path) return frozenset(results) @functools.lru_cache(maxsize=1) def common_roots(paths): """ Return a tuple of common roots that are shared between the given paths. File system watchers operate on directories and aren't cheap to create. Try to find the minimum set of directories to watch that encompass all of the files that need to be watched. """ # Inspired from Werkzeug: # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py # Create a sorted list of the path components, longest first. path_parts = sorted([x.parts for x in paths], key=len, reverse=True) tree = {} for chunks in path_parts: node = tree # Add each part of the path to the tree. for chunk in chunks: node = node.setdefault(chunk, {}) # Clear the last leaf in the tree. node.clear() # Turn the tree into a list of Path instances. def _walk(node, path): for prefix, child in node.items(): yield from _walk(child, path + (prefix,)) if not node: yield Path(*path) return tuple(_walk(tree, ())) def sys_path_directories(): """ Yield absolute directories from sys.path, ignoring entries that don't exist. """ for path in sys.path: path = Path(path) if not path.exists(): continue resolved_path = path.resolve().absolute() # If the path is a file (like a zip file), watch the parent directory. if resolved_path.is_file(): yield resolved_path.parent else: yield resolved_path def get_child_arguments(): """ Return the executable. This contains a workaround for Windows if the executable is reported to not have the .exe extension which can cause bugs on reloading. """ import __main__ py_script = Path(sys.argv[0]) args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions] if sys.implementation.name == "cpython": args.extend( f"-X{key}" if value is True else f"-X{key}={value}" for key, value in sys._xoptions.items() ) # __spec__ is set when the server was started with the `-m` option, # see https://docs.python.org/3/reference/import.html#main-spec # __spec__ may not exist, e.g. when running in a Conda env. if getattr(__main__, "__spec__", None) is not None: spec = __main__.__spec__ if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent: name = spec.parent else: name = spec.name args += ["-m", name] args += sys.argv[1:] elif not py_script.exists(): # sys.argv[0] may not exist for several reasons on Windows. # It may exist with a .exe extension or have a -script.py suffix. exe_entrypoint = py_script.with_suffix(".exe") if exe_entrypoint.exists(): # Should be executed directly, ignoring sys.executable. return [exe_entrypoint, *sys.argv[1:]] script_entrypoint = py_script.with_name("%s-script.py" % py_script.name) if script_entrypoint.exists(): # Should be executed as usual. return [*args, script_entrypoint, *sys.argv[1:]] raise RuntimeError("Script %s does not exist." % py_script) else: args += sys.argv return args def trigger_reload(filename): logger.info("%s changed, reloading.", filename) sys.exit(3) def restart_with_reloader(): new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: "true"} args = get_child_arguments() while True: p = subprocess.run(args, env=new_environ, close_fds=False) if p.returncode != 3: return p.returncode class BaseReloader: def __init__(self): self.extra_files = set() self.directory_globs = defaultdict(set) self._stop_condition = threading.Event() def watch_dir(self, path, glob): path = Path(path) try: path = path.absolute() except FileNotFoundError: logger.debug( "Unable to watch directory %s as it cannot be resolved.", path, exc_info=True, ) return logger.debug("Watching dir %s with glob %s.", path, glob) self.directory_globs[path].add(glob) def watched_files(self, include_globs=True): """ Yield all files that need to be watched, including module files and files within globs. """ yield from iter_all_python_module_files() yield from self.extra_files if include_globs: for directory, patterns in self.directory_globs.items(): for pattern in patterns: yield from directory.glob(pattern) def wait_for_apps_ready(self, app_reg, django_main_thread): """ Wait until Django reports that the apps have been loaded. If the given thread has terminated before the apps are ready, then a SyntaxError or other non-recoverable error has been raised. In that case, stop waiting for the apps_ready event and continue processing. Return True if the thread is alive and the ready event has been triggered, or False if the thread is terminated while waiting for the event. """ while django_main_thread.is_alive(): if app_reg.ready_event.wait(timeout=0.1): return True else: logger.debug("Main Django thread has terminated before apps are ready.") return False def run(self, django_main_thread): logger.debug("Waiting for apps ready_event.") self.wait_for_apps_ready(apps, django_main_thread) from django.urls import get_resolver # Prevent a race condition where URL modules aren't loaded when the # reloader starts by accessing the urlconf_module property. try: get_resolver().urlconf_module except Exception: # Loading the urlconf can result in errors during development. # If this occurs then swallow the error and continue. pass logger.debug("Apps ready_event triggered. Sending autoreload_started signal.") autoreload_started.send(sender=self) self.run_loop() def run_loop(self): ticker = self.tick() while not self.should_stop: try: next(ticker) except StopIteration: break self.stop() def tick(self): """ This generator is called in a loop from run_loop. It's important that the method takes care of pausing or otherwise waiting for a period of time. This split between run_loop() and tick() is to improve the testability of the reloader implementations by decoupling the work they do from the loop. """ raise NotImplementedError("subclasses must implement tick().") @classmethod def check_availability(cls): raise NotImplementedError("subclasses must implement check_availability().") def notify_file_changed(self, path): results = file_changed.send(sender=self, file_path=path) logger.debug("%s notified as changed. Signal results: %s.", path, results) if not any(res[1] for res in results): trigger_reload(path) # These are primarily used for testing. @property def should_stop(self): return self._stop_condition.is_set() def stop(self): self._stop_condition.set() class StatReloader(BaseReloader): SLEEP_TIME = 1 # Check for changes once per second. def tick(self): mtimes = {} while True: for filepath, mtime in self.snapshot_files(): old_time = mtimes.get(filepath) mtimes[filepath] = mtime if old_time is None: logger.debug("File %s first seen with mtime %s", filepath, mtime) continue elif mtime > old_time: logger.debug( "File %s previous mtime: %s, current mtime: %s", filepath, old_time, mtime, ) self.notify_file_changed(filepath) time.sleep(self.SLEEP_TIME) yield def snapshot_files(self): # watched_files may produce duplicate paths if globs overlap. seen_files = set() for file in self.watched_files(): if file in seen_files: continue try: mtime = file.stat().st_mtime except OSError: # This is thrown when the file does not exist. continue seen_files.add(file) yield file, mtime @classmethod def check_availability(cls): return True class WatchmanUnavailable(RuntimeError): pass class WatchmanReloader(BaseReloader): def __init__(self): self.roots = defaultdict(set) self.processed_request = threading.Event() self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5)) super().__init__() @cached_property def client(self): return pywatchman.client(timeout=self.client_timeout) def _watch_root(self, root): # In practice this shouldn't occur, however, it's possible that a # directory that doesn't exist yet is being watched. If it's outside of # sys.path then this will end up a new root. How to handle this isn't # clear: Not adding the root will likely break when subscribing to the # changes, however, as this is currently an internal API, no files # will be being watched outside of sys.path. Fixing this by checking # inside watch_glob() and watch_dir() is expensive, instead this could # could fall back to the StatReloader if this case is detected? For # now, watching its parent, if possible, is sufficient. if not root.exists(): if not root.parent.exists(): logger.warning( "Unable to watch root dir %s as neither it or its parent exist.", root, ) return root = root.parent result = self.client.query("watch-project", str(root.absolute())) if "warning" in result: logger.warning("Watchman warning: %s", result["warning"]) logger.debug("Watchman watch-project result: %s", result) return result["watch"], result.get("relative_path") @functools.lru_cache def _get_clock(self, root): return self.client.query("clock", root)["clock"] def _subscribe(self, directory, name, expression): root, rel_path = self._watch_root(directory) # Only receive notifications of files changing, filtering out other types # like special files: https://facebook.github.io/watchman/docs/type only_files_expression = [ "allof", ["anyof", ["type", "f"], ["type", "l"]], expression, ] query = { "expression": only_files_expression, "fields": ["name"], "since": self._get_clock(root), "dedup_results": True, } if rel_path: query["relative_root"] = rel_path logger.debug( "Issuing watchman subscription %s, for root %s. Query: %s", name, root, query, ) self.client.query("subscribe", root, name, query) def _subscribe_dir(self, directory, filenames): if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "files-parent-%s" % directory.name filenames = ["%s/%s" % (directory.name, filename) for filename in filenames] directory = directory.parent expression = ["name", filenames, "wholename"] else: prefix = "files" expression = ["name", filenames] self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def _watch_glob(self, directory, patterns): """ Watch a directory with a specific glob. If the directory doesn't yet exist, attempt to watch the parent directory and amend the patterns to include this. It's important this method isn't called more than one per directory when updating all subscriptions. Subsequent calls will overwrite the named subscription, so it must include all possible glob expressions. """ prefix = "glob" if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "glob-parent-%s" % directory.name patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns] directory = directory.parent expression = ["anyof"] for pattern in patterns: expression.append(["match", pattern, "wholename"]) self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def watched_roots(self, watched_files): extra_directories = self.directory_globs.keys() watched_file_dirs = [f.parent for f in watched_files] sys_paths = list(sys_path_directories()) return frozenset((*extra_directories, *watched_file_dirs, *sys_paths)) def _update_watches(self): watched_files = list(self.watched_files(include_globs=False)) found_roots = common_roots(self.watched_roots(watched_files)) logger.debug("Watching %s files", len(watched_files)) logger.debug("Found common roots: %s", found_roots) # Setup initial roots for performance, shortest roots first. for root in sorted(found_roots): self._watch_root(root) for directory, patterns in self.directory_globs.items(): self._watch_glob(directory, patterns) # Group sorted watched_files by their parent directory. sorted_files = sorted(watched_files, key=lambda p: p.parent) for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent): # These paths need to be relative to the parent directory. self._subscribe_dir( directory, [str(p.relative_to(directory)) for p in group] ) def update_watches(self): try: self._update_watches() except Exception as ex: # If the service is still available, raise the original exception. if self.check_server_status(ex): raise def _check_subscription(self, sub): subscription = self.client.getSubscription(sub) if not subscription: return logger.debug("Watchman subscription %s has results.", sub) for result in subscription: # When using watch-project, it's not simple to get the relative # directory without storing some specific state. Store the full # path to the directory in the subscription name, prefixed by its # type (glob, files). root_directory = Path(result["subscription"].split(":", 1)[1]) logger.debug("Found root directory %s", root_directory) for file in result.get("files", []): self.notify_file_changed(root_directory / file) def request_processed(self, **kwargs): logger.debug("Request processed. Setting update_watches event.") self.processed_request.set() def tick(self): request_finished.connect(self.request_processed) self.update_watches() while True: if self.processed_request.is_set(): self.update_watches() self.processed_request.clear() try: self.client.receive() except pywatchman.SocketTimeout: pass except pywatchman.WatchmanError as ex: logger.debug("Watchman error: %s, checking server status.", ex) self.check_server_status(ex) else: for sub in list(self.client.subs.keys()): self._check_subscription(sub) yield # Protect against busy loops. time.sleep(0.1) def stop(self): self.client.close() super().stop() def check_server_status(self, inner_ex=None): """Return True if the server is available.""" try: self.client.query("version") except Exception: raise WatchmanUnavailable(str(inner_ex)) from inner_ex return True @classmethod def check_availability(cls): if not pywatchman: raise WatchmanUnavailable("pywatchman not installed.") client = pywatchman.client(timeout=0.1) try: result = client.capabilityCheck() except Exception: # The service is down? raise WatchmanUnavailable("Cannot connect to the watchman service.") version = get_version_tuple(result["version"]) # Watchman 4.9 includes multiple improvements to watching project # directories as well as case insensitive filesystems. logger.debug("Watchman version %s", version) if version < (4, 9): raise WatchmanUnavailable("Watchman 4.9 or later is required.") def get_reloader(): """Return the most suitable reloader for this environment.""" try: WatchmanReloader.check_availability() except WatchmanUnavailable: return StatReloader() return WatchmanReloader() def start_django(reloader, main_func, *args, **kwargs): ensure_echo_on() main_func = check_errors(main_func) django_main_thread = threading.Thread( target=main_func, args=args, kwargs=kwargs, name="django-main-thread" ) django_main_thread.daemon = True django_main_thread.start() while not reloader.should_stop: try: reloader.run(django_main_thread) except WatchmanUnavailable as ex: # It's possible that the watchman service shuts down or otherwise # becomes unavailable. In that case, use the StatReloader. reloader = StatReloader() logger.error("Error connecting to Watchman: %s", ex) logger.info( "Watching for file changes with %s", reloader.__class__.__name__ ) def run_with_reloader(main_func, *args, **kwargs): signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) try: if os.environ.get(DJANGO_AUTORELOAD_ENV) == "true": reloader = get_reloader() logger.info( "Watching for file changes with %s", reloader.__class__.__name__ ) start_django(reloader, main_func, *args, **kwargs) else: exit_code = restart_with_reloader() sys.exit(exit_code) except KeyboardInterrupt: pass
90bbea7bf35dcf56eaab670b7e7ce7570449405716975458ff00279553b9d7ac
import re import unicodedata from gzip import GzipFile from gzip import compress as gzip_compress from io import BytesIO from django.core.exceptions import SuspiciousFileOperation from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy, pgettext @keep_lazy_text def capfirst(x): """Capitalize the first letter of a string.""" if not x: return x if not isinstance(x, str): x = str(x) return x[0].upper() + x[1:] # Set up regular expressions re_words = _lazy_re_compile(r"<[^>]+?>|([^<>\s]+)", re.S) re_chars = _lazy_re_compile(r"<[^>]+?>|(.)", re.S) re_tag = _lazy_re_compile(r"<(/)?(\S+?)(?:(\s*/)|\s.*?)?>", re.S) re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))") @keep_lazy_text def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. Preserve all white space except added line breaks consume the space on which they break the line. Don't wrap long words, thus the output text may have lines longer than ``width``. """ def _generator(): for line in text.splitlines(True): # True keeps trailing linebreaks max_width = min((line.endswith("\n") and width + 1 or width), width) while len(line) > max_width: space = line[: max_width + 1].rfind(" ") + 1 if space == 0: space = line.find(" ") + 1 if space == 0: yield line line = "" break yield "%s\n" % line[: space - 1] line = line[space:] max_width = min((line.endswith("\n") and width + 1 or width), width) if line: yield line return "".join(_generator()) class Truncator(SimpleLazyObject): """ An object used to truncate text, either by characters or words. """ def __init__(self, text): super().__init__(lambda: str(text)) def add_truncation_text(self, text, truncate=None): if truncate is None: truncate = pgettext( "String to return when truncating text", "%(truncated_text)s…" ) if "%(truncated_text)s" in truncate: return truncate % {"truncated_text": text} # The truncation text didn't contain the %(truncated_text)s string # replacement argument so just append it to the text. if text.endswith(truncate): # But don't append the truncation text if the current text already # ends in this. return text return "%s%s" % (text, truncate) def chars(self, num, truncate=None, html=False): """ Return the text truncated to be no longer than the specified number of characters. `truncate` specifies what should be used to notify that the string has been truncated, defaulting to a translatable string of an ellipsis. """ self._setup() length = int(num) text = unicodedata.normalize("NFC", self._wrapped) # Calculate the length to truncate to (max length - end_text length) truncate_len = length for char in self.add_truncation_text("", truncate): if not unicodedata.combining(char): truncate_len -= 1 if truncate_len == 0: break if html: return self._truncate_html(length, truncate, text, truncate_len, False) return self._text_chars(length, truncate, text, truncate_len) def _text_chars(self, length, truncate, text, truncate_len): """Truncate a string after a certain number of chars.""" s_len = 0 end_index = None for i, char in enumerate(text): if unicodedata.combining(char): # Don't consider combining characters # as adding to the string length continue s_len += 1 if end_index is None and s_len > truncate_len: end_index = i if s_len > length: # Return the truncated string return self.add_truncation_text(text[: end_index or 0], truncate) # Return the original string since no truncation was necessary return text def words(self, num, truncate=None, html=False): """ Truncate a string after a certain number of words. `truncate` specifies what should be used to notify that the string has been truncated, defaulting to ellipsis. """ self._setup() length = int(num) if html: return self._truncate_html(length, truncate, self._wrapped, length, True) return self._text_words(length, truncate) def _text_words(self, length, truncate): """ Truncate a string after a certain number of words. Strip newlines in the string. """ words = self._wrapped.split() if len(words) > length: words = words[:length] return self.add_truncation_text(" ".join(words), truncate) return " ".join(words) def _truncate_html(self, length, truncate, text, truncate_len, words): """ Truncate HTML to a certain number of chars (not counting tags and comments), or, if words is True, then to a certain number of words. Close opened tags if they were correctly closed in the given HTML. Preserve newlines in the HTML. """ if words and length <= 0: return "" html4_singlets = ( "br", "col", "link", "base", "img", "param", "area", "hr", "input", ) # Count non-HTML chars/words and keep note of open tags pos = 0 end_text_pos = 0 current_len = 0 open_tags = [] regex = re_words if words else re_chars while current_len <= length: m = regex.search(text, pos) if not m: # Checked through whole string break pos = m.end(0) if m[1]: # It's an actual non-HTML word or char current_len += 1 if current_len == truncate_len: end_text_pos = pos continue # Check for tag tag = re_tag.match(m[0]) if not tag or current_len >= truncate_len: # Don't worry about non tags or tags after our truncate point continue closing_tag, tagname, self_closing = tag.groups() # Element names are always case-insensitive tagname = tagname.lower() if self_closing or tagname in html4_singlets: pass elif closing_tag: # Check for match in open tags list try: i = open_tags.index(tagname) except ValueError: pass else: # SGML: An end tag closes, back to the matching start tag, # all unclosed intervening start tags with omitted end tags open_tags = open_tags[i + 1 :] else: # Add it to the start of the open tags list open_tags.insert(0, tagname) if current_len <= length: return text out = text[:end_text_pos] truncate_text = self.add_truncation_text("", truncate) if truncate_text: out += truncate_text # Close any tags still open for tag in open_tags: out += "</%s>" % tag # Return string return out @keep_lazy_text def get_valid_filename(name): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = str(name).strip().replace(" ", "_") s = re.sub(r"(?u)[^-\w.]", "", s) if s in {"", ".", ".."}: raise SuspiciousFileOperation("Could not derive file name from '%s'" % name) return s @keep_lazy_text def get_text_list(list_, last_word=gettext_lazy("or")): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' """ if not list_: return "" if len(list_) == 1: return str(list_[0]) return "%s %s %s" % ( # Translators: This string is used as a separator between list elements _(", ").join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1]), ) @keep_lazy_text def normalize_newlines(text): """Normalize CRLF and CR newlines to just LF.""" return re_newlines.sub("\n", str(text)) @keep_lazy_text def phone2numeric(phone): """Convert a phone number with letters into its numeric equivalent.""" char2number = { "a": "2", "b": "2", "c": "2", "d": "3", "e": "3", "f": "3", "g": "4", "h": "4", "i": "4", "j": "5", "k": "5", "l": "5", "m": "6", "n": "6", "o": "6", "p": "7", "q": "7", "r": "7", "s": "7", "t": "8", "u": "8", "v": "8", "w": "9", "x": "9", "y": "9", "z": "9", } return "".join(char2number.get(c, c) for c in phone.lower()) def compress_string(s): return gzip_compress(s, compresslevel=6, mtime=0) class StreamingBuffer(BytesIO): def read(self): ret = self.getvalue() self.seek(0) self.truncate() return ret # Like compress_string, but for iterators of strings. def compress_sequence(sequence): buf = StreamingBuffer() with GzipFile(mode="wb", compresslevel=6, fileobj=buf, mtime=0) as zfile: # Output headers... yield buf.read() for item in sequence: zfile.write(item) data = buf.read() if data: yield data yield buf.read() # Expression to match some_token and some_token="with spaces" (and similarly # for single-quoted strings). smart_split_re = _lazy_re_compile( r""" ((?: [^\s'"]* (?: (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*') [^\s'"]* )+ ) | \S+) """, re.VERBOSE, ) def smart_split(text): r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then be further processed with unescape_string_literal()). >>> list(smart_split(r'This is "a person\'s" test.')) ['This', 'is', '"a person\\\'s"', 'test.'] >>> list(smart_split(r"Another 'person\'s' test.")) ['Another', "'person\\'s'", 'test.'] >>> list(smart_split(r'A "\"funky\" style" test.')) ['A', '"\\"funky\\" style"', 'test.'] """ for bit in smart_split_re.finditer(str(text)): yield bit[0] @keep_lazy_text def unescape_string_literal(s): r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted:: >>> unescape_string_literal('"abc"') 'abc' >>> unescape_string_literal("'abc'") 'abc' >>> unescape_string_literal('"a \"bc\""') 'a "bc"' >>> unescape_string_literal("'\'ab\' c'") "'ab' c" """ if not s or s[0] not in "\"'" or s[-1] != s[0]: raise ValueError("Not a string literal: %r" % s) quote = s[0] return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\") @keep_lazy_text def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace, dashes, and underscores. """ value = str(value) if allow_unicode: value = unicodedata.normalize("NFKC", value) else: value = ( unicodedata.normalize("NFKD", value) .encode("ascii", "ignore") .decode("ascii") ) value = re.sub(r"[^\w\s-]", "", value.lower()) return re.sub(r"[-\s]+", "-", value).strip("-_") def camel_case_to_spaces(value): """ Split CamelCase and convert to lowercase. Strip surrounding whitespace. """ return re_camel_case.sub(r" \1", value).strip().lower() def _format_lazy(format_string, *args, **kwargs): """ Apply str.format() on 'format_string' where format_string, args, and/or kwargs might be lazy. """ return format_string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str)
c2c5f486aac79e93ec44b689c3eef2847c802c94abd25423f9cef8ba9fed7508
"""Functions to parse datetime objects.""" # We're using regular expressions rather than time.strptime because: # - They provide both validation and parsing. # - They're more flexible for datetimes. # - The date/datetime/time constructors produce friendlier error messages. import datetime from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import get_fixed_timezone, utc date_re = _lazy_re_compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") time_re = _lazy_re_compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:[\.,](?P<microsecond>\d{1,6})\d{0,6})?)?$" ) datetime_re = _lazy_re_compile( r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})" r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:[\.,](?P<microsecond>\d{1,6})\d{0,6})?)?" r"\s*(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$" ) standard_duration_re = _lazy_re_compile( r"^" r"(?:(?P<days>-?\d+) (days?, )?)?" r"(?P<sign>-?)" r"((?:(?P<hours>\d+):)(?=\d+:\d+))?" r"(?:(?P<minutes>\d+):)?" r"(?P<seconds>\d+)" r"(?:[\.,](?P<microseconds>\d{1,6})\d{0,6})?" r"$" ) # Support the sections of ISO 8601 date representation that are accepted by # timedelta iso8601_duration_re = _lazy_re_compile( r"^(?P<sign>[-+]?)" r"P" r"(?:(?P<days>\d+([\.,]\d+)?)D)?" r"(?:T" r"(?:(?P<hours>\d+([\.,]\d+)?)H)?" r"(?:(?P<minutes>\d+([\.,]\d+)?)M)?" r"(?:(?P<seconds>\d+([\.,]\d+)?)S)?" r")?" r"$" ) # Support PostgreSQL's day-time interval format, e.g. "3 days 04:05:06". The # year-month and mixed intervals cannot be converted to a timedelta and thus # aren't accepted. postgres_interval_re = _lazy_re_compile( r"^" r"(?:(?P<days>-?\d+) (days? ?))?" r"(?:(?P<sign>[-+])?" r"(?P<hours>\d+):" r"(?P<minutes>\d\d):" r"(?P<seconds>\d\d)" r"(?:\.(?P<microseconds>\d{1,6}))?" r")?$" ) def parse_date(value): """Parse a string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Return None if the input isn't well formatted. """ try: return datetime.date.fromisoformat(value) except ValueError: if match := date_re.match(value): kw = {k: int(v) for k, v in match.groupdict().items()} return datetime.date(**kw) def parse_time(value): """Parse a string and return a datetime.time. This function doesn't support time zone offsets. Raise ValueError if the input is well formatted but not a valid time. Return None if the input isn't well formatted, in particular if it contains an offset. """ try: # The fromisoformat() method takes time zone info into account and # returns a time with a tzinfo component, if possible. However, there # are no circumstances where aware datetime.time objects make sense, so # remove the time zone offset. return datetime.time.fromisoformat(value).replace(tzinfo=None) except ValueError: if match := time_re.match(value): kw = match.groupdict() kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") kw = {k: int(v) for k, v in kw.items() if v is not None} return datetime.time(**kw) def parse_datetime(value): """Parse a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Return None if the input isn't well formatted. """ try: return datetime.datetime.fromisoformat(value) except ValueError: if match := datetime_re.match(value): kw = match.groupdict() kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") tzinfo = kw.pop("tzinfo") if tzinfo == "Z": tzinfo = utc elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == "-": offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in kw.items() if v is not None} return datetime.datetime(**kw, tzinfo=tzinfo) def parse_duration(value): """Parse a duration string and return a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation and PostgreSQL's day-time interval format. """ match = ( standard_duration_re.match(value) or iso8601_duration_re.match(value) or postgres_interval_re.match(value) ) if match: kw = match.groupdict() sign = -1 if kw.pop("sign", "+") == "-" else 1 if kw.get("microseconds"): kw["microseconds"] = kw["microseconds"].ljust(6, "0") kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None} days = datetime.timedelta(kw.pop("days", 0.0) or 0.0) if match.re == iso8601_duration_re: days *= sign return days + sign * datetime.timedelta(**kw)
2ec820788e2f8659f7027fd85cd064d9c0b028b42031ef8eff72fefa3de8dc63
""" Utilities for XML generation/parsing. """ import re from xml.sax.saxutils import XMLGenerator class UnserializableContentError(ValueError): pass class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents) self.endElement(name) def characters(self, content): if content and re.search(r"[\x00-\x08\x0B-\x0C\x0E-\x1F]", content): # Fail loudly when content has control chars (unsupported in XML 1.0) # See https://www.w3.org/International/questions/qa-controls raise UnserializableContentError( "Control characters are not supported in XML 1.0" ) XMLGenerator.characters(self, content) def startElement(self, name, attrs): # Sort attrs for a deterministic output. sorted_attrs = dict(sorted(attrs.items())) if attrs else attrs super().startElement(name, sorted_attrs)
5bfc51f1e9e7f1c63a5b8a0cf0cd939e889d6db89865b4e17dd23a50c238fa07
class CyclicDependencyError(ValueError): pass def topological_sort_as_sets(dependency_graph): """ Variation of Kahn's algorithm (1962) that returns sets. Take a dependency graph as a dictionary of node => dependencies. Yield sets of items in topological order, where the first set contains all nodes without dependencies, and each following set contains all nodes that may depend on the nodes only in the previously yielded sets. """ todo = dependency_graph.copy() while todo: current = {node for node, deps in todo.items() if not deps} if not current: raise CyclicDependencyError( "Cyclic dependency in graph: {}".format( ", ".join(repr(x) for x in todo.items()) ) ) yield current # remove current from todo's nodes & dependencies todo = { node: (dependencies - current) for node, dependencies in todo.items() if node not in current } def stable_topological_sort(nodes, dependency_graph): result = [] for layer in topological_sort_as_sets(dependency_graph): for node in nodes: if node in layer: result.append(node) return result
f7d0da84ca48f788600402edd34f9519a37d34c62325f6f8587714f6d9dec124
from decimal import Decimal from django.conf import settings from django.utils.safestring import mark_safe def format( number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep="", force_grouping=False, use_l10n=None, ): """ Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-uniform digit grouping, it can be a sequence with the number of digit group sizes following the format used by the Python locale module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example ",") """ use_grouping = ( use_l10n or (use_l10n is None and settings.USE_L10N) ) and settings.USE_THOUSAND_SEPARATOR use_grouping = use_grouping or force_grouping use_grouping = use_grouping and grouping != 0 # Make the common case fast if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(number) # sign sign = "" # Treat potentially very large/small floats as Decimals. if isinstance(number, float) and "e" in str(number).lower(): number = Decimal(str(number)) if isinstance(number, Decimal): if decimal_pos is not None: # If the provided number is too small to affect any of the visible # decimal places, consider it equal to '0'. cutoff = Decimal("0." + "1".rjust(decimal_pos, "0")) if abs(number) < cutoff: number = Decimal("0") # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponent = number.as_tuple() if abs(exponent) + len(digits) > 200: number = "{:e}".format(number) coefficient, exponent = number.split("e") # Format the coefficient. coefficient = format( coefficient, decimal_sep, decimal_pos, grouping, thousand_sep, force_grouping, use_l10n, ) return "{}e{}".format(coefficient, exponent) else: str_number = "{:f}".format(number) else: str_number = str(number) if str_number[0] == "-": sign = "-" str_number = str_number[1:] # decimal part if "." in str_number: int_part, dec_part = str_number.split(".") if decimal_pos is not None: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, "" if decimal_pos is not None: dec_part = dec_part + ("0" * (decimal_pos - len(dec_part))) dec_part = dec_part and decimal_sep + dec_part # grouping if use_grouping: try: # if grouping is a sequence intervals = list(grouping) except TypeError: # grouping is a single value intervals = [grouping, 0] active_interval = intervals.pop(0) int_part_gd = "" cnt = 0 for digit in int_part[::-1]: if cnt and cnt == active_interval: if intervals: active_interval = intervals.pop(0) or active_interval int_part_gd += thousand_sep[::-1] cnt = 0 int_part_gd += digit cnt += 1 int_part = int_part_gd[::-1] return sign + int_part + dec_part
5777dfdd20bd154a2766bf27a2f6113e72a8f1c74cf4275f06a3deca65cd3212
import datetime import functools import os import subprocess import sys from django.utils.regex_helper import _lazy_re_compile # Private, stable API for detecting the Python version. PYXY means "Python X.Y # or later". So that third-party apps can use these values, each constant # should remain as long as the oldest supported Django version supports that # Python version. PY36 = sys.version_info >= (3, 6) PY37 = sys.version_info >= (3, 7) PY38 = sys.version_info >= (3, 8) PY39 = sys.version_info >= (3, 9) PY310 = sys.version_info >= (3, 10) PY311 = sys.version_info >= (3, 11) def get_version(version=None): """Return a PEP 440-compliant version number from VERSION.""" version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases main = get_main_version(version) sub = "" if version[3] == "alpha" and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = ".dev%s" % git_changeset elif version[3] != "final": mapping = {"alpha": "a", "beta": "b", "rc": "rc"} sub = mapping[version[3]] + str(version[4]) return main + sub def get_main_version(version=None): """Return main version (X.Y[.Z]) from VERSION.""" version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return ".".join(str(x) for x in version[:parts]) def get_complete_version(version=None): """ Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ("alpha", "beta", "rc", "final") return version def get_docs_version(version=None): version = get_complete_version(version) if version[3] != "final": return "dev" else: return "%d.%d" % version[:2] @functools.lru_cache def get_git_changeset(): """Return a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ # Repository may not be found if __file__ is undefined, e.g. in a frozen # module. if "__file__" not in globals(): return None repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.run( "git log --pretty=format:%ct --quiet -1 HEAD", capture_output=True, shell=True, cwd=repo_dir, text=True, ) timestamp = git_log.stdout tz = datetime.timezone.utc try: timestamp = datetime.datetime.fromtimestamp(int(timestamp), tz=tz) except ValueError: return None return timestamp.strftime("%Y%m%d%H%M%S") version_component_re = _lazy_re_compile(r"(\d+|[a-z]+|\.)") def get_version_tuple(version): """ Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3'). """ version_numbers = [] for item in version_component_re.split(version): if item and item != ".": try: component = int(item) except ValueError: break else: version_numbers.append(component) return tuple(version_numbers)
ccf06b02a7ae8ad737d38ee1349ae28fe02c7aeadd55b480e2d18d6ac8b1af3a
""" Timezone-related classes and functions. """ import functools import sys import warnings try: import zoneinfo except ImportError: from backports import zoneinfo from contextlib import ContextDecorator from datetime import datetime, timedelta, timezone, tzinfo from asgiref.local import Local from django.conf import settings from django.utils.deprecation import RemovedInDjango50Warning __all__ = [ "utc", "get_fixed_timezone", "get_default_timezone", "get_default_timezone_name", "get_current_timezone", "get_current_timezone_name", "activate", "deactivate", "override", "localtime", "now", "is_aware", "is_naive", "make_aware", "make_naive", ] # RemovedInDjango50Warning: sentinel for deprecation of is_dst parameters. NOT_PASSED = object() utc = timezone.utc def get_fixed_timezone(offset): """Return a tzinfo instance with a fixed offset from UTC.""" if isinstance(offset, timedelta): offset = offset.total_seconds() // 60 sign = "-" if offset < 0 else "+" hhmm = "%02d%02d" % divmod(abs(offset), 60) name = sign + hhmm return timezone(timedelta(minutes=offset), name) # In order to avoid accessing settings at compile time, # wrap the logic in a function and cache the result. @functools.lru_cache def get_default_timezone(): """ Return the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. """ if settings.USE_DEPRECATED_PYTZ: import pytz return pytz.timezone(settings.TIME_ZONE) return zoneinfo.ZoneInfo(settings.TIME_ZONE) # This function exists for consistency with get_current_timezone_name def get_default_timezone_name(): """Return the name of the default time zone.""" return _get_timezone_name(get_default_timezone()) _active = Local() def get_current_timezone(): """Return the currently active time zone as a tzinfo instance.""" return getattr(_active, "value", get_default_timezone()) def get_current_timezone_name(): """Return the name of the currently active time zone.""" return _get_timezone_name(get_current_timezone()) def _get_timezone_name(timezone): """ Return the offset for fixed offset timezones, or the name of timezone if not set. """ return timezone.tzname(None) or str(timezone) # Timezone selection functions. # These functions don't change os.environ['TZ'] and call time.tzset() # because it isn't thread safe. def activate(timezone): """ Set the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, str): if settings.USE_DEPRECATED_PYTZ: import pytz _active.value = pytz.timezone(timezone) else: _active.value = zoneinfo.ZoneInfo(timezone) else: raise ValueError("Invalid timezone: %r" % timezone) def deactivate(): """ Unset the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value class override(ContextDecorator): """ Temporarily set the time zone for the current thread. This is a context manager that uses django.utils.timezone.activate() to set the timezone on entry and restores the previously active timezone on exit. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a time zone name, or ``None``. If it is ``None``, Django enables the default time zone. """ def __init__(self, timezone): self.timezone = timezone def __enter__(self): self.old_timezone = getattr(_active, "value", None) if self.timezone is None: deactivate() else: activate(self.timezone) def __exit__(self, exc_type, exc_value, traceback): if self.old_timezone is None: deactivate() else: _active.value = self.old_timezone # Templates def template_localtime(value, use_tz=None): """ Check if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = ( isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, "convert_to_local_time", True) ) return localtime(value) if should_convert else value # Utilities def localtime(value=None, timezone=None): """ Convert an aware datetime.datetime to local time. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ if value is None: value = now() if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("localtime() cannot be applied to a naive datetime") return value.astimezone(timezone) def localdate(value=None, timezone=None): """ Convert an aware datetime to local time and return the value's date. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ return localtime(value, timezone).date() def now(): """ Return an aware or naive datetime.datetime, depending on settings.USE_TZ. """ return datetime.now(tz=utc if settings.USE_TZ else None) # By design, these four functions don't perform any checks on their arguments. # The caller should ensure that they don't receive an invalid value like None. def is_aware(value): """ Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is not None def is_naive(value): """ Determine if a given datetime.datetime is naive. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is None def make_aware(value, timezone=None, is_dst=NOT_PASSED): """Make a naive datetime.datetime in a given time zone aware.""" if is_dst is NOT_PASSED: is_dst = None else: warnings.warn( "The is_dst argument to make_aware(), used by the Trunc() " "database functions and QuerySet.datetimes(), is deprecated as it " "has no effect with zoneinfo time zones.", RemovedInDjango50Warning, ) if timezone is None: timezone = get_current_timezone() if _is_pytz_zone(timezone): # This method is available for pytz time zones. return timezone.localize(value, is_dst=is_dst) else: # Check that we won't overwrite the timezone of an aware datetime. if is_aware(value): raise ValueError("make_aware expects a naive datetime, got %s" % value) # This may be wrong around DST changes! return value.replace(tzinfo=timezone) def make_naive(value, timezone=None): """Make an aware datetime.datetime naive in a given time zone.""" if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("make_naive() cannot be applied to a naive datetime") return value.astimezone(timezone).replace(tzinfo=None) _PYTZ_IMPORTED = False def _pytz_imported(): """ Detects whether or not pytz has been imported without importing pytz. Copied from pytz_deprecation_shim with thanks to Paul Ganssle. """ global _PYTZ_IMPORTED if not _PYTZ_IMPORTED and "pytz" in sys.modules: _PYTZ_IMPORTED = True return _PYTZ_IMPORTED def _is_pytz_zone(tz): """Checks if a zone is a pytz zone.""" # See if pytz was already imported rather than checking # settings.USE_DEPRECATED_PYTZ to *allow* manually passing a pytz timezone, # which some of the test cases (at least) rely on. if not _pytz_imported(): return False # If tz could be pytz, then pytz is needed here. import pytz _PYTZ_BASE_CLASSES = (pytz.tzinfo.BaseTzInfo, pytz._FixedOffset) # In releases prior to 2018.4, pytz.UTC was not a subclass of BaseTzInfo if not isinstance(pytz.UTC, pytz._FixedOffset): _PYTZ_BASE_CLASSES = _PYTZ_BASE_CLASSES + (type(pytz.UTC),) return isinstance(tz, _PYTZ_BASE_CLASSES) def _datetime_ambiguous_or_imaginary(dt, tz): if _is_pytz_zone(tz): import pytz try: tz.utcoffset(dt) except (pytz.AmbiguousTimeError, pytz.NonExistentTimeError): return True else: return False return tz.utcoffset(dt.replace(fold=not dt.fold)) != tz.utcoffset(dt)
8924f75085f81e86e6968dd8c5011358c3e28fb97fc2c66a56878e1e7cb2721b
""" A class for storing a tree graph. Primarily used for filter constructs in the ORM. """ import copy from django.utils.hashable import make_hashable class Node: """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances. """ # Standard connector type. Clients usually won't use this at all and # subclasses will usually override the value. default = "DEFAULT" def __init__(self, children=None, connector=None, negated=False): """Construct a new Node. If no connector is given, use the default.""" self.children = children[:] if children else [] self.connector = connector or self.default self.negated = negated # Required because django.db.models.query_utils.Q. Q. __init__() is # problematic, but it is a natural Node subclass in all other respects. @classmethod def _new_instance(cls, children=None, connector=None, negated=False): """ Create a new instance of this class when new Nodes (or subclasses) are needed in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature that aren't an extension of Node.__init__ might need to implement this method to allow a Node to create a new instance of them (if they have any extra setting up to do). """ obj = Node(children, connector, negated) obj.__class__ = cls return obj def __str__(self): template = "(NOT (%s: %s))" if self.negated else "(%s: %s)" return template % (self.connector, ", ".join(str(c) for c in self.children)) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def __deepcopy__(self, memodict): obj = Node(connector=self.connector, negated=self.negated) obj.__class__ = self.__class__ obj.children = copy.deepcopy(self.children, memodict) return obj def __len__(self): """Return the number of children this node has.""" return len(self.children) def __bool__(self): """Return whether or not this node has children.""" return bool(self.children) def __contains__(self, other): """Return True if 'other' is a direct child of this instance.""" return other in self.children def __eq__(self, other): return ( self.__class__ == other.__class__ and self.connector == other.connector and self.negated == other.negated and self.children == other.children ) def __hash__(self): return hash( ( self.__class__, self.connector, self.negated, *make_hashable(self.children), ) ) def add(self, data, conn_type): """ Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place of data regardless if the node other got squashed or not. """ if self.connector != conn_type: obj = self._new_instance(self.children, self.connector, self.negated) self.connector = conn_type self.children = [obj, data] return data elif ( isinstance(data, Node) and not data.negated and (data.connector == conn_type or len(data) == 1) ): # We can squash the other node's children directly into this node. # We are just doing (AB)(CD) == (ABCD) here, with the addition that # if the length of the other node is 1 the connector doesn't # matter. However, for the len(self) == 1 case we don't want to do # the squashing, as it would alter self.connector. self.children.extend(data.children) return self else: # We could use perhaps additional logic here to see if some # children could be used for pushdown here. self.children.append(data) return data def negate(self): """Negate the sense of the root connector.""" self.negated = not self.negated
c461f49ab0c0838b92d2341bbc36868b0cdc5f7c81be933b72eff0a107e7c31a
import asyncio import inspect import warnings from asgiref.sync import sync_to_async class RemovedInNextVersionWarning(DeprecationWarning): pass class RemovedInDjango50Warning(PendingDeprecationWarning): pass RemovedAfterNextVersionWarning = RemovedInDjango50Warning class warn_about_renamed_method: def __init__( self, class_name, old_method_name, new_method_name, deprecation_warning ): self.class_name = class_name self.old_method_name = old_method_name self.new_method_name = new_method_name self.deprecation_warning = deprecation_warning def __call__(self, f): def wrapped(*args, **kwargs): warnings.warn( "`%s.%s` is deprecated, use `%s` instead." % (self.class_name, self.old_method_name, self.new_method_name), self.deprecation_warning, 2, ) return f(*args, **kwargs) return wrapped class RenameMethodsBase(type): """ Handles the deprecation paths when renaming a method. It does the following: 1) Define the new method if missing and complain about it. 2) Define the old method if missing. 3) Complain whenever an old method is called. See #15363 for more details. """ renamed_methods = () def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ for renamed_method in cls.renamed_methods: old_method_name = renamed_method[0] old_method = base.__dict__.get(old_method_name) new_method_name = renamed_method[1] new_method = base.__dict__.get(new_method_name) deprecation_warning = renamed_method[2] wrapper = warn_about_renamed_method(class_name, *renamed_method) # Define the new method if missing and complain about it if not new_method and old_method: warnings.warn( "`%s.%s` method should be renamed `%s`." % (class_name, old_method_name, new_method_name), deprecation_warning, 2, ) setattr(base, new_method_name, old_method) setattr(base, old_method_name, wrapper(old_method)) # Define the old method as a wrapped call to the new method. if not old_method and new_method: setattr(base, old_method_name, wrapper(new_method)) return new_class class DeprecationInstanceCheck(type): def __instancecheck__(self, instance): warnings.warn( "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative), self.deprecation_warning, 2, ) return super().__instancecheck__(instance) class MiddlewareMixin: sync_capable = True async_capable = True def __init__(self, get_response): if get_response is None: raise ValueError("get_response must be provided.") self.get_response = get_response self._async_check() super().__init__() def __repr__(self): return "<%s get_response=%s>" % ( self.__class__.__qualname__, getattr( self.get_response, "__qualname__", self.get_response.__class__.__name__, ), ) def _async_check(self): """ If get_response is a coroutine function, turns us into async mode so a thread is not consumed during a whole request. """ if asyncio.iscoroutinefunction(self.get_response): # Mark the class as async-capable, but do the actual switch # inside __call__ to avoid swapping out dunder methods self._is_coroutine = asyncio.coroutines._is_coroutine else: self._is_coroutine = None def __call__(self, request): # Exit out to async mode, if needed if self._is_coroutine: return self.__acall__(request) response = None if hasattr(self, "process_request"): response = self.process_request(request) response = response or self.get_response(request) if hasattr(self, "process_response"): response = self.process_response(request, response) return response async def __acall__(self, request): """ Async version of __call__ that is swapped in when an async request is running. """ response = None if hasattr(self, "process_request"): response = await sync_to_async( self.process_request, thread_sensitive=True, )(request) response = response or await self.get_response(request) if hasattr(self, "process_response"): response = await sync_to_async( self.process_response, thread_sensitive=True, )(request, response) return response
20546f9c1d3e83d985d47f804bbdbf2c52198021e5a38ca5d75643a014c0fe05
import codecs import datetime import locale from decimal import Decimal from urllib.parse import quote from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __init__(self, obj, *args): self.obj = obj super().__init__(*args) def __str__(self): return "%s. You passed in %r (%s)" % ( super().__str__(), self.obj, type(self.obj), ) def smart_str(s, encoding="utf-8", strings_only=False, errors="strict"): """ Return a string representing 's'. Treat bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_str(s, encoding, strings_only, errors) _PROTECTED_TYPES = ( type(None), int, float, Decimal, datetime.datetime, datetime.date, datetime.time, ) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_str(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def force_str(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if issubclass(type(s), str): return s if strings_only and is_protected_type(s): return s try: if isinstance(s, bytes): s = str(s, encoding, errors) else: s = str(s) except UnicodeDecodeError as e: raise DjangoUnicodeDecodeError(s, *e.args) return s def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Return a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors) def force_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == "utf-8": return s else: return s.decode("utf-8", errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, memoryview): return bytes(s) return str(s).encode(encoding, errors) def iri_to_uri(iri): """ Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987, slightly simplified since the input is assumed to be a string rather than an arbitrary byte stream. Take an IRI (string or UTF-8 bytes, e.g. '/I ♥ Django/' or b'/I \xe2\x99\xa5 Django/') and return a string containing the encoded result with ASCII chars only (e.g. '/I%20%E2%99%A5%20Django/'). """ # The list of safe characters here is constructed from the "reserved" and # "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986: # reserved = gen-delims / sub-delims # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # Of the unreserved characters, urllib.parse.quote() already considers all # but the ~ safe. # The % character is also added to the list of safe characters here, as the # end of section 3.1 of RFC 3987 specifically mentions that % must not be # converted. if iri is None: return iri elif isinstance(iri, Promise): iri = str(iri) return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") # List of byte values that uri_to_iri() decodes from percent encoding. # First, the unreserved characters from RFC 3986: _ascii_ranges = [[45, 46, 95, 126], range(65, 91), range(97, 123)] _hextobyte = { (fmt % char).encode(): bytes((char,)) for ascii_range in _ascii_ranges for char in ascii_range for fmt in ["%02x", "%02X"] } # And then everything above 128, because bytes ≥ 128 are part of multibyte # Unicode characters. _hexdig = "0123456789ABCDEFabcdef" _hextobyte.update( {(a + b).encode(): bytes.fromhex(a + b) for a in _hexdig[8:] for b in _hexdig} ) def uri_to_iri(uri): """ Convert a Uniform Resource Identifier(URI) into an Internationalized Resource Identifier(IRI). This is the algorithm from section 3.2 of RFC 3987, excluding step 4. Take an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and return a string containing the encoded result (e.g. '/I%20♥%20Django/'). """ if uri is None: return uri uri = force_bytes(uri) # Fast selective unquote: First, split on '%' and then starting with the # second block, decode the first 2 bytes if they represent a hex code to # decode. The rest of the block is the part after '%AB', not containing # any '%'. Add that to the output without further processing. bits = uri.split(b"%") if len(bits) == 1: iri = uri else: parts = [bits[0]] append = parts.append hextobyte = _hextobyte for item in bits[1:]: hex = item[:2] if hex in hextobyte: append(hextobyte[item[:2]]) append(item[2:]) else: append(b"%") append(item) iri = b"".join(parts) return repercent_broken_unicode(iri).decode() def escape_uri_path(path): """ Escape the unsafe characters from the path portion of a Uniform Resource Identifier (URI). """ # These are the "reserved" and "unreserved" characters specified in # sections 2.2 and 2.3 of RFC 2396: # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," # unreserved = alphanum | mark # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" # The list of safe characters here is constructed subtracting ";", "=", # and "?" according to section 3.3 of RFC 2396. # The reason for not subtracting and escaping "/" is that we are escaping # the entire path, not a path segment. return quote(path, safe="/:@&+$,-_.!~*'()") def punycode(domain): """Return the Punycode of the given domain if it's non-ASCII.""" return domain.encode("idna").decode("ascii") def repercent_broken_unicode(path): """ As per section 3.2 of RFC 3987, step three of converting a URI into an IRI, repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exception # handling uses massive amounts of memory repercent = quote(path[e.start : e.end], safe=b"/#%[]=:;$&()+,!?*@'~") path = path[: e.start] + repercent.encode() + path[e.end :] else: return path def filepath_to_uri(path): """Convert a file system path to a URI portion that is suitable for inclusion in a URL. Encode certain chars that would normally be recognized as special chars for URIs. Do not encode the ' character, as it is a valid character within URIs. See the encodeURIComponent() JavaScript function for details. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return quote(str(path).replace("\\", "/"), safe="/~!*()'") def get_system_encoding(): """ The encoding of the default system locale. Fallback to 'ascii' if the #encoding is unsupported by Python or could not be determined. See tickets #10335 and #5846. """ try: encoding = locale.getdefaultlocale()[1] or "ascii" codecs.lookup(encoding) except Exception: encoding = "ascii" return encoding DEFAULT_LOCALE_ENCODING = get_system_encoding()
885e31e5469ddec49591f2922bebf38c3185a23ae1dc4eb2a0f2b4dad9e395ea
""" Django's standard crypto functions and utilities. """ import hashlib import hmac import secrets from django.conf import settings from django.utils.encoding import force_bytes from django.utils.inspect import func_supports_parameter class InvalidAlgorithm(ValueError): """Algorithm is not supported by hashlib.""" pass def salted_hmac(key_salt, value, secret=None, *, algorithm="sha1"): """ Return the HMAC of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1, but any algorithm name supported by hashlib can be passed. A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings.SECRET_KEY key_salt = force_bytes(key_salt) secret = force_bytes(secret) try: hasher = getattr(hashlib, algorithm) except AttributeError as e: raise InvalidAlgorithm( "%r is not an algorithm accepted by the hashlib module." % algorithm ) from e # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function. key = hasher(key_salt + secret).digest() # If len(key_salt + secret) > block size of the hash algorithm, the above # line is redundant and could be replaced by key = key_salt + secret, since # the hmac module does the same thing for keys longer than the block size. # However, we need to ensure that we *always* do this. return hmac.new(key, msg=force_bytes(value), digestmod=hasher) RANDOM_STRING_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS): """ Return a securely generated random string. The bit length of the returned value can be calculated with the formula: log_2(len(allowed_chars)^length) For example, with default `allowed_chars` (26+26+10), this gives: * length: 12, bit length =~ 71 bits * length: 22, bit length =~ 131 bits """ return "".join(secrets.choice(allowed_chars) for i in range(length)) def constant_time_compare(val1, val2): """Return True if the two strings are equal, False otherwise.""" return secrets.compare_digest(force_bytes(val1), force_bytes(val2)) def pbkdf2(password, salt, iterations, dklen=0, digest=None): """Return the hash of password using pbkdf2.""" if digest is None: digest = hashlib.sha256 dklen = dklen or None password = force_bytes(password) salt = force_bytes(salt) return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen) # TODO: Remove when dropping support for PY38. inspect.signature() is used to # detect whether the usedforsecurity argument is available as this fix may also # have been applied by downstream package maintainers to other versions in # their repositories. if func_supports_parameter(hashlib.md5, "usedforsecurity"): md5 = hashlib.md5 new_hash = hashlib.new else: def md5(data=b"", *, usedforsecurity=True): return hashlib.md5(data) def new_hash(hash_algorithm, *, usedforsecurity=True): return hashlib.new(hash_algorithm)
82fd187e4a1f722088e22a6dbffe86130c8bc95660d7f1c568d4709f70ee1f87
""" Functions for reversing a regular expression (used in reverse URL resolving). Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ import re from django.utils.functional import SimpleLazyObject # Mapping of an escape character to a representative of that class. So, e.g., # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore # this sequence. Any missing key is mapped to itself. ESCAPE_MAPPINGS = { "A": None, "b": None, "B": None, "d": "0", "D": "x", "s": " ", "S": "x", "w": "x", "W": "!", "Z": None, } class Choice(list): """Represent multiple possibilities at this point in a pattern string.""" class Group(list): """Represent a capturing group in the pattern string.""" class NonCapture(list): """Represent a non-capturing group in the pattern string.""" def normalize(pattern): r""" Given a reg-exp pattern, normalize it to an iterable of forms that suffice for reverse matching. This does the following: (1) For any repeating sections, keeps the minimum number of occurrences permitted (this means zero for optional groups). (2) If an optional group includes parameters, include one occurrence of that group (along with the zero occurrence case from step (1)). (3) Select the first (essentially an arbitrary) element from any character class. Select an arbitrary character for any unordered class (e.g. '.' or '\w') in the pattern. (4) Ignore look-ahead and look-behind assertions. (5) Raise an error on any disjunctive ('|') constructs. Django's URLs for forward resolving are either all positional arguments or all keyword arguments. That is assumed here, as well. Although reverse resolving can be done using positional args when keyword args are specified, the two cannot be mixed in the same reverse() call. """ # Do a linear scan to work out the special features of this pattern. The # idea is that we scan once here and collect all the information we need to # make future decisions. result = [] non_capturing_groups = [] consume_next = True pattern_iter = next_char(iter(pattern)) num_args = 0 # A "while" loop is used here because later on we need to be able to peek # at the next character and possibly go around without consuming another # one at the top of the loop. try: ch, escaped = next(pattern_iter) except StopIteration: return [("", [])] try: while True: if escaped: result.append(ch) elif ch == ".": # Replace "any character" with an arbitrary representative. result.append(".") elif ch == "|": # FIXME: One day we'll should do this, but not in 1.0. raise NotImplementedError("Awaiting Implementation") elif ch == "^": pass elif ch == "$": break elif ch == ")": # This can only be the end of a non-capturing group, since all # other unescaped parentheses are handled by the grouping # section later (and the full group is handled there). # # We regroup everything inside the capturing group so that it # can be quantified, if necessary. start = non_capturing_groups.pop() inner = NonCapture(result[start:]) result = result[:start] + [inner] elif ch == "[": # Replace ranges with the first character in the range. ch, escaped = next(pattern_iter) result.append(ch) ch, escaped = next(pattern_iter) while escaped or ch != "]": ch, escaped = next(pattern_iter) elif ch == "(": # Some kind of group. ch, escaped = next(pattern_iter) if ch != "?" or escaped: # A positional group name = "_%d" % num_args num_args += 1 result.append(Group((("%%(%s)s" % name), name))) walk_to_end(ch, pattern_iter) else: ch, escaped = next(pattern_iter) if ch in "!=<": # All of these are ignorable. Walk to the end of the # group. walk_to_end(ch, pattern_iter) elif ch == ":": # Non-capturing group non_capturing_groups.append(len(result)) elif ch != "P": # Anything else, other than a named group, is something # we cannot reverse. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch) else: ch, escaped = next(pattern_iter) if ch not in ("<", "="): raise ValueError( "Non-reversible reg-exp portion: '(?P%s'" % ch ) # We are in a named capturing group. Extra the name and # then skip to the end. if ch == "<": terminal_char = ">" # We are in a named backreference. else: terminal_char = ")" name = [] ch, escaped = next(pattern_iter) while ch != terminal_char: name.append(ch) ch, escaped = next(pattern_iter) param = "".join(name) # Named backreferences have already consumed the # parenthesis. if terminal_char != ")": result.append(Group((("%%(%s)s" % param), param))) walk_to_end(ch, pattern_iter) else: result.append(Group((("%%(%s)s" % param), None))) elif ch in "*?+{": # Quantifiers affect the previous item in the result list. count, ch = get_quantifier(ch, pattern_iter) if ch: # We had to look ahead, but it wasn't need to compute the # quantifier, so use this character next time around the # main loop. consume_next = False if count == 0: if contains(result[-1], Group): # If we are quantifying a capturing group (or # something containing such a group) and the minimum is # zero, we must also handle the case of one occurrence # being present. All the quantifiers (except {0,0}, # which we conveniently ignore) that have a 0 minimum # also allow a single occurrence. result[-1] = Choice([None, result[-1]]) else: result.pop() elif count > 1: result.extend([result[-1]] * (count - 1)) else: # Anything else is a literal. result.append(ch) if consume_next: ch, escaped = next(pattern_iter) consume_next = True except StopIteration: pass except NotImplementedError: # A case of using the disjunctive form. No results for you! return [("", [])] return list(zip(*flatten_result(result))) def next_char(input_iter): r""" An iterator that yields the next character from "pattern_iter", respecting escape sequences. An escaped character is replaced by a representative of its class (e.g. \w -> "x"). If the escaped character is one that is skipped, it is not returned (the next character is returned instead). Yield the next character, along with a boolean indicating whether it is a raw (unescaped) character or not. """ for ch in input_iter: if ch != "\\": yield ch, False continue ch = next(input_iter) representative = ESCAPE_MAPPINGS.get(ch, ch) if representative is None: continue yield representative, True def walk_to_end(ch, input_iter): """ The iterator is currently inside a capturing group. Walk to the close of this group, skipping over any nested groups and handling escaped parentheses correctly. """ if ch == "(": nesting = 1 else: nesting = 0 for ch, escaped in input_iter: if escaped: continue elif ch == "(": nesting += 1 elif ch == ")": if not nesting: return nesting -= 1 def get_quantifier(ch, input_iter): """ Parse a quantifier from the input, where "ch" is the first character in the quantifier. Return the minimum number of occurrences permitted by the quantifier and either None or the next character from the input_iter if the next character is not part of the quantifier. """ if ch in "*?+": try: ch2, escaped = next(input_iter) except StopIteration: ch2 = None if ch2 == "?": ch2 = None if ch == "+": return 1, ch2 return 0, ch2 quant = [] while ch != "}": ch, escaped = next(input_iter) quant.append(ch) quant = quant[:-1] values = "".join(quant).split(",") # Consume the trailing '?', if necessary. try: ch, escaped = next(input_iter) except StopIteration: ch = None if ch == "?": ch = None return int(values[0]), ch def contains(source, inst): """ Return True if the "source" contains an instance of "inst". False, otherwise. """ if isinstance(source, inst): return True if isinstance(source, NonCapture): for elt in source: if contains(elt, inst): return True return False def flatten_result(source): """ Turn the given source sequence into a list of reg-exp possibilities and their arguments. Return a list of strings and a list of argument lists. Each of the two lists will be of the same length. """ if source is None: return [""], [[]] if isinstance(source, Group): if source[1] is None: params = [] else: params = [source[1]] return [source[0]], [params] result = [""] result_args = [[]] pos = last = 0 for pos, elt in enumerate(source): if isinstance(elt, str): continue piece = "".join(source[last:pos]) if isinstance(elt, Group): piece += elt[0] param = elt[1] else: param = None last = pos + 1 for i in range(len(result)): result[i] += piece if param: result_args[i].append(param) if isinstance(elt, (Choice, NonCapture)): if isinstance(elt, NonCapture): elt = [elt] inner_result, inner_args = [], [] for item in elt: res, args = flatten_result(item) inner_result.extend(res) inner_args.extend(args) new_result = [] new_args = [] for item, args in zip(result, result_args): for i_item, i_args in zip(inner_result, inner_args): new_result.append(item + i_item) new_args.append(args[:] + i_args) result = new_result result_args = new_args if pos >= last: piece = "".join(source[last:]) for i in range(len(result)): result[i] += piece return result, result_args def _lazy_re_compile(regex, flags=0): """Lazily compile a regex with flags.""" def _compile(): # Compile the regex if it was not passed pre-compiled. if isinstance(regex, (str, bytes)): return re.compile(regex, flags) else: assert not flags, "flags must be empty if regex is passed pre-compiled" return regex return SimpleLazyObject(_compile)
8874ca48a8cf6a72b7616b52579b1f66cddc4eb0dc6e7b966318a720cfba29a4
import calendar import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware, utc from django.utils.translation import gettext, ngettext_lazy TIME_STRINGS = { "year": ngettext_lazy("%(num)d year", "%(num)d years", "num"), "month": ngettext_lazy("%(num)d month", "%(num)d months", "num"), "week": ngettext_lazy("%(num)d week", "%(num)d weeks", "num"), "day": ngettext_lazy("%(num)d day", "%(num)d days", "num"), "hour": ngettext_lazy("%(num)d hour", "%(num)d hours", "num"), "minute": ngettext_lazy("%(num)d minute", "%(num)d minutes", "num"), } TIMESINCE_CHUNKS = ( (60 * 60 * 24 * 365, "year"), (60 * 60 * 24 * 30, "month"), (60 * 60 * 24 * 7, "week"), (60 * 60 * 24, "day"), (60 * 60, "hour"), (60, "minute"), ) def timesince(d, now=None, reversed=False, time_strings=None, depth=2): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to `depth` adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. `time_strings` is an optional dict of strings to replace the default TIME_STRINGS dict. `depth` is an optional integer to control the number of adjacent time units returned. Adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ if time_strings is None: time_strings = TIME_STRINGS if depth <= 0: raise ValueError("depth must be greater than 0.") # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) now = now or datetime.datetime.now(utc if is_aware(d) else None) if reversed: d, now = now, d delta = now - d # Deal with leapyears by subtracing the number of leapdays leapdays = calendar.leapdays(d.year, now.year) if leapdays != 0: if calendar.isleap(d.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= datetime.timedelta(leapdays) # ignore microseconds since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(time_strings["minute"] % {"num": 0}) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break else: return avoid_wrapping(time_strings["minute"] % {"num": 0}) result = [] current_depth = 0 while i < len(TIMESINCE_CHUNKS) and current_depth < depth: seconds, name = TIMESINCE_CHUNKS[i] count = since // seconds if count == 0: break result.append(avoid_wrapping(time_strings[name] % {"num": count})) since -= seconds * count current_depth += 1 i += 1 return gettext(", ").join(result) def timeuntil(d, now=None, time_strings=None, depth=2): """ Like timesince, but return a string measuring the time until the given time. """ return timesince(d, now, reversed=True, time_strings=time_strings, depth=depth)
9610c43ad9922c4b9be498fffcc2205b703258e11591a03a76824a2b006167a0
import functools import inspect @functools.lru_cache(maxsize=512) def _get_func_parameters(func, remove_first): parameters = tuple(inspect.signature(func).parameters.values()) if remove_first: parameters = parameters[1:] return parameters def _get_callable_parameters(meth_or_func): is_method = inspect.ismethod(meth_or_func) func = meth_or_func.__func__ if is_method else meth_or_func return _get_func_parameters(func, remove_first=is_method) def get_func_args(func): params = _get_callable_parameters(func) return [ param.name for param in params if param.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD ] def get_func_full_args(func): """ Return a list of (argument name, default value) tuples. If the argument does not have a default value, omit it in the tuple. Arguments such as *args and **kwargs are also included. """ params = _get_callable_parameters(func) args = [] for param in params: name = param.name # Ignore 'self' if name == "self": continue if param.kind == inspect.Parameter.VAR_POSITIONAL: name = "*" + name elif param.kind == inspect.Parameter.VAR_KEYWORD: name = "**" + name if param.default != inspect.Parameter.empty: args.append((name, param.default)) else: args.append((name,)) return args def func_accepts_kwargs(func): """Return True if function 'func' accepts keyword arguments **kwargs.""" return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_KEYWORD) def func_accepts_var_args(func): """ Return True if function 'func' accepts positional arguments *args. """ return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_POSITIONAL) def method_has_no_args(meth): """Return True if a method only accepts 'self'.""" count = len( [p for p in _get_callable_parameters(meth) if p.kind == p.POSITIONAL_OR_KEYWORD] ) return count == 0 if inspect.ismethod(meth) else count == 1 def func_supports_parameter(func, name): return any(param.name == name for param in _get_callable_parameters(func))
5d88af96df42be45fc9904e9ebc0007d46684bc83218458d8f67f1fc2f40c989
from asgiref.local import Local from django.conf import settings as django_settings from django.utils.functional import cached_property class ConnectionProxy: """Proxy for accessing a connection object's attributes.""" def __init__(self, connections, alias): self.__dict__["_connections"] = connections self.__dict__["_alias"] = alias def __getattr__(self, item): return getattr(self._connections[self._alias], item) def __setattr__(self, name, value): return setattr(self._connections[self._alias], name, value) def __delattr__(self, name): return delattr(self._connections[self._alias], name) def __contains__(self, key): return key in self._connections[self._alias] def __eq__(self, other): return self._connections[self._alias] == other class ConnectionDoesNotExist(Exception): pass class BaseConnectionHandler: settings_name = None exception_class = ConnectionDoesNotExist thread_critical = False def __init__(self, settings=None): self._settings = settings self._connections = Local(self.thread_critical) @cached_property def settings(self): self._settings = self.configure_settings(self._settings) return self._settings def configure_settings(self, settings): if settings is None: settings = getattr(django_settings, self.settings_name) return settings def create_connection(self, alias): raise NotImplementedError("Subclasses must implement create_connection().") def __getitem__(self, alias): try: return getattr(self._connections, alias) except AttributeError: if alias not in self.settings: raise self.exception_class(f"The connection '{alias}' doesn't exist.") conn = self.create_connection(alias) setattr(self._connections, alias, conn) return conn def __setitem__(self, key, value): setattr(self._connections, key, value) def __delitem__(self, key): delattr(self._connections, key) def __iter__(self): return iter(self.settings) def all(self): return [self[alias] for alias in self]
b9df2a9905e9a3505fbf91b8157f09446a8f6f580b8a7258b96beb03581d2611
import copy from collections.abc import Mapping class OrderedSet: """ A set which keeps the ordering of the inserted items. """ def __init__(self, iterable=None): self.dict = dict.fromkeys(iterable or ()) def add(self, item): self.dict[item] = None def remove(self, item): del self.dict[item] def discard(self, item): try: self.remove(item) except KeyError: pass def __iter__(self): return iter(self.dict) def __reversed__(self): return reversed(self.dict) def __contains__(self, item): return item in self.dict def __bool__(self): return bool(self.dict) def __len__(self): return len(self.dict) def __repr__(self): data = repr(list(self.dict)) if self.dict else "" return f"{self.__class__.__qualname__}({data})" class MultiValueDictKeyError(KeyError): pass class MultiValueDict(dict): """ A subclass of dictionary customized to handle multiple values for the same key. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) >>> d['name'] 'Simon' >>> d.getlist('name') ['Adrian', 'Simon'] >>> d.getlist('doesnotexist') [] >>> d.getlist('doesnotexist', ['Adrian', 'Simon']) ['Adrian', 'Simon'] >>> d.get('lastname', 'nonexistent') 'nonexistent' >>> d.setlist('lastname', ['Holovaty', 'Willison']) This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most web forms submit single name-value pairs. """ def __init__(self, key_to_list_mapping=()): super().__init__(key_to_list_mapping) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, super().__repr__()) def __getitem__(self, key): """ Return the last data value for this key, or [] if it's an empty list; raise KeyError if not found. """ try: list_ = super().__getitem__(key) except KeyError: raise MultiValueDictKeyError(key) try: return list_[-1] except IndexError: return [] def __setitem__(self, key, value): super().__setitem__(key, [value]) def __copy__(self): return self.__class__([(k, v[:]) for k, v in self.lists()]) def __deepcopy__(self, memo): result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__( result, copy.deepcopy(key, memo), copy.deepcopy(value, memo) ) return result def __getstate__(self): return {**self.__dict__, "_data": {k: self._getlist(k) for k in self}} def __setstate__(self, obj_dict): data = obj_dict.pop("_data", {}) for k, v in data.items(): self.setlist(k, v) self.__dict__.update(obj_dict) def get(self, key, default=None): """ Return the last data value for the passed key. If key doesn't exist or value is an empty list, return `default`. """ try: val = self[key] except KeyError: return default if val == []: return default return val def _getlist(self, key, default=None, force_list=False): """ Return a list of values for the key. Used internally to manipulate values list. If force_list is True, return a new copy of values. """ try: values = super().__getitem__(key) except KeyError: if default is None: return [] return default else: if force_list: values = list(values) if values is not None else None return values def getlist(self, key, default=None): """ Return the list of values for the key. If key doesn't exist, return a default value. """ return self._getlist(key, default, force_list=True) def setlist(self, key, list_): super().__setitem__(key, list_) def setdefault(self, key, default=None): if key not in self: self[key] = default # Do not return default here because __setitem__() may store # another value -- QueryDict.__setitem__() does. Look it up. return self[key] def setlistdefault(self, key, default_list=None): if key not in self: if default_list is None: default_list = [] self.setlist(key, default_list) # Do not return default_list here because setlist() may store # another value -- QueryDict.setlist() does. Look it up. return self._getlist(key) def appendlist(self, key, value): """Append an item to the internal list associated with key.""" self.setlistdefault(key).append(value) def items(self): """ Yield (key, value) pairs, where value is the last item in the list associated with the key. """ for key in self: yield key, self[key] def lists(self): """Yield (key, list) pairs.""" return iter(super().items()) def values(self): """Yield the last value on every key list.""" for key in self: yield self[key] def copy(self): """Return a shallow copy of this object.""" return copy.copy(self) def update(self, *args, **kwargs): """Extend rather than replace existing key lists.""" if len(args) > 1: raise TypeError("update expected at most 1 argument, got %d" % len(args)) if args: arg = args[0] if isinstance(arg, MultiValueDict): for key, value_list in arg.lists(): self.setlistdefault(key).extend(value_list) else: if isinstance(arg, Mapping): arg = arg.items() for key, value in arg: self.setlistdefault(key).append(value) for key, value in kwargs.items(): self.setlistdefault(key).append(value) def dict(self): """Return current object as a dict with singular values.""" return {key: self[key] for key in self} class ImmutableList(tuple): """ A tuple-like object that raises useful errors when it is asked to mutate. Example:: >>> a = ImmutableList(range(5), warning="You cannot mutate this.") >>> a[3] = '4' Traceback (most recent call last): ... AttributeError: You cannot mutate this. """ def __new__(cls, *args, warning="ImmutableList object is immutable.", **kwargs): self = tuple.__new__(cls, *args, **kwargs) self.warning = warning return self def complain(self, *args, **kwargs): raise AttributeError(self.warning) # All list mutation functions complain. __delitem__ = complain __delslice__ = complain __iadd__ = complain __imul__ = complain __setitem__ = complain __setslice__ = complain append = complain extend = complain insert = complain pop = complain remove = complain sort = complain reverse = complain class DictWrapper(dict): """ Wrap accesses to a dictionary so that certain values (those starting with the specified prefix) are passed through a function before being returned. The prefix is removed before looking up the real value. Used by the SQL construction code to ensure that values are correctly quoted before being used. """ def __init__(self, data, func, prefix): super().__init__(data) self.func = func self.prefix = prefix def __getitem__(self, key): """ Retrieve the real value after stripping the prefix string (if present). If the prefix is present, pass the value through self.func before returning, otherwise return the raw value. """ use_func = key.startswith(self.prefix) if use_func: key = key[len(self.prefix) :] value = super().__getitem__(key) if use_func: return self.func(value) return value class CaseInsensitiveMapping(Mapping): """ Mapping allowing case-insensitive key lookups. Original case of keys is preserved for iteration and string representation. Example:: >>> ci_map = CaseInsensitiveMapping({'name': 'Jane'}) >>> ci_map['Name'] Jane >>> ci_map['NAME'] Jane >>> ci_map['name'] Jane >>> ci_map # original case preserved {'name': 'Jane'} """ def __init__(self, data): self._store = {k.lower(): (k, v) for k, v in self._unpack_items(data)} def __getitem__(self, key): return self._store[key.lower()][1] def __len__(self): return len(self._store) def __eq__(self, other): return isinstance(other, Mapping) and { k.lower(): v for k, v in self.items() } == {k.lower(): v for k, v in other.items()} def __iter__(self): return (original_key for original_key, value in self._store.values()) def __repr__(self): return repr({key: value for key, value in self._store.values()}) def copy(self): return self @staticmethod def _unpack_items(data): # Explicitly test for dict first as the common case for performance, # avoiding abc's __instancecheck__ and _abc_instancecheck for the # general Mapping case. if isinstance(data, (dict, Mapping)): yield from data.items() return for i, elem in enumerate(data): if len(elem) != 2: raise ValueError( "dictionary update sequence element #{} has length {}; " "2 is required.".format(i, len(elem)) ) if not isinstance(elem[0], str): raise ValueError( "Element key %r invalid, only strings are allowed" % elem[0] ) yield elem
ce86f1024480e93e0920991ff74047288144f21c19983a95e8fb42faf6286f8a
""" PHP date() style date formatting See https://www.php.net/date for format strings Usage: >>> import datetime >>> d = datetime.datetime.now() >>> df = DateFormat(d) >>> print(df.format('jS F Y H:i')) 7th October 2003 11:39 >>> """ import calendar import datetime from email.utils import format_datetime as format_datetime_rfc5322 from django.utils.dates import ( MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR, ) from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import ( _datetime_ambiguous_or_imaginary, get_default_timezone, is_naive, make_aware, ) from django.utils.translation import gettext as _ re_formatchars = _lazy_re_compile(r"(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])") re_escaped = _lazy_re_compile(r"\\(.)") class Formatter: def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(str(formatstr))): if i % 2: if type(self.data) is datetime.date and hasattr(TimeFormat, piece): raise TypeError( "The format for date objects may not contain " "time-related format specifiers (found '%s')." % piece ) pieces.append(str(getattr(self, piece)())) elif piece: pieces.append(re_escaped.sub(r"\1", piece)) return "".join(pieces) class TimeFormat(Formatter): def __init__(self, obj): self.data = obj self.timezone = None # We only support timezone when formatting datetime objects, # not date objects (timezone information not appropriate), # or time objects (against established django policy). if isinstance(obj, datetime.datetime): if is_naive(obj): self.timezone = get_default_timezone() else: self.timezone = obj.tzinfo @property def _no_timezone_or_datetime_is_ambiguous_or_imaginary(self): return not self.timezone or _datetime_ambiguous_or_imaginary( self.data, self.timezone ) def a(self): "'a.m.' or 'p.m.'" if self.data.hour > 11: return _("p.m.") return _("a.m.") def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _("PM") return _("AM") def e(self): """ Timezone name. If timezone information is not available, return an empty string. """ if not self.timezone: return "" try: if hasattr(self.data, "tzinfo") and self.data.tzinfo: return self.data.tzname() or "" except NotImplementedError: pass return "" def f(self): """ Time, in 12-hour hours and minutes, with minutes left off if they're zero. Examples: '1', '1:30', '2:05', '2' Proprietary extension. """ hour = self.data.hour % 12 or 12 minute = self.data.minute return "%d:%02d" % (hour, minute) if minute else hour def g(self): "Hour, 12-hour format without leading zeros; i.e. '1' to '12'" return self.data.hour % 12 or 12 def G(self): "Hour, 24-hour format without leading zeros; i.e. '0' to '23'" return self.data.hour def h(self): "Hour, 12-hour format; i.e. '01' to '12'" return "%02d" % (self.data.hour % 12 or 12) def H(self): "Hour, 24-hour format; i.e. '00' to '23'" return "%02d" % self.data.hour def i(self): "Minutes; i.e. '00' to '59'" return "%02d" % self.data.minute def O(self): # NOQA: E743, E741 """ Difference to Greenwich time in hours; e.g. '+0200', '-0430'. If timezone information is not available, return an empty string. """ if self._no_timezone_or_datetime_is_ambiguous_or_imaginary: return "" seconds = self.Z() sign = "-" if seconds < 0 else "+" seconds = abs(seconds) return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _("midnight") if self.data.minute == 0 and self.data.hour == 12: return _("noon") return "%s %s" % (self.f(), self.a()) def s(self): "Seconds; i.e. '00' to '59'" return "%02d" % self.data.second def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, return an empty string. """ if self._no_timezone_or_datetime_is_ambiguous_or_imaginary: return "" return str(self.timezone.tzname(self.data)) def u(self): "Microseconds; i.e. '000000' to '999999'" return "%06d" % self.data.microsecond def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, return an empty string. """ if self._no_timezone_or_datetime_is_ambiguous_or_imaginary: return "" offset = self.timezone.utcoffset(self.data) # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds class DateFormat(TimeFormat): def b(self): "Month, textual, 3 letters, lowercase; e.g. 'jan'" return MONTHS_3[self.data.month] def c(self): """ ISO 8601 Format Example : '2008-01-02T10:30:00.000123' """ return self.data.isoformat() def d(self): "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" return "%02d" % self.data.day def D(self): "Day of the week, textual, 3 letters; e.g. 'Fri'" return WEEKDAYS_ABBR[self.data.weekday()] def E(self): "Alternative month names as required by some locales. Proprietary extension." return MONTHS_ALT[self.data.month] def F(self): "Month, textual, long; e.g. 'January'" return MONTHS[self.data.month] def I(self): # NOQA: E743, E741 "'1' if daylight saving time, '0' otherwise." if self._no_timezone_or_datetime_is_ambiguous_or_imaginary: return "" return "1" if self.timezone.dst(self.data) else "0" def j(self): "Day of the month without leading zeros; i.e. '1' to '31'" return self.data.day def l(self): # NOQA: E743, E741 "Day of the week, textual, long; e.g. 'Friday'" return WEEKDAYS[self.data.weekday()] def L(self): "Boolean for whether it is a leap year; i.e. True or False" return calendar.isleap(self.data.year) def m(self): "Month; i.e. '01' to '12'" return "%02d" % self.data.month def M(self): "Month, textual, 3 letters; e.g. 'Jan'" return MONTHS_3[self.data.month].title() def n(self): "Month without leading zeros; i.e. '1' to '12'" return self.data.month def N(self): "Month abbreviation in Associated Press style. Proprietary extension." return MONTHS_AP[self.data.month] def o(self): "ISO 8601 year number matching the ISO week number (W)" return self.data.isocalendar()[0] def r(self): "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" if type(self.data) is datetime.date: raise TypeError( "The format for date objects may not contain time-related " "format specifiers (found 'r')." ) if is_naive(self.data): dt = make_aware(self.data, timezone=self.timezone) else: dt = self.data return format_datetime_rfc5322(dt) def S(self): """ English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'. """ if self.data.day in (11, 12, 13): # Special case return "th" last = self.data.day % 10 if last == 1: return "st" if last == 2: return "nd" if last == 3: return "rd" return "th" def t(self): "Number of days in the given month; i.e. '28' to '31'" return "%02d" % calendar.monthrange(self.data.year, self.data.month)[1] def U(self): "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)" value = self.data if not isinstance(value, datetime.datetime): value = datetime.datetime.combine(value, datetime.time.min) return int(value.timestamp()) def w(self): "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)" return (self.data.weekday() + 1) % 7 def W(self): "ISO-8601 week number of year, weeks starting on Monday" return self.data.isocalendar()[1] def y(self): """Year, 2 digits with leading zeros; e.g. '99'.""" return "%02d" % (self.data.year % 100) def Y(self): """Year, 4 digits with leading zeros; e.g. '1999'.""" return "%04d" % self.data.year def z(self): """Day of the year, i.e. 1 to 366.""" return self.data.timetuple().tm_yday def format(value, format_string): "Convenience function" df = DateFormat(value) return df.format(format_string) def time_format(value, format_string): "Convenience function" tf = TimeFormat(value) return tf.format(format_string)
f9aeea39be6ba69f8bc3fe75bf220f49d6fb478d01d7a12bd597350bf6ba89b6
import copy import os import sys from importlib import import_module from importlib.util import find_spec as importlib_find def cached_import(module_path, class_name): # Check whether module is loaded and fully initialized. if not ( (module := sys.modules.get(module_path)) and (spec := getattr(module, "__spec__", None)) and getattr(spec, "_initializing", False) is False ): module = import_module(module_path) return getattr(module, class_name) def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError as err: raise ImportError("%s doesn't look like a module path" % dotted_path) from err try: return cached_import(module_path, class_name) except AttributeError as err: raise ImportError( 'Module "%s" does not define a "%s" attribute/class' % (module_path, class_name) ) from err def autodiscover_modules(*args, **kwargs): """ Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to access it. """ from django.apps import apps register_to = kwargs.get("register_to") for app_config in apps.get_app_configs(): for module_to_search in args: # Attempt to import the app's module. try: if register_to: before_import_registry = copy.copy(register_to._registry) import_module("%s.%s" % (app_config.name, module_to_search)) except Exception: # Reset the registry to the state before the last import # as this import will have to reoccur on the next request and # this could raise NotRegistered and AlreadyRegistered # exceptions (see #8245). if register_to: register_to._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have the module in question, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, module_to_search): raise def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" try: package_name = package.__name__ package_path = package.__path__ except AttributeError: # package isn't a package. return False full_module_name = package_name + "." + module_name try: return importlib_find(full_module_name, package_path) is not None except ModuleNotFoundError: # When module_name is an invalid dotted path, Python raises # ModuleNotFoundError. return False def module_dir(module): """ Find the name of the directory that contains a module, if possible. Raise ValueError otherwise, e.g. for namespace packages that are split over several directories. """ # Convert to list because __path__ may not support indexing. paths = list(getattr(module, "__path__", [])) if len(paths) == 1: return paths[0] else: filename = getattr(module, "__file__", None) if filename is not None: return os.path.dirname(filename) raise ValueError("Cannot determine directory containing %s" % module)
9a7227dff3f68ea6fccad8853a26828eb4c516e8de3454f4124ca6a529adec29
# RemovedInDjango50Warning # Copyright (c) 2010 Guilherme Gondim. All rights reserved. # Copyright (c) 2009 Simon Willison. All rights reserved. # Copyright (c) 2002 Drew Perttula. All rights reserved. # # License: # Python Software Foundation License version 2 # # See the file "LICENSE" for terms & conditions for usage, and a DISCLAIMER OF # ALL WARRANTIES. # # This Baseconv distribution contains no GNU General Public Licensed (GPLed) # code so it may be used in proprietary projects just like prior ``baseconv`` # distributions. # # All trademarks referenced herein are property of their respective holders. # """ Convert numbers from base 10 integers to base X strings and back again. Sample usage:: >>> base20 = BaseConverter('0123456789abcdefghij') >>> base20.encode(1234) '31e' >>> base20.decode('31e') 1234 >>> base20.encode(-1234) '-31e' >>> base20.decode('-31e') -1234 >>> base11 = BaseConverter('0123456789-', sign='$') >>> base11.encode(-1234) '$-22' >>> base11.decode('$-22') -1234 """ import warnings from django.utils.deprecation import RemovedInDjango50Warning warnings.warn( "The django.utils.baseconv module is deprecated.", category=RemovedInDjango50Warning, stacklevel=2, ) BASE2_ALPHABET = "01" BASE16_ALPHABET = "0123456789ABCDEF" BASE56_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz" BASE36_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz" BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" BASE64_ALPHABET = BASE62_ALPHABET + "-_" class BaseConverter: decimal_digits = "0123456789" def __init__(self, digits, sign="-"): self.sign = sign self.digits = digits if sign in self.digits: raise ValueError("Sign character found in converter base digits.") def __repr__(self): return "<%s: base%s (%s)>" % ( self.__class__.__name__, len(self.digits), self.digits, ) def encode(self, i): neg, value = self.convert(i, self.decimal_digits, self.digits, "-") if neg: return self.sign + value return value def decode(self, s): neg, value = self.convert(s, self.digits, self.decimal_digits, self.sign) if neg: value = "-" + value return int(value) def convert(self, number, from_digits, to_digits, sign): if str(number)[0] == sign: number = str(number)[1:] neg = 1 else: neg = 0 # make an integer out of the number x = 0 for digit in str(number): x = x * len(from_digits) + from_digits.index(digit) # create the result in base 'len(to_digits)' if x == 0: res = to_digits[0] else: res = "" while x > 0: digit = x % len(to_digits) res = to_digits[digit] + res x = int(x // len(to_digits)) return neg, res base2 = BaseConverter(BASE2_ALPHABET) base16 = BaseConverter(BASE16_ALPHABET) base36 = BaseConverter(BASE36_ALPHABET) base56 = BaseConverter(BASE56_ALPHABET) base62 = BaseConverter(BASE62_ALPHABET) base64 = BaseConverter(BASE64_ALPHABET, sign="$")
f0916faeb972306514715a8dfbbfd347fc22dfcf2b6585ac068a9e659b6951b4
import datetime def _get_duration_components(duration): days = duration.days seconds = duration.seconds microseconds = duration.microseconds minutes = seconds // 60 seconds = seconds % 60 hours = minutes // 60 minutes = minutes % 60 return days, hours, minutes, seconds, microseconds def duration_string(duration): """Version of str(timedelta) which is not English specific.""" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) string = "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds) if days: string = "{} ".format(days) + string if microseconds: string += ".{:06d}".format(microseconds) return string def duration_iso_string(duration): if duration < datetime.timedelta(0): sign = "-" duration *= -1 else: sign = "" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) ms = ".{:06d}".format(microseconds) if microseconds else "" return "{}P{}DT{:02d}H{:02d}M{:02d}{}S".format( sign, days, hours, minutes, seconds, ms ) def duration_microseconds(delta): return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
cc750778e931ba8e77ad3bc71b775630b45f5727da30b048b79c6603813f21db
"Commonly-used date structures" from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy WEEKDAYS = { 0: _("Monday"), 1: _("Tuesday"), 2: _("Wednesday"), 3: _("Thursday"), 4: _("Friday"), 5: _("Saturday"), 6: _("Sunday"), } WEEKDAYS_ABBR = { 0: _("Mon"), 1: _("Tue"), 2: _("Wed"), 3: _("Thu"), 4: _("Fri"), 5: _("Sat"), 6: _("Sun"), } MONTHS = { 1: _("January"), 2: _("February"), 3: _("March"), 4: _("April"), 5: _("May"), 6: _("June"), 7: _("July"), 8: _("August"), 9: _("September"), 10: _("October"), 11: _("November"), 12: _("December"), } MONTHS_3 = { 1: _("jan"), 2: _("feb"), 3: _("mar"), 4: _("apr"), 5: _("may"), 6: _("jun"), 7: _("jul"), 8: _("aug"), 9: _("sep"), 10: _("oct"), 11: _("nov"), 12: _("dec"), } MONTHS_AP = { # month names in Associated Press style 1: pgettext_lazy("abbrev. month", "Jan."), 2: pgettext_lazy("abbrev. month", "Feb."), 3: pgettext_lazy("abbrev. month", "March"), 4: pgettext_lazy("abbrev. month", "April"), 5: pgettext_lazy("abbrev. month", "May"), 6: pgettext_lazy("abbrev. month", "June"), 7: pgettext_lazy("abbrev. month", "July"), 8: pgettext_lazy("abbrev. month", "Aug."), 9: pgettext_lazy("abbrev. month", "Sept."), 10: pgettext_lazy("abbrev. month", "Oct."), 11: pgettext_lazy("abbrev. month", "Nov."), 12: pgettext_lazy("abbrev. month", "Dec."), } MONTHS_ALT = { # required for long date representation by some locales 1: pgettext_lazy("alt. month", "January"), 2: pgettext_lazy("alt. month", "February"), 3: pgettext_lazy("alt. month", "March"), 4: pgettext_lazy("alt. month", "April"), 5: pgettext_lazy("alt. month", "May"), 6: pgettext_lazy("alt. month", "June"), 7: pgettext_lazy("alt. month", "July"), 8: pgettext_lazy("alt. month", "August"), 9: pgettext_lazy("alt. month", "September"), 10: pgettext_lazy("alt. month", "October"), 11: pgettext_lazy("alt. month", "November"), 12: pgettext_lazy("alt. month", "December"), }
9056c79d5380e20fab4c523fd681de346034644cc0958d2f39e19301eab1cfb1
from django.utils.itercompat import is_iterable def make_hashable(value): """ Attempt to make value hashable or raise a TypeError if it fails. The returned value should generate the same hash for equal values. """ if isinstance(value, dict): return tuple( [ (key, make_hashable(nested_value)) for key, nested_value in sorted(value.items()) ] ) # Try hash to avoid converting a hashable iterable (e.g. string, frozenset) # to a tuple. try: hash(value) except TypeError: if is_iterable(value): return tuple(map(make_hashable, value)) # Non-hashable, non-iterable. raise return value
45a99f4888199e649a8083181bea620bcf09db2bd3f1d77c82417a012b77f912
"""HTML utilities suitable for global use.""" import html import json import re from html.parser import HTMLParser from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit from django.utils.encoding import punycode from django.utils.functional import Promise, keep_lazy, keep_lazy_text from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import normalize_newlines @keep_lazy(SafeString) def escape(text): """ Return the given text with ampersands, quotes and angle brackets encoded for use in HTML. Always escape input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return SafeString(html.escape(str(text))) _js_escapes = { ord("\\"): "\\u005C", ord("'"): "\\u0027", ord('"'): "\\u0022", ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", ord("="): "\\u003D", ord("-"): "\\u002D", ord(";"): "\\u003B", ord("`"): "\\u0060", ord("\u2028"): "\\u2028", ord("\u2029"): "\\u2029", } # Escape every ASCII character with a value less than 32. _js_escapes.update((ord("%c" % z), "\\u%04X" % z) for z in range(32)) @keep_lazy(SafeString) def escapejs(value): """Hex encode characters for use in JavaScript strings.""" return mark_safe(str(value).translate(_js_escapes)) _json_script_escapes = { ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", } def json_script(value, element_id=None): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag. """ from django.core.serializers.json import DjangoJSONEncoder json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes) if element_id: template = '<script id="{}" type="application/json">{}</script>' args = (element_id, mark_safe(json_str)) else: template = '<script type="application/json">{}</script>' args = (mark_safe(json_str),) return format_html(template, *args) def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ if isinstance(text, Promise): text = str(text) if hasattr(text, "__html__"): return text.__html__() else: return escape(text) def format_html(format_string, *args, **kwargs): """ Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditional_escape, args) kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()} return mark_safe(format_string.format(*args_safe, **kwargs_safe)) def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users)) """ return mark_safe( conditional_escape(sep).join( format_html(format_string, *args) for args in args_generator ) ) @keep_lazy_text def linebreaks(value, autoescape=False): """Convert newlines into <p> and <br>s.""" value = normalize_newlines(value) paras = re.split("\n{2,}", str(value)) if autoescape: paras = ["<p>%s</p>" % escape(p).replace("\n", "<br>") for p in paras] else: paras = ["<p>%s</p>" % p.replace("\n", "<br>") for p in paras] return "\n\n".join(paras) class MLStripper(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append("&%s;" % name) def handle_charref(self, name): self.fed.append("&#%s;" % name) def get_data(self): return "".join(self.fed) def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() s.feed(value) s.close() return s.get_data() @keep_lazy_text def strip_tags(value): """Return the given HTML with all tags stripped.""" # Note: in typical case this loop executes _strip_once once. Loop condition # is redundant, but helps to reduce number of executions of _strip_once. value = str(value) while "<" in value and ">" in value: new_value = _strip_once(value) if value.count("<") == new_value.count("<"): # _strip_once wasn't able to detect more tags. break value = new_value return value @keep_lazy_text def strip_spaces_between_tags(value): """Return the given HTML with spaces between tags removed.""" return re.sub(r">\s+<", "><", str(value)) def smart_urlquote(url): """Quote a URL if it isn't already quoted.""" def unquote_quote(segment): segment = unquote(segment) # Tilde is part of RFC3986 Unreserved Characters # https://tools.ietf.org/html/rfc3986#section-2.3 # See also https://bugs.python.org/issue16285 return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + "~") # Handle IDN before quoting. try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: # invalid IPv6 URL (normally square brackets in hostname part). return unquote_quote(url) try: netloc = punycode(netloc) # IDN -> ACE except UnicodeError: # invalid domain part return unquote_quote(url) if query: # Separately unquoting key/value, so as to not mix querystring separators # included in query values. See #22267. query_parts = [ (unquote(q[0]), unquote(q[1])) for q in parse_qsl(query, keep_blank_values=True) ] # urlencode will take care of quoting query = urlencode(query_parts) path = unquote_quote(path) fragment = unquote_quote(fragment) return urlunsplit((scheme, netloc, path, query, fragment)) class Urlizer: """ Convert any URLs in text into clickable links. Work on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. """ trailing_punctuation_chars = ".,:;!" wrapping_punctuation = [("(", ")"), ("[", "]")] simple_url_re = _lazy_re_compile(r"^https?://\[?\w", re.IGNORECASE) simple_url_2_re = _lazy_re_compile( r"^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$", re.IGNORECASE ) word_split_re = _lazy_re_compile(r"""([\s<>"']+)""") mailto_template = "mailto:{local}@{domain}" url_template = '<a href="{href}"{attrs}>{url}</a>' def __call__(self, text, trim_url_limit=None, nofollow=False, autoescape=False): """ If trim_url_limit is not None, truncate the URLs in the link text longer than this limit to trim_url_limit - 1 characters and append an ellipsis. If nofollow is True, give the links a rel="nofollow" attribute. If autoescape is True, autoescape the link text and URLs. """ safe_input = isinstance(text, SafeData) words = self.word_split_re.split(str(text)) return "".join( [ self.handle_word( word, safe_input=safe_input, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape, ) for word in words ] ) def handle_word( self, word, *, safe_input, trim_url_limit=None, nofollow=False, autoescape=False, ): if "." in word or "@" in word or ":" in word: # lead: Punctuation trimmed from the beginning of the word. # middle: State of the word. # trail: Punctuation trimmed from the end of the word. lead, middle, trail = self.trim_punctuation(word) # Make URL we want to point to. url = None nofollow_attr = ' rel="nofollow"' if nofollow else "" if self.simple_url_re.match(middle): url = smart_urlquote(html.unescape(middle)) elif self.simple_url_2_re.match(middle): url = smart_urlquote("http://%s" % html.unescape(middle)) elif ":" not in middle and self.is_email_simple(middle): local, domain = middle.rsplit("@", 1) try: domain = punycode(domain) except UnicodeError: return word url = self.mailto_template.format(local=local, domain=domain) nofollow_attr = "" # Make link. if url: trimmed = self.trim_url(middle, limit=trim_url_limit) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) trimmed = escape(trimmed) middle = self.url_template.format( href=escape(url), attrs=nofollow_attr, url=trimmed, ) return mark_safe(f"{lead}{middle}{trail}") else: if safe_input: return mark_safe(word) elif autoescape: return escape(word) elif safe_input: return mark_safe(word) elif autoescape: return escape(word) return word def trim_url(self, x, *, limit): if limit is None or len(x) <= limit: return x return "%s…" % x[: max(0, limit - 1)] def trim_punctuation(self, word): """ Trim trailing and wrapping punctuation from `word`. Return the items of the new state. """ lead, middle, trail = "", word, "" # Continue trimming until middle remains unchanged. trimmed_something = True while trimmed_something: trimmed_something = False # Trim wrapping punctuation. for opening, closing in self.wrapping_punctuation: if middle.startswith(opening): middle = middle[len(opening) :] lead += opening trimmed_something = True # Keep parentheses at the end only if they're balanced. if ( middle.endswith(closing) and middle.count(closing) == middle.count(opening) + 1 ): middle = middle[: -len(closing)] trail = closing + trail trimmed_something = True # Trim trailing punctuation (after trimming wrapping punctuation, # as encoded entities contain ';'). Unescape entities to avoid # breaking them by removing ';'. middle_unescaped = html.unescape(middle) stripped = middle_unescaped.rstrip(self.trailing_punctuation_chars) if middle_unescaped != stripped: punctuation_count = len(middle_unescaped) - len(stripped) trail = middle[-punctuation_count:] + trail middle = middle[:-punctuation_count] trimmed_something = True return lead, middle, trail @staticmethod def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if "@" not in value or value.startswith("@") or value.endswith("@"): return False try: p1, p2 = value.split("@") except ValueError: # value contains more than one @. return False # Dot must be in p2 (e.g. example.com) if "." not in p2 or p2.startswith("."): return False return True urlizer = Urlizer() @keep_lazy_text def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): return urlizer( text, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape ) def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0") def html_safe(klass): """ A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString. """ if "__html__" in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it defines " "__html__()." % klass.__name__ ) if "__str__" not in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it doesn't " "define __str__()." % klass.__name__ ) klass_str = klass.__str__ klass.__str__ = lambda self: mark_safe(klass_str(self)) klass.__html__ = lambda self: str(self) return klass
aa4197073e3309591f394cbeddc88c34e01fe7767de0bc80798c65c83df2904f
import logging import logging.config # needed when logging_config doesn't start with logging.config from copy import copy from django.conf import settings from django.core import mail from django.core.mail import get_connection from django.core.management.color import color_style from django.utils.module_loading import import_string request_logger = logging.getLogger("django.request") # Default logging for Django. This sends an email to the site admins on every # HTTP 500 error. Depending on DEBUG, all other log records are either sent to # the console (DEBUG=True) or discarded (DEBUG=False) by means of the # require_debug_true filter. This configuration is quoted in # docs/ref/logging.txt; please amend it there if edited here. DEFAULT_LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, }, "formatters": { "django.server": { "()": "django.utils.log.ServerFormatter", "format": "[{server_time}] {message}", "style": "{", } }, "handlers": { "console": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler", }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, }, "loggers": { "django": { "handlers": ["console", "mail_admins"], "level": "INFO", }, "django.server": { "handlers": ["django.server"], "level": "INFO", "propagate": False, }, }, } def configure_logging(logging_config, logging_settings): if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) logging.config.dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings) class AdminEmailHandler(logging.Handler): """An exception log handler that emails log entries to site admins. If the request is passed as the first argument to the log record, request data will be provided in the email report. """ def __init__(self, include_html=False, email_backend=None, reporter_class=None): super().__init__() self.include_html = include_html self.email_backend = email_backend self.reporter_class = import_string( reporter_class or settings.DEFAULT_EXCEPTION_REPORTER ) def emit(self, record): try: request = record.request subject = "%s (%s IP): %s" % ( record.levelname, ( "internal" if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS else "EXTERNAL" ), record.getMessage(), ) except Exception: subject = "%s: %s" % (record.levelname, record.getMessage()) request = None subject = self.format_subject(subject) # Since we add a nicely formatted traceback on our own, create a copy # of the log record without the exception data. no_exc_record = copy(record) no_exc_record.exc_info = None no_exc_record.exc_text = None if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) reporter = self.reporter_class(request, is_email=True, *exc_info) message = "%s\n\n%s" % ( self.format(no_exc_record), reporter.get_traceback_text(), ) html_message = reporter.get_traceback_html() if self.include_html else None self.send_mail(subject, message, fail_silently=True, html_message=html_message) def send_mail(self, subject, message, *args, **kwargs): mail.mail_admins( subject, message, *args, connection=self.connection(), **kwargs ) def connection(self): return get_connection(backend=self.email_backend, fail_silently=True) def format_subject(self, subject): """ Escape CR and LF characters. """ return subject.replace("\n", "\\n").replace("\r", "\\r") class CallbackFilter(logging.Filter): """ A logging filter that checks the return value of a given callable (which takes the record-to-be-logged as its only parameter) to decide whether to log a record. """ def __init__(self, callback): self.callback = callback def filter(self, record): if self.callback(record): return 1 return 0 class RequireDebugFalse(logging.Filter): def filter(self, record): return not settings.DEBUG class RequireDebugTrue(logging.Filter): def filter(self, record): return settings.DEBUG class ServerFormatter(logging.Formatter): default_time_format = "%d/%b/%Y %H:%M:%S" def __init__(self, *args, **kwargs): self.style = color_style() super().__init__(*args, **kwargs) def format(self, record): msg = record.msg status_code = getattr(record, "status_code", None) if status_code: if 200 <= status_code < 300: # Put 2XX first, since it should be the common case msg = self.style.HTTP_SUCCESS(msg) elif 100 <= status_code < 200: msg = self.style.HTTP_INFO(msg) elif status_code == 304: msg = self.style.HTTP_NOT_MODIFIED(msg) elif 300 <= status_code < 400: msg = self.style.HTTP_REDIRECT(msg) elif status_code == 404: msg = self.style.HTTP_NOT_FOUND(msg) elif 400 <= status_code < 500: msg = self.style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other status code msg = self.style.HTTP_SERVER_ERROR(msg) if self.uses_server_time() and not hasattr(record, "server_time"): record.server_time = self.formatTime(record, self.datefmt) record.msg = msg return super().format(record) def uses_server_time(self): return self._fmt.find("{server_time}") >= 0 def log_response( message, *args, response=None, request=None, logger=request_logger, level=None, exception=None, ): """ Log errors based on HttpResponse status. Log 5xx responses as errors and 4xx responses as warnings (unless a level is given as a keyword argument). The HttpResponse status_code and the request are passed to the logger's extra parameter. """ # Check if the response has already been logged. Multiple requests to log # the same response can be received in some cases, e.g., when the # response is the result of an exception and is logged when the exception # is caught, to record the exception. if getattr(response, "_has_been_logged", False): return if level is None: if response.status_code >= 500: level = "error" elif response.status_code >= 400: level = "warning" else: level = "info" getattr(logger, level)( message, *args, extra={ "status_code": response.status_code, "request": request, }, exc_info=exception, ) response._has_been_logged = True
6dccb85c5b2a9ece3f15404439f59c855003c330c01ebc0ad25938a06edf02a0
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ from functools import wraps from django.utils.functional import keep_lazy class SafeData: __slots__ = () def __html__(self): """ Return the html representation of a string for interoperability. This allows other template engines to understand Django's SafeData. """ return self class SafeString(str, SafeData): """ A str subclass that has been specifically marked as "safe" for HTML output purposes. """ __slots__ = () def __add__(self, rhs): """ Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe. """ t = super().__add__(rhs) if isinstance(rhs, SafeData): return SafeString(t) return t def __str__(self): return self SafeText = SafeString # For backwards compatibility since Django 2.0. def _safety_decorator(safety_marker, func): @wraps(func) def wrapped(*args, **kwargs): return safety_marker(func(*args, **kwargs)) return wrapped @keep_lazy(SafeString) def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string. """ if hasattr(s, "__html__"): return s if callable(s): return _safety_decorator(mark_safe, s) return SafeString(s)
244c597e68aa4a2c50fee8d8ed433ab0d4a15693b90ac17ed211f6ab2b78e04a
""" Based on "python-archive" -- https://pypi.org/project/python-archive/ Copyright (c) 2010 Gary Wilson Jr. <[email protected]> and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import shutil import stat import tarfile import zipfile from django.core.exceptions import SuspiciousOperation class ArchiveException(Exception): """ Base exception class for all archive errors. """ class UnrecognizedArchiveFormat(ArchiveException): """ Error raised when passed file is not a recognized archive format. """ def extract(path, to_path): """ Unpack the tar or zip file at the specified path to the directory specified by to_path. """ with Archive(path) as archive: archive.extract(to_path) class Archive: """ The external API class that encapsulates an archive implementation. """ def __init__(self, file): self._archive = self._archive_cls(file)(file) @staticmethod def _archive_cls(file): cls = None if isinstance(file, str): filename = file else: try: filename = file.name except AttributeError: raise UnrecognizedArchiveFormat( "File object not a recognized archive format." ) base, tail_ext = os.path.splitext(filename.lower()) cls = extension_map.get(tail_ext) if not cls: base, ext = os.path.splitext(base) cls = extension_map.get(ext) if not cls: raise UnrecognizedArchiveFormat( "Path not a recognized archive format: %s" % filename ) return cls def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def extract(self, to_path): self._archive.extract(to_path) def list(self): self._archive.list() def close(self): self._archive.close() class BaseArchive: """ Base Archive class. Implementations should inherit this class. """ @staticmethod def _copy_permissions(mode, filename): """ If the file in the archive has some permissions (this assumes a file won't be writable/executable without being readable), apply those permissions to the unarchived file. """ if mode & stat.S_IROTH: os.chmod(filename, mode) def split_leading_dir(self, path): path = str(path) path = path.lstrip("/").lstrip("\\") if "/" in path and ( ("\\" in path and path.find("/") < path.find("\\")) or "\\" not in path ): return path.split("/", 1) elif "\\" in path: return path.split("\\", 1) else: return path, "" def has_leading_dir(self, paths): """ Return True if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive). """ common_prefix = None for path in paths: prefix, rest = self.split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True def target_filename(self, to_path, name): target_path = os.path.abspath(to_path) filename = os.path.abspath(os.path.join(target_path, name)) if not filename.startswith(target_path): raise SuspiciousOperation("Archive contains invalid path: '%s'" % name) return filename def extract(self): raise NotImplementedError( "subclasses of BaseArchive must provide an extract() method" ) def list(self): raise NotImplementedError( "subclasses of BaseArchive must provide a list() method" ) class TarArchive(BaseArchive): def __init__(self, file): self._archive = tarfile.open(file) def list(self, *args, **kwargs): self._archive.list(*args, **kwargs) def extract(self, to_path): members = self._archive.getmembers() leading = self.has_leading_dir(x.name for x in members) for member in members: name = member.name if leading: name = self.split_leading_dir(name)[1] filename = self.target_filename(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True) else: try: extracted = self._archive.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) print( "In the tar file %s the member %s is invalid: %s" % (name, member.name, exc) ) else: dirname = os.path.dirname(filename) if dirname: os.makedirs(dirname, exist_ok=True) with open(filename, "wb") as outfile: shutil.copyfileobj(extracted, outfile) self._copy_permissions(member.mode, filename) finally: if extracted: extracted.close() def close(self): self._archive.close() class ZipArchive(BaseArchive): def __init__(self, file): self._archive = zipfile.ZipFile(file) def list(self, *args, **kwargs): self._archive.printdir(*args, **kwargs) def extract(self, to_path): namelist = self._archive.namelist() leading = self.has_leading_dir(namelist) for name in namelist: data = self._archive.read(name) info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] if not name: continue filename = self.target_filename(to_path, name) if name.endswith(("/", "\\")): # A directory os.makedirs(filename, exist_ok=True) else: dirname = os.path.dirname(filename) if dirname: os.makedirs(dirname, exist_ok=True) with open(filename, "wb") as outfile: outfile.write(data) # Convert ZipInfo.external_attr to mode mode = info.external_attr >> 16 self._copy_permissions(mode, filename) def close(self): self._archive.close() extension_map = dict.fromkeys( ( ".tar", ".tar.bz2", ".tbz2", ".tbz", ".tz2", ".tar.gz", ".tgz", ".taz", ".tar.lzma", ".tlz", ".tar.xz", ".txz", ), TarArchive, ) extension_map[".zip"] = ZipArchive
c94b4180a86c85fb48a4f834e2973522b2e9381c9d6487fb8348ac14220966a9
""" Utility functions for generating "lorem ipsum" Latin text. """ import random COMMON_P = ( "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." ) WORDS = ( "exercitationem", "perferendis", "perspiciatis", "laborum", "eveniet", "sunt", "iure", "nam", "nobis", "eum", "cum", "officiis", "excepturi", "odio", "consectetur", "quasi", "aut", "quisquam", "vel", "eligendi", "itaque", "non", "odit", "tempore", "quaerat", "dignissimos", "facilis", "neque", "nihil", "expedita", "vitae", "vero", "ipsum", "nisi", "animi", "cumque", "pariatur", "velit", "modi", "natus", "iusto", "eaque", "sequi", "illo", "sed", "ex", "et", "voluptatibus", "tempora", "veritatis", "ratione", "assumenda", "incidunt", "nostrum", "placeat", "aliquid", "fuga", "provident", "praesentium", "rem", "necessitatibus", "suscipit", "adipisci", "quidem", "possimus", "voluptas", "debitis", "sint", "accusantium", "unde", "sapiente", "voluptate", "qui", "aspernatur", "laudantium", "soluta", "amet", "quo", "aliquam", "saepe", "culpa", "libero", "ipsa", "dicta", "reiciendis", "nesciunt", "doloribus", "autem", "impedit", "minima", "maiores", "repudiandae", "ipsam", "obcaecati", "ullam", "enim", "totam", "delectus", "ducimus", "quis", "voluptates", "dolores", "molestiae", "harum", "dolorem", "quia", "voluptatem", "molestias", "magni", "distinctio", "omnis", "illum", "dolorum", "voluptatum", "ea", "quas", "quam", "corporis", "quae", "blanditiis", "atque", "deserunt", "laboriosam", "earum", "consequuntur", "hic", "cupiditate", "quibusdam", "accusamus", "ut", "rerum", "error", "minus", "eius", "ab", "ad", "nemo", "fugit", "officia", "at", "in", "id", "quos", "reprehenderit", "numquam", "iste", "fugiat", "sit", "inventore", "beatae", "repellendus", "magnam", "recusandae", "quod", "explicabo", "doloremque", "aperiam", "consequatur", "asperiores", "commodi", "optio", "dolor", "labore", "temporibus", "repellat", "veniam", "architecto", "est", "esse", "mollitia", "nulla", "a", "similique", "eos", "alias", "dolore", "tenetur", "deleniti", "porro", "facere", "maxime", "corrupti", ) COMMON_WORDS = ( "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", ) def sentence(): """ Return a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random. """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [ " ".join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5)) ] s = ", ".join(sections) # Convert to sentence case and add end punctuation. return "%s%s%s" % (s[0].upper(), s[1:], random.choice("?.")) def paragraph(): """ Return a randomly generated paragraph of lorem ipsum text. The paragraph consists of between 1 and 4 sentences, inclusive. """ return " ".join(sentence() for i in range(random.randint(1, 4))) def paragraphs(count, common=True): """ Return a list of paragraphs as returned by paragraph(). If `common` is True, then the first paragraph will be the standard 'lorem ipsum' paragraph. Otherwise, the first paragraph will be random Latin text. Either way, subsequent paragraphs will be random Latin text. """ paras = [] for i in range(count): if common and i == 0: paras.append(COMMON_P) else: paras.append(paragraph()) return paras def words(count, common=True): """ Return a string of `count` lorem ipsum words separated by a single space. If `common` is True, then the first 19 words will be the standard 'lorem ipsum' words. Otherwise, all words will be selected randomly. """ word_list = list(COMMON_WORDS) if common else [] c = len(word_list) if count > c: count -= c while count > 0: c = min(count, len(WORDS)) count -= c word_list += random.sample(WORDS, c) else: word_list = word_list[:count] return " ".join(word_list)
791a91aad6efacfe0fd8009a3a79f9e088d5e8b4ef0794a5d5d4cdc9f7f25ff4
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", ... description="A group blog by the sharpest minds in online journalism.", ... language="en", ... ) >>> feed.add_item( ... title="Hello", ... link="http://www.holovaty.com/test/", ... description="Testing." ... ) >>> with open('test.rss', 'w') as fp: ... feed.write(fp, 'utf-8') For definitions of the different versions of RSS, see: https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss """ import datetime import email from io import StringIO from urllib.parse import urlparse from django.utils.encoding import iri_to_uri from django.utils.timezone import utc from django.utils.xmlutils import SimplerXMLGenerator def rfc2822_date(date): if not isinstance(date, datetime.datetime): date = datetime.datetime.combine(date, datetime.time()) return email.utils.format_datetime(date) def rfc3339_date(date): if not isinstance(date, datetime.datetime): date = datetime.datetime.combine(date, datetime.time()) return date.isoformat() + ("Z" if date.utcoffset() is None else "") def get_tag_uri(url, date): """ Create a TagURI. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = "" if date is not None: d = ",%s" % date.strftime("%Y-%m-%d") return "tag:%s%s:%s/%s" % (bits.hostname, d, bits.path, bits.fragment) class SyndicationFeed: "Base class for all syndication feeds. Subclasses should provide write()" def __init__( self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs, ): def to_str(s): return str(s) if s is not None else s categories = categories and [str(c) for c in categories] self.feed = { "title": to_str(title), "link": iri_to_uri(link), "description": to_str(description), "language": to_str(language), "author_email": to_str(author_email), "author_name": to_str(author_name), "author_link": iri_to_uri(author_link), "subtitle": to_str(subtitle), "categories": categories or (), "feed_url": iri_to_uri(feed_url), "feed_copyright": to_str(feed_copyright), "id": feed_guid or link, "ttl": to_str(ttl), **kwargs, } self.items = [] def add_item( self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, unique_id_is_permalink=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs, ): """ Add an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is an iterable of instances of the Enclosure class. """ def to_str(s): return str(s) if s is not None else s categories = categories and [to_str(c) for c in categories] self.items.append( { "title": to_str(title), "link": iri_to_uri(link), "description": to_str(description), "author_email": to_str(author_email), "author_name": to_str(author_name), "author_link": iri_to_uri(author_link), "pubdate": pubdate, "updateddate": updateddate, "comments": to_str(comments), "unique_id": to_str(unique_id), "unique_id_is_permalink": unique_id_is_permalink, "enclosures": enclosures or (), "categories": categories or (), "item_copyright": to_str(item_copyright), "ttl": to_str(ttl), **kwargs, } ) def num_items(self): return len(self.items) def root_attributes(self): """ Return extra attributes to place on the root (i.e. feed/channel) element. Called from write(). """ return {} def add_root_elements(self, handler): """ Add elements in the root (i.e. feed/channel) element. Called from write(). """ pass def item_attributes(self, item): """ Return extra attributes to place on each item (i.e. item/entry) element. """ return {} def add_item_elements(self, handler, item): """ Add elements on each item (i.e. item/entry) element. """ pass def write(self, outfile, encoding): """ Output the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. """ raise NotImplementedError( "subclasses of SyndicationFeed must provide a write() method" ) def writeString(self, encoding): """ Return the feed in the given encoding as a string. """ s = StringIO() self.write(s, encoding) return s.getvalue() def latest_post_date(self): """ Return the latest item's pubdate or updateddate. If no items have either of these attributes this return the current UTC date/time. """ latest_date = None date_keys = ("updateddate", "pubdate") for item in self.items: for date_key in date_keys: item_date = item.get(date_key) if item_date: if latest_date is None or item_date > latest_date: latest_date = item_date return latest_date or datetime.datetime.now(tz=utc) class Enclosure: """An RSS enclosure""" def __init__(self, url, length, mime_type): "All args are expected to be strings" self.length, self.mime_type = length, mime_type self.url = iri_to_uri(url) class RssFeed(SyndicationFeed): content_type = "application/rss+xml; charset=utf-8" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True) handler.startDocument() handler.startElement("rss", self.rss_attributes()) handler.startElement("channel", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) self.endChannelElement(handler) handler.endElement("rss") def rss_attributes(self): return { "version": self._version, "xmlns:atom": "http://www.w3.org/2005/Atom", } def write_items(self, handler): for item in self.items: handler.startElement("item", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("item") def add_root_elements(self, handler): handler.addQuickElement("title", self.feed["title"]) handler.addQuickElement("link", self.feed["link"]) handler.addQuickElement("description", self.feed["description"]) if self.feed["feed_url"] is not None: handler.addQuickElement( "atom:link", None, {"rel": "self", "href": self.feed["feed_url"]} ) if self.feed["language"] is not None: handler.addQuickElement("language", self.feed["language"]) for cat in self.feed["categories"]: handler.addQuickElement("category", cat) if self.feed["feed_copyright"] is not None: handler.addQuickElement("copyright", self.feed["feed_copyright"]) handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) if self.feed["ttl"] is not None: handler.addQuickElement("ttl", self.feed["ttl"]) def endChannelElement(self, handler): handler.endElement("channel") class RssUserland091Feed(RssFeed): _version = "0.91" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"]) class Rss201rev2Feed(RssFeed): # Spec: https://cyber.harvard.edu/rss/rss.html _version = "2.0" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"]) # Author information. if item["author_name"] and item["author_email"]: handler.addQuickElement( "author", "%s (%s)" % (item["author_email"], item["author_name"]) ) elif item["author_email"]: handler.addQuickElement("author", item["author_email"]) elif item["author_name"]: handler.addQuickElement( "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"}, ) if item["pubdate"] is not None: handler.addQuickElement("pubDate", rfc2822_date(item["pubdate"])) if item["comments"] is not None: handler.addQuickElement("comments", item["comments"]) if item["unique_id"] is not None: guid_attrs = {} if isinstance(item.get("unique_id_is_permalink"), bool): guid_attrs["isPermaLink"] = str(item["unique_id_is_permalink"]).lower() handler.addQuickElement("guid", item["unique_id"], guid_attrs) if item["ttl"] is not None: handler.addQuickElement("ttl", item["ttl"]) # Enclosure. if item["enclosures"]: enclosures = list(item["enclosures"]) if len(enclosures) > 1: raise ValueError( "RSS feed items may only have one enclosure, see " "http://www.rssboard.org/rss-profile#element-channel-item-enclosure" ) enclosure = enclosures[0] handler.addQuickElement( "enclosure", "", { "url": enclosure.url, "length": enclosure.length, "type": enclosure.mime_type, }, ) # Categories. for cat in item["categories"]: handler.addQuickElement("category", cat) class Atom1Feed(SyndicationFeed): # Spec: https://tools.ietf.org/html/rfc4287 content_type = "application/atom+xml; charset=utf-8" ns = "http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True) handler.startDocument() handler.startElement("feed", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) handler.endElement("feed") def root_attributes(self): if self.feed["language"] is not None: return {"xmlns": self.ns, "xml:lang": self.feed["language"]} else: return {"xmlns": self.ns} def add_root_elements(self, handler): handler.addQuickElement("title", self.feed["title"]) handler.addQuickElement( "link", "", {"rel": "alternate", "href": self.feed["link"]} ) if self.feed["feed_url"] is not None: handler.addQuickElement( "link", "", {"rel": "self", "href": self.feed["feed_url"]} ) handler.addQuickElement("id", self.feed["id"]) handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) if self.feed["author_name"] is not None: handler.startElement("author", {}) handler.addQuickElement("name", self.feed["author_name"]) if self.feed["author_email"] is not None: handler.addQuickElement("email", self.feed["author_email"]) if self.feed["author_link"] is not None: handler.addQuickElement("uri", self.feed["author_link"]) handler.endElement("author") if self.feed["subtitle"] is not None: handler.addQuickElement("subtitle", self.feed["subtitle"]) for cat in self.feed["categories"]: handler.addQuickElement("category", "", {"term": cat}) if self.feed["feed_copyright"] is not None: handler.addQuickElement("rights", self.feed["feed_copyright"]) def write_items(self, handler): for item in self.items: handler.startElement("entry", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("entry") def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", "", {"href": item["link"], "rel": "alternate"}) if item["pubdate"] is not None: handler.addQuickElement("published", rfc3339_date(item["pubdate"])) if item["updateddate"] is not None: handler.addQuickElement("updated", rfc3339_date(item["updateddate"])) # Author information. if item["author_name"] is not None: handler.startElement("author", {}) handler.addQuickElement("name", item["author_name"]) if item["author_email"] is not None: handler.addQuickElement("email", item["author_email"]) if item["author_link"] is not None: handler.addQuickElement("uri", item["author_link"]) handler.endElement("author") # Unique ID. if item["unique_id"] is not None: unique_id = item["unique_id"] else: unique_id = get_tag_uri(item["link"], item["pubdate"]) handler.addQuickElement("id", unique_id) # Summary. if item["description"] is not None: handler.addQuickElement("summary", item["description"], {"type": "html"}) # Enclosures. for enclosure in item["enclosures"]: handler.addQuickElement( "link", "", { "rel": "enclosure", "href": enclosure.url, "length": enclosure.length, "type": enclosure.mime_type, }, ) # Categories. for cat in item["categories"]: handler.addQuickElement("category", "", {"term": cat}) # Rights. if item["item_copyright"] is not None: handler.addQuickElement("rights", item["item_copyright"]) # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". DefaultFeed = Rss201rev2Feed
45a797d984dc7b523d5c9b10d3f16a61372e74f339c6effef8cd6d0199bb2ce0
from importlib import import_module from django.utils.version import get_docs_version def deconstructible(*args, path=None): """ Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path. """ def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(klass, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj def deconstruct(obj): """ Return a 3-tuple of class import path, positional arguments, and keyword arguments. """ # Fallback version if path and type(obj) is klass: module_name, _, name = path.rpartition(".") else: module_name = obj.__module__ name = obj.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/%s/topics/migrations/" "#serializing-values" % (name, module_name, get_docs_version()) ) return ( path if path and type(obj) is klass else f"{obj.__class__.__module__}.{name}", obj._constructor_args[0], obj._constructor_args[1], ) klass.__new__ = staticmethod(__new__) klass.deconstruct = deconstruct return klass if not args: return decorator return decorator(*args)
1a155cb6709590fb25f11258cf6c13aa910b330dcd663e35c7cde800e7280cf3
import copy import itertools import operator import warnings from functools import total_ordering, wraps class cached_property: """ Decorator that converts a method with a single self argument into a property cached on the instance. A cached property can be made out of an existing method: (e.g. ``url = cached_property(get_absolute_url)``). """ name = None @staticmethod def func(instance): raise TypeError( "Cannot use cached_property instance without calling " "__set_name__() on it." ) def __init__(self, func, name=None): from django.utils.deprecation import RemovedInDjango50Warning if name is not None: warnings.warn( "The name argument is deprecated as it's unnecessary as of " "Python 3.6.", RemovedInDjango50Warning, stacklevel=2, ) self.real_func = func self.__doc__ = getattr(func, "__doc__") def __set_name__(self, owner, name): if self.name is None: self.name = name self.func = self.real_func elif name != self.name: raise TypeError( "Cannot assign the same cached_property to two different names " "(%r and %r)." % (self.name, name) ) def __get__(self, instance, cls=None): """ Call the function and put the return value in instance.__dict__ so that subsequent attribute access on the instance returns the cached value instead of calling cached_property.__get__(). """ if instance is None: return self res = instance.__dict__[self.name] = self.func(instance) return res class classproperty: """ Decorator that converts a method with a single cls argument into a property that can be accessed directly from the class. """ def __init__(self, method=None): self.fget = method def __get__(self, instance, cls=None): return self.fget(cls) def getter(self, method): self.fget = method return self class Promise: """ Base class for the proxy class created in the closure of the lazy function. It's used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turn any callable into a lazy evaluated callable. result classes or types is required -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ @total_ordering class __proxy__(Promise): """ Encapsulate a function call and act as a proxy for methods that are called on the result of that function. The function is not evaluated until one of the methods on the result is called. """ __prepared = False def __init__(self, args, kw): self.__args = args self.__kw = kw if not self.__prepared: self.__prepare_class__() self.__class__.__prepared = True def __reduce__(self): return ( _lazy_proxy_unpickle, (func, self.__args, self.__kw) + resultclasses, ) def __repr__(self): return repr(self.__cast()) @classmethod def __prepare_class__(cls): for resultclass in resultclasses: for type_ in resultclass.mro(): for method_name in type_.__dict__: # All __promise__ return the same wrapper method, they # look up the correct implementation when called. if hasattr(cls, method_name): continue meth = cls.__promise__(method_name) setattr(cls, method_name, meth) cls._delegate_bytes = bytes in resultclasses cls._delegate_text = str in resultclasses if cls._delegate_bytes and cls._delegate_text: raise ValueError( "Cannot call lazy() with both bytes and text return types." ) if cls._delegate_text: cls.__str__ = cls.__text_cast elif cls._delegate_bytes: cls.__bytes__ = cls.__bytes_cast @classmethod def __promise__(cls, method_name): # Builds a wrapper around some magic method def __wrapper__(self, *args, **kw): # Automatically triggers the evaluation of a lazy value and # applies the given magic method of the result type. res = func(*self.__args, **self.__kw) return getattr(res, method_name)(*args, **kw) return __wrapper__ def __text_cast(self): return func(*self.__args, **self.__kw) def __bytes_cast(self): return bytes(func(*self.__args, **self.__kw)) def __bytes_cast_encoded(self): return func(*self.__args, **self.__kw).encode() def __cast(self): if self._delegate_bytes: return self.__bytes_cast() elif self._delegate_text: return self.__text_cast() else: return func(*self.__args, **self.__kw) def __str__(self): # object defines __str__(), so __prepare_class__() won't overload # a __str__() method from the proxied class. return str(self.__cast()) def __eq__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() == other def __lt__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() < other def __hash__(self): return hash(self.__cast()) def __mod__(self, rhs): if self._delegate_text: return str(self) % rhs return self.__cast() % rhs def __add__(self, other): return self.__cast() + other def __radd__(self, other): return other + self.__cast() def __deepcopy__(self, memo): # Instances of this class are effectively immutable. It's just a # collection of functions. So we don't need to do anything # complicated for copying. memo[id(self)] = self return self @wraps(func) def __wrapper__(*args, **kw): # Creates the proxy object, instead of the actual value. return __proxy__(args, kw) return __wrapper__ def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses): return lazy(func, *resultclasses)(*args, **kwargs) def lazystr(text): """ Shortcut for the common case of a lazy callable that returns str. """ return lazy(str, str)(text) def keep_lazy(*resultclasses): """ A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed. """ if not resultclasses: raise TypeError("You must pass at least one argument to keep_lazy().") def decorator(func): lazy_func = lazy(func, *resultclasses) @wraps(func) def wrapper(*args, **kwargs): if any( isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values()) ): return lazy_func(*args, **kwargs) return func(*args, **kwargs) return wrapper return decorator def keep_lazy_text(func): """ A decorator for functions that accept lazy arguments and return text. """ return keep_lazy(str)(func) empty = object() def new_method_proxy(func): def inner(self, *args): if self._wrapped is empty: self._setup() return func(self._wrapped, *args) inner._mask_wrapped = False return inner class LazyObject: """ A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the instantiation. If you don't need to do that, use SimpleLazyObject. """ # Avoid infinite recursion when tracing __init__ (#19456). _wrapped = None def __init__(self): # Note: if a subclass overrides __init__(), it will likely need to # override __copy__() and __deepcopy__() as well. self._wrapped = empty def __getattribute__(self, name): if name == "_wrapped": # Avoid recursion when getting wrapped object. return super().__getattribute__(name) value = super().__getattribute__(name) # If attribute is a proxy method, raise an AttributeError to call # __getattr__() and use the wrapped object method. if not getattr(value, "_mask_wrapped", True): raise AttributeError return value __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value): if name == "_wrapped": # Assign to __dict__ to avoid infinite __setattr__ loops. self.__dict__["_wrapped"] = value else: if self._wrapped is empty: self._setup() setattr(self._wrapped, name, value) def __delattr__(self, name): if name == "_wrapped": raise TypeError("can't delete _wrapped.") if self._wrapped is empty: self._setup() delattr(self._wrapped, name) def _setup(self): """ Must be implemented by subclasses to initialize the wrapped object. """ raise NotImplementedError( "subclasses of LazyObject must provide a _setup() method" ) # Because we have messed with __class__ below, we confuse pickle as to what # class we are pickling. We're going to have to initialize the wrapped # object to successfully pickle it, so we might as well just pickle the # wrapped object since they're supposed to act the same way. # # Unfortunately, if we try to simply act like the wrapped object, the ruse # will break down when pickle gets our id(). Thus we end up with pickle # thinking, in effect, that we are a distinct object from the wrapped # object, but with the same __dict__. This can cause problems (see #25389). # # So instead, we define our own __reduce__ method and custom unpickler. We # pickle the wrapped object as the unpickler's argument, so that pickle # will pickle it normally, and then the unpickler simply returns its # argument. def __reduce__(self): if self._wrapped is empty: self._setup() return (unpickle_lazyobject, (self._wrapped,)) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use type(self), not # self.__class__, because the latter is proxied. return type(self)() else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use type(self), not self.__class__, because the # latter is proxied. result = type(self)() memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) __bytes__ = new_method_proxy(bytes) __str__ = new_method_proxy(str) __bool__ = new_method_proxy(bool) # Introspection support __dir__ = new_method_proxy(dir) # Need to pretend to be the wrapped class, for the sake of objects that # care about this (especially in equality tests) __class__ = property(new_method_proxy(operator.attrgetter("__class__"))) __eq__ = new_method_proxy(operator.eq) __lt__ = new_method_proxy(operator.lt) __gt__ = new_method_proxy(operator.gt) __ne__ = new_method_proxy(operator.ne) __hash__ = new_method_proxy(hash) # List/Tuple/Dictionary methods support __getitem__ = new_method_proxy(operator.getitem) __setitem__ = new_method_proxy(operator.setitem) __delitem__ = new_method_proxy(operator.delitem) __iter__ = new_method_proxy(iter) __len__ = new_method_proxy(len) __contains__ = new_method_proxy(operator.contains) def unpickle_lazyobject(wrapped): """ Used to unpickle lazy objects. Just return its argument, which will be the wrapped object. """ return wrapped class SimpleLazyObject(LazyObject): """ A lazy object initialized from any function. Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy. """ def __init__(self, func): """ Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value. """ self.__dict__["_setupfunc"] = func super().__init__() def _setup(self): self._wrapped = self._setupfunc() # Return a meaningful representation of the lazy object for debugging # without evaluating the wrapped object. def __repr__(self): if self._wrapped is empty: repr_attr = self._setupfunc else: repr_attr = self._wrapped return "<%s: %r>" % (type(self).__name__, repr_attr) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use SimpleLazyObject, not # self.__class__, because the latter is proxied. return SimpleLazyObject(self._setupfunc) else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use SimpleLazyObject, not self.__class__, because the # latter is proxied. result = SimpleLazyObject(self._setupfunc) memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) __add__ = new_method_proxy(operator.add) @new_method_proxy def __radd__(self, other): return other + self def partition(predicate, values): """ Split the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item) return results
d2094e8377869a6b3e814bf4e19803bd9b75f4865b74f042eb83e768aa9e1837
import os from asyncio import get_running_loop from functools import wraps from django.core.exceptions import SynchronousOnlyOperation def async_unsafe(message): """ Decorator to mark functions as async-unsafe. Someone trying to access the function while in an async context will get an error message. """ def decorator(func): @wraps(func) def inner(*args, **kwargs): # Detect a running event loop in this thread. try: get_running_loop() except RuntimeError: pass else: if not os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE"): raise SynchronousOnlyOperation(message) # Pass onward. return func(*args, **kwargs) return inner # If the message is actually a function, then be a no-arguments decorator. if callable(message): func = message message = ( "You cannot call this from an async context - use a thread or " "sync_to_async." ) return decorator(func) else: return decorator
95a0ce41efebe16fa854a2ce810e1a009c6cdfb9fc3f72e41fe79e21c849aa1e
import ipaddress from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def clean_ipv6_address( ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.") ): """ Clean an IPv6 address string. Raise ValidationError if the address is invalid. Replace the longest continuous zero-sequence with "::", remove leading zeroes, and make sure all hextets are lowercase. Args: ip_str: A valid IPv6 address. unpack_ipv4: if an IPv4-mapped address is found, return the plain IPv4 address (default=False). error_message: An error message used in the ValidationError. Return a compressed IPv6 address or the same value. """ try: addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) except ValueError: raise ValidationError(error_message, code="invalid") if unpack_ipv4 and addr.ipv4_mapped: return str(addr.ipv4_mapped) elif addr.ipv4_mapped: return "::ffff:%s" % str(addr.ipv4_mapped) return str(addr) def is_valid_ipv6_address(ip_str): """ Return whether or not the `ip_str` string is a valid IPv6 address. """ try: ipaddress.IPv6Address(ip_str) except ValueError: return False return True
608ec43d4723248cf09bfa45b06f1f8fff3ba3dc56b8cd6cef8c595528a5f07f
import base64 import datetime import re import unicodedata from binascii import Error as BinasciiError from email.utils import formatdate from urllib.parse import ( ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, scheme_chars, ) from urllib.parse import urlencode as original_urlencode from urllib.parse import uses_params from django.utils.datastructures import MultiValueDict from django.utils.regex_helper import _lazy_re_compile # based on RFC 7232, Appendix C ETAG_MATCH = _lazy_re_compile( r""" \A( # start of string and capture group (?:W/)? # optional weak indicator " # opening quote [^"]* # any sequence of non-quote characters " # end quote )\Z # end of string and capture group """, re.X, ) MONTHS = "jan feb mar apr may jun jul aug sep oct nov dec".split() __D = r"(?P<day>[0-9]{2})" __D2 = r"(?P<day>[ 0-9][0-9])" __M = r"(?P<mon>\w{3})" __Y = r"(?P<year>[0-9]{4})" __Y2 = r"(?P<year>[0-9]{2})" __T = r"(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2})" RFC1123_DATE = _lazy_re_compile(r"^\w{3}, %s %s %s %s GMT$" % (__D, __M, __Y, __T)) RFC850_DATE = _lazy_re_compile(r"^\w{6,9}, %s-%s-%s %s GMT$" % (__D, __M, __Y2, __T)) ASCTIME_DATE = _lazy_re_compile(r"^\w{3} %s %s %s %s$" % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = ":/?#[]@" RFC3986_SUBDELIMS = "!$&'()*+,;=" def urlencode(query, doseq=False): """ A version of Python's urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, "items"): query = query.items() query_params = [] for key, value in query: if value is None: raise TypeError( "Cannot encode None for key '%s' in a query string. Did you " "mean to pass an empty string or omit the value?" % key ) elif not doseq or isinstance(value, (str, bytes)): query_val = value else: try: itr = iter(value) except TypeError: query_val = value else: # Consume generators and iterators, when doseq=True, to # work around https://bugs.python.org/issue31706. query_val = [] for item in itr: if item is None: raise TypeError( "Cannot encode None for key '%s' in a query " "string. Did you mean to pass an empty string or " "omit the value?" % key ) elif not isinstance(item, bytes): item = str(item) query_val.append(item) query_params.append((key, query_val)) return original_urlencode(query_params, doseq) def http_date(epoch_seconds=None): """ Format the time to match the RFC1123 date format as specified by HTTP RFC7231 section 7.1.1.1. `epoch_seconds` is a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, it defaults to the current time. Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. """ # email.utils.parsedate() does the job for RFC1123 dates; unfortunately # RFC7231 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: tz = datetime.timezone.utc year = int(m["year"]) if year < 100: current_year = datetime.datetime.now(tz=tz).year current_century = current_year - (current_year % 100) if year - (current_year % 100) > 50: # year that appears to be more than 50 years in the future are # interpreted as representing the past. year += current_century - 100 else: year += current_century month = MONTHS.index(m["mon"].lower()) + 1 day = int(m["day"]) hour = int(m["hour"]) min = int(m["min"]) sec = int(m["sec"]) result = datetime.datetime(year, month, day, hour, min, sec, tzinfo=tz) return int(result.timestamp()) except Exception as exc: raise ValueError("%r is not a valid date" % date) from exc def parse_http_date_safe(date): """ Same as parse_http_date, but return None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Convert a base 36 string to an int. Raise ValueError if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is longer than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") return int(s, 36) def int_to_base36(i): """Convert an integer to a base36 string.""" char_set = "0123456789abcdefghijklmnopqrstuvwxyz" if i < 0: raise ValueError("Negative base36 conversion input.") if i < 36: return char_set[i] b36 = "" while i != 0: i, n = divmod(i, 36) b36 = char_set[n] + b36 return b36 def urlsafe_base64_encode(s): """ Encode a bytestring to a base64 string for use in URLs. Strip any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b"\n=").decode("ascii") def urlsafe_base64_decode(s): """ Decode a base64 encoded string. Add back any trailing equal signs that might have been stripped. """ s = s.encode() try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b"=")) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parse a string of ETags given in an If-None-Match or If-Match header as defined by RFC 7232. Return a list of quoted ETags, or ['*'] if all ETags should be matched. """ if etag_str.strip() == "*": return ["*"] else: # Parse each ETag individually, and return any that are valid. etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(",")) return [match[1] for match in etag_matches if match] def quote_etag(etag_str): """ If the provided string is already a quoted ETag, return it. Otherwise, wrap the string in quotes, making it a strong ETag. """ if ETAG_MATCH.match(etag_str): return etag_str else: return '"%s"' % etag_str def is_same_domain(host, pattern): """ Return ``True`` if the host is either an exact match or a match to the wildcard pattern. Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. ``.example.com`` matches ``example.com`` and ``foo.example.com``). Anything else is an exact string match. """ if not pattern: return False pattern = pattern.lower() return ( pattern[0] == "." and (host.endswith(pattern) or host == pattern[1:]) or pattern == host ) def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): """ Return ``True`` if the url uses an allowed host and a safe scheme. Always return ``False`` on an empty url. If ``require_https`` is ``True``, only 'https' will be considered a valid scheme, as opposed to 'http' and 'https' with the default, ``False``. Note: "True" doesn't entail that a URL is "safe". It may still be e.g. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri() on the path component of untrusted URLs. """ if url is not None: url = url.strip() if not url: return False if allowed_hosts is None: allowed_hosts = set() elif isinstance(allowed_hosts, str): allowed_hosts = {allowed_hosts} # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _url_has_allowed_host_and_scheme( url, allowed_hosts, require_https=require_https ) and _url_has_allowed_host_and_scheme( url.replace("\\", "/"), allowed_hosts, require_https=require_https ) # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme="", allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Return a 6-tuple: (scheme, netloc, path, params, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) splitresult = _urlsplit(url, scheme, allow_fragments) scheme, netloc, url, query, fragment = splitresult if scheme in uses_params and ";" in url: url, params = _splitparams(url) else: params = "" result = ParseResult(scheme, netloc, url, params, query, fragment) return _coerce_result(result) # Copied from urllib.parse.urlsplit() with # https://github.com/python/cpython/pull/661 applied. def _urlsplit(url, scheme="", allow_fragments=True): """Parse a URL into 5 components: <scheme>://<netloc>/<path>?<query>#<fragment> Return a 5-tuple: (scheme, netloc, path, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) netloc = query = fragment = "" i = url.find(":") if i > 0: for c in url[:i]: if c not in scheme_chars: break else: scheme, url = url[:i].lower(), url[i + 1 :] if url[:2] == "//": netloc, url = _splitnetloc(url, 2) if ("[" in netloc and "]" not in netloc) or ( "]" in netloc and "[" not in netloc ): raise ValueError("Invalid IPv6 URL") if allow_fragments and "#" in url: url, fragment = url.split("#", 1) if "?" in url: url, query = url.split("?", 1) v = SplitResult(scheme, netloc, url, query, fragment) return _coerce_result(v) def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.startswith("///"): return False try: url_info = _urlparse(url) except ValueError: # e.g. invalid IPv6 addresses return False # Forbid URLs like http:///example.com - with a scheme, but without a hostname. # In that URL, example.com is not the hostname but, a path component. However, # Chrome will still consider example.com to be the hostname, so we must not # allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == "C": return False scheme = url_info.scheme # Consider URLs without a scheme (e.g. //example.com/p) to be http. if not url_info.scheme and url_info.netloc: scheme = "http" valid_schemes = ["https"] if require_https else ["http", "https"] return (not url_info.netloc or url_info.netloc in allowed_hosts) and ( not scheme or scheme in valid_schemes ) def escape_leading_slashes(url): """ If redirecting to an absolute path (two leading slashes), a slash must be escaped to prevent browsers from handling the path as schemaless and redirecting to another host. """ if url.startswith("//"): url = "/%2F{}".format(url[2:]) return url
0e51b7d4774cf4d50d680672cb99e169079bc985be18aaae7e26573e092ad257
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see: https://tools.ietf.org/html/rfc7231#section-7.1.4 Essentially, the "Vary" HTTP header defines which headers a cache should take into account when building its cache key. Requests with the same path but different header content for headers named in "Vary" need to get different cache keys to prevent delivery of wrong content. An example: i18n middleware would need to distinguish caches by the "Accept-language" header. """ import time from collections import defaultdict from django.conf import settings from django.core.cache import caches from django.http import HttpResponse, HttpResponseNotModified from django.utils.crypto import md5 from django.utils.http import http_date, parse_etags, parse_http_date_safe, quote_etag from django.utils.log import log_response from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import get_current_timezone_name from django.utils.translation import get_language cc_delim_re = _lazy_re_compile(r"\s*,\s*") def patch_cache_control(response, **kwargs): """ Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true value), only the parameter name is added to the header. * All other parameters are added with their value, after applying str() to it. """ def dictitem(s): t = s.split("=", 1) if len(t) > 1: return (t[0].lower(), t[1]) else: return (t[0].lower(), True) def dictvalue(*t): if t[1] is True: return t[0] else: return "%s=%s" % (t[0], t[1]) cc = defaultdict(set) if response.get("Cache-Control"): for field in cc_delim_re.split(response.headers["Cache-Control"]): directive, value = dictitem(field) if directive == "no-cache": # no-cache supports multiple field names. cc[directive].add(value) else: cc[directive] = value # If there's already a max-age header but we're being asked to set a new # max-age, use the minimum of the two ages. In practice this happens when # a decorator and a piece of middleware both operate on a given view. if "max-age" in cc and "max_age" in kwargs: kwargs["max_age"] = min(int(cc["max-age"]), kwargs["max_age"]) # Allow overriding private caching and vice versa if "private" in cc and "public" in kwargs: del cc["private"] elif "public" in cc and "private" in kwargs: del cc["public"] for (k, v) in kwargs.items(): directive = k.replace("_", "-") if directive == "no-cache": # no-cache supports multiple field names. cc[directive].add(v) else: cc[directive] = v directives = [] for directive, values in cc.items(): if isinstance(values, set): if True in values: # True takes precedence. values = {True} directives.extend([dictvalue(directive, value) for value in values]) else: directives.append(dictvalue(directive, values)) cc = ", ".join(directives) response.headers["Cache-Control"] = cc def get_max_age(response): """ Return the max-age from the response Cache-Control header as an integer, or None if it wasn't found or wasn't an integer. """ if not response.has_header("Cache-Control"): return cc = dict( _to_tuple(el) for el in cc_delim_re.split(response.headers["Cache-Control"]) ) try: return int(cc["max-age"]) except (ValueError, TypeError, KeyError): pass def set_response_etag(response): if not response.streaming and response.content: response.headers["ETag"] = quote_etag( md5(response.content, usedforsecurity=False).hexdigest(), ) return response def _precondition_failed(request): response = HttpResponse(status=412) log_response( "Precondition Failed: %s", request.path, response=response, request=request, ) return response def _not_modified(request, response=None): new_response = HttpResponseNotModified() if response: # Preserve the headers required by Section 4.1 of RFC 7232, as well as # Last-Modified. for header in ( "Cache-Control", "Content-Location", "Date", "ETag", "Expires", "Last-Modified", "Vary", ): if header in response: new_response.headers[header] = response.headers[header] # Preserve cookies as per the cookie specification: "If a proxy server # receives a response which contains a Set-cookie header, it should # propagate the Set-cookie header to the client, regardless of whether # the response was 304 (Not Modified) or 200 (OK). # https://curl.haxx.se/rfc/cookie_spec.html new_response.cookies = response.cookies return new_response def get_conditional_response(request, etag=None, last_modified=None, response=None): # Only return conditional responses on successful requests. if response and not (200 <= response.status_code < 300): return response # Get HTTP request headers. if_match_etags = parse_etags(request.META.get("HTTP_IF_MATCH", "")) if_unmodified_since = request.META.get("HTTP_IF_UNMODIFIED_SINCE") if_unmodified_since = if_unmodified_since and parse_http_date_safe( if_unmodified_since ) if_none_match_etags = parse_etags(request.META.get("HTTP_IF_NONE_MATCH", "")) if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE") if_modified_since = if_modified_since and parse_http_date_safe(if_modified_since) # Step 1 of section 6 of RFC 7232: Test the If-Match precondition. if if_match_etags and not _if_match_passes(etag, if_match_etags): return _precondition_failed(request) # Step 2: Test the If-Unmodified-Since precondition. if ( not if_match_etags and if_unmodified_since and not _if_unmodified_since_passes(last_modified, if_unmodified_since) ): return _precondition_failed(request) # Step 3: Test the If-None-Match precondition. if if_none_match_etags and not _if_none_match_passes(etag, if_none_match_etags): if request.method in ("GET", "HEAD"): return _not_modified(request, response) else: return _precondition_failed(request) # Step 4: Test the If-Modified-Since precondition. if ( not if_none_match_etags and if_modified_since and not _if_modified_since_passes(last_modified, if_modified_since) and request.method in ("GET", "HEAD") ): return _not_modified(request, response) # Step 5: Test the If-Range precondition (not supported). # Step 6: Return original response since there isn't a conditional response. return response def _if_match_passes(target_etag, etags): """ Test the If-Match comparison as defined in section 3.1 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there can't be a match. return False elif etags == ["*"]: # The existence of an ETag means that there is "a current # representation for the target resource", even if the ETag is weak, # so there is a match to '*'. return True elif target_etag.startswith("W/"): # A weak ETag can never strongly match another ETag. return False else: # Since the ETag is strong, this will only return True if there's a # strong match. return target_etag in etags def _if_unmodified_since_passes(last_modified, if_unmodified_since): """ Test the If-Unmodified-Since comparison as defined in section 3.4 of RFC 7232. """ return last_modified and last_modified <= if_unmodified_since def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in section 3.2 of RFC 7232. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ["*"]: # The existence of an ETag means that there is "a current # representation for the target resource", so there is a match to '*'. return False else: # The comparison should be weak, so look for a match after stripping # off any weak indicators. target_etag = target_etag.strip("W/") etags = (etag.strip("W/") for etag in etags) return target_etag not in etags def _if_modified_since_passes(last_modified, if_modified_since): """ Test the If-Modified-Since comparison as defined in section 3.3 of RFC 7232. """ return not last_modified or last_modified > if_modified_since def patch_response_headers(response, cache_timeout=None): """ Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS if cache_timeout < 0: cache_timeout = 0 # Can't have max-age negative if not response.has_header("Expires"): response.headers["Expires"] = http_date(time.time() + cache_timeout) patch_cache_control(response, max_age=cache_timeout) def add_never_cache_headers(response): """ Add headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) patch_cache_control( response, no_cache=True, no_store=True, must_revalidate=True, private=True ) def patch_vary_headers(response, newheaders): """ Add (or update) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". If headers contains an asterisk, then "Vary" header will consist of a single asterisk '*'. Otherwise, existing headers in "Vary" aren't removed. """ # Note that we need to keep the original order intact, because cache # implementations may rely on the order of the Vary contents in, say, # computing an MD5 hash. if response.has_header("Vary"): vary_headers = cc_delim_re.split(response.headers["Vary"]) else: vary_headers = [] # Use .lower() here so we treat headers as case-insensitive. existing_headers = {header.lower() for header in vary_headers} additional_headers = [ newheader for newheader in newheaders if newheader.lower() not in existing_headers ] vary_headers += additional_headers if "*" in vary_headers: response.headers["Vary"] = "*" else: response.headers["Vary"] = ", ".join(vary_headers) def has_vary_header(response, header_query): """ Check to see if the response has a given header name in its Vary header. """ if not response.has_header("Vary"): return False vary_headers = cc_delim_re.split(response.headers["Vary"]) existing_headers = {header.lower() for header in vary_headers} return header_query.lower() in existing_headers def _i18n_cache_key_suffix(request, cache_key): """If necessary, add the current locale or time zone to the cache key.""" if settings.USE_I18N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language # which in turn can also fall back to settings.LANGUAGE_CODE cache_key += ".%s" % getattr(request, "LANGUAGE_CODE", get_language()) if settings.USE_TZ: cache_key += ".%s" % get_current_timezone_name() return cache_key def _generate_cache_key(request, method, headerlist, key_prefix): """Return a cache key from the headers given in the header list.""" ctx = md5(usedforsecurity=False) for header in headerlist: value = request.META.get(header) if value is not None: ctx.update(value.encode()) url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) cache_key = "views.decorators.cache.cache_page.%s.%s.%s.%s" % ( key_prefix, method, url.hexdigest(), ctx.hexdigest(), ) return _i18n_cache_key_suffix(request, cache_key) def _generate_cache_header_key(key_prefix, request): """Return a cache key for the header cache.""" url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) cache_key = "views.decorators.cache.cache_header.%s.%s" % ( key_prefix, url.hexdigest(), ) return _i18n_cache_key_suffix(request, cache_key) def get_cache_key(request, key_prefix=None, method="GET", cache=None): """ Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there isn't a headerlist stored, return None, indicating that the page needs to be rebuilt. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learn what headers to take into account for some request URL from the response object. Store those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] if response.has_header("Vary"): is_accept_language_redundant = settings.USE_I18N # If i18n is used, the generated cache key will be suffixed with the # current locale. Adding the raw value of Accept-Language is redundant # in that case and would result in storing the same content under # multiple keys in the cache. See #18191 for details. headerlist = [] for header in cc_delim_re.split(response.headers["Vary"]): header = header.upper().replace("-", "_") if header != "ACCEPT_LANGUAGE" or not is_accept_language_redundant: headerlist.append("HTTP_" + header) headerlist.sort() cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, request.method, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.build_absolute_uri() cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, request.method, [], key_prefix) def _to_tuple(s): t = s.split("=", 1) if len(t) == 2: return t[0].lower(), t[1] return t[0].lower(), True
be9941174a70674c7fddb5f4f26b37b714592d05e6cf73c770d78e78be6a07bf
import datetime import decimal import functools import re import unicodedata from importlib import import_module from django.conf import settings from django.utils import dateformat, numberformat from django.utils.functional import lazy from django.utils.translation import check_for_language, get_language, to_locale # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { "DATE_INPUT_FORMATS": ["%Y-%m-%d"], "TIME_INPUT_FORMATS": ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"], "DATETIME_INPUT_FORMATS": [ "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%Y-%m-%d", ], } FORMAT_SETTINGS = frozenset( [ "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "FIRST_DAY_OF_WEEK", "MONTH_DAY_FORMAT", "TIME_FORMAT", "DATE_FORMAT", "DATETIME_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "YEAR_MONTH_FORMAT", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ] ) def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang, format_module_path=None): """Find format modules.""" if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, str): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + ".%s") format_locations.append("django.conf.locale.%s") locale = to_locale(lang) locales = [locale] if "_" in locale: locales.append(locale.split("_")[0]) for location in format_locations: for loc in locales: try: yield import_module("%s.formats" % (location % loc)) except ImportError: pass def get_format_modules(lang=None): """Return a list of the format modules found.""" if lang is None: lang = get_language() if lang not in _format_modules_cache: _format_modules_cache[lang] = list( iter_format_modules(lang, settings.FORMAT_MODULE_PATH) ) return _format_modules_cache[lang] def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, return the format for the current language (locale). Default to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT'. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n is None: try: use_l10n = settings._USE_L10N_INTERNAL except AttributeError: use_l10n = settings.USE_L10N if use_l10n and lang is None: lang = get_language() cache_key = (format_type, lang) try: return _format_cache[cache_key] except KeyError: pass # The requested format_type has not been cached yet. Try to find it in any # of the format_modules for the given lang if l10n is enabled. If it's not # there or if l10n is disabled, fall back to the project settings. val = None if use_l10n: for module in get_format_modules(lang): val = getattr(module, format_type, None) if val is not None: break if val is None: if format_type not in FORMAT_SETTINGS: return format_type val = getattr(settings, format_type) elif format_type in ISO_INPUT_FORMATS: # If a list of input formats from one of the format_modules was # retrieved, make sure the ISO_INPUT_FORMATS are in this list. val = list(val) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: val.append(iso_input) _format_cache[cache_key] = val return val get_format_lazy = lazy(get_format, str, list, tuple) def date_format(value, format=None, use_l10n=None): """ Format a datetime.date or datetime.datetime object using a localizable format. If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.format( value, get_format(format or "DATE_FORMAT", use_l10n=use_l10n) ) def time_format(value, format=None, use_l10n=None): """ Format a datetime.time object using a localizable format. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format( value, get_format(format or "TIME_FORMAT", use_l10n=use_l10n) ) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Format a numeric value using localization settings. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n is None: try: use_l10n = settings._USE_L10N_INTERNAL except AttributeError: use_l10n = settings.USE_L10N lang = get_language() if use_l10n else None return numberformat.format( value, get_format("DECIMAL_SEPARATOR", lang, use_l10n=use_l10n), decimal_pos, get_format("NUMBER_GROUPING", lang, use_l10n=use_l10n), get_format("THOUSAND_SEPARATOR", lang, use_l10n=use_l10n), force_grouping=force_grouping, use_l10n=use_l10n, ) def localize(value, use_l10n=None): """ Check if value is a localizable type (date, number...) and return it formatted as a string using current locale format. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Make sure booleans don't get treated as numbers return str(value) elif isinstance(value, (decimal.Decimal, float, int)): if use_l10n is False: return str(value) return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, "DATETIME_FORMAT", use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, "TIME_FORMAT", use_l10n=use_l10n) return value def localize_input(value, default=None): """ Check if an input value is a localizable type and return it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return str(value) elif isinstance(value, (decimal.Decimal, float, int)): return number_format(value) elif isinstance(value, datetime.datetime): format = default or get_format("DATETIME_INPUT_FORMATS")[0] format = sanitize_strftime_format(format) return value.strftime(format) elif isinstance(value, datetime.date): format = default or get_format("DATE_INPUT_FORMATS")[0] format = sanitize_strftime_format(format) return value.strftime(format) elif isinstance(value, datetime.time): format = default or get_format("TIME_INPUT_FORMATS")[0] return value.strftime(format) return value @functools.lru_cache def sanitize_strftime_format(fmt): """ Ensure that certain specifiers are correctly padded with leading zeros. For years < 1000 specifiers %C, %F, %G, and %Y don't work as expected for strftime provided by glibc on Linux as they don't pad the year or century with leading zeros. Support for specifying the padding explicitly is available, however, which can be used to fix this issue. FreeBSD, macOS, and Windows do not support explicitly specifying the padding, but return four digit years (with leading zeros) as expected. This function checks whether the %Y produces a correctly padded string and, if not, makes the following substitutions: - %C → %02C - %F → %010F - %G → %04G - %Y → %04Y See https://bugs.python.org/issue13305 for more details. """ if datetime.date(1, 1, 1).strftime("%Y") == "0001": return fmt mapping = {"C": 2, "F": 10, "G": 4, "Y": 4} return re.sub( r"((?:^|[^%])(?:%%)*)%([CFGY])", lambda m: r"%s%%0%s%s" % (m[1], mapping[m[2]], m[2]), fmt, ) def sanitize_separators(value): """ Sanitize a value according to the current decimal and thousand separator setting. Used with form field input. """ if isinstance(value, str): parts = [] decimal_separator = get_format("DECIMAL_SEPARATOR") if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format("THOUSAND_SEPARATOR") if ( thousand_sep == "." and value.count(".") == 1 and len(value.split(".")[-1]) != 3 ): # Special case where we suspect a dot meant decimal separator # (see #22171). pass else: for replacement in { thousand_sep, unicodedata.normalize("NFKD", thousand_sep), }: value = value.replace(replacement, "") parts.append(value) value = ".".join(reversed(parts)) return value
7216bcc454f9710d0e32128cb1db08ab54c70e776629435834d89e43c04d6bd1
"""JsLex: a lexer for JavaScript""" # Originally from https://bitbucket.org/ned/jslex import re class Tok: """ A specification for a token class. """ num = 0 def __init__(self, name, regex, next=None): self.id = Tok.num Tok.num += 1 self.name = name self.regex = regex self.next = next def literals(choices, prefix="", suffix=""): """ Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix + re.escape(c) + suffix for c in choices.split()) class Lexer: """ A generic multi-state regex-based lexer. """ def __init__(self, states, first): self.regexes = {} self.toks = {} for state, rules in states.items(): parts = [] for tok in rules: groupid = "t%d" % tok.id self.toks[groupid] = tok parts.append("(?P<%s>%s)" % (groupid, tok.regex)) self.regexes[state] = re.compile("|".join(parts), re.MULTILINE | re.VERBOSE) self.state = first def lex(self, text): """ Lexically analyze `text`. Yield pairs (`name`, `tokentext`). """ end = len(text) state = self.state regexes = self.regexes toks = self.toks start = 0 while start < end: for match in regexes[state].finditer(text, start): name = match.lastgroup tok = toks[name] toktext = match[name] start += len(toktext) yield (tok.name, toktext) if tok.next: state = tok.next break self.state = state class JsLexer(Lexer): """ A JavaScript lexer >>> lexer = JsLexer() >>> list(lexer.lex("a = 1")) [('id', 'a'), ('ws', ' '), ('punct', '='), ('ws', ' '), ('dnum', '1')] This doesn't properly handle non-ASCII characters in the JavaScript source. """ # Because these tokens are matched as alternatives in a regex, longer # possibilities must appear in the list before shorter ones, for example, # '>>' before '>'. # # Note that we don't have to detect malformed JavaScript, only properly # lex correct JavaScript, so much of this is simplified. # Details of JavaScript lexical structure are taken from # https://www.ecma-international.org/publications-and-standards/standards/ecma-262/ # A useful explanation of automatic semicolon insertion is at # http://inimino.org/~inimino/blog/javascript_semicolons both_before = [ Tok("comment", r"/\*(.|\n)*?\*/"), Tok("linecomment", r"//.*?$"), Tok("ws", r"\s+"), Tok( "keyword", literals( """ break case catch class const continue debugger default delete do else enum export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with """, suffix=r"\b", ), next="reg", ), Tok("reserved", literals("null true false", suffix=r"\b"), next="div"), Tok( "id", r""" ([a-zA-Z_$ ]|\\u[0-9a-fA-Z]{4}) # first char ([a-zA-Z_$0-9]|\\u[0-9a-fA-F]{4})* # rest chars """, next="div", ), Tok("hnum", r"0[xX][0-9a-fA-F]+", next="div"), Tok("onum", r"0[0-7]+"), Tok( "dnum", r""" ( (0|[1-9][0-9]*) # DecimalIntegerLiteral \. # dot [0-9]* # DecimalDigits-opt ([eE][-+]?[0-9]+)? # ExponentPart-opt | \. # dot [0-9]+ # DecimalDigits ([eE][-+]?[0-9]+)? # ExponentPart-opt | (0|[1-9][0-9]*) # DecimalIntegerLiteral ([eE][-+]?[0-9]+)? # ExponentPart-opt ) """, next="div", ), Tok( "punct", literals( """ >>>= === !== >>> <<= >>= <= >= == != << >> && || += -= *= %= &= |= ^= """ ), next="reg", ), Tok("punct", literals("++ -- ) ]"), next="div"), Tok("punct", literals("{ } ( [ . ; , < > + - * % & | ^ ! ~ ? : ="), next="reg"), Tok("string", r'"([^"\\]|(\\(.|\n)))*?"', next="div"), Tok("string", r"'([^'\\]|(\\(.|\n)))*?'", next="div"), ] both_after = [ Tok("other", r"."), ] states = { # slash will mean division "div": both_before + [ Tok("punct", literals("/= /"), next="reg"), ] + both_after, # slash will mean regex "reg": both_before + [ Tok( "regex", r""" / # opening slash # First character is.. ( [^*\\/[] # anything but * \ / or [ | \\. # or an escape sequence | \[ # or a class, which has ( [^\]\\] # anything but \ or ] | \\. # or an escape sequence )* # many times \] ) # Following characters are same, except for excluding a star ( [^\\/[] # anything but \ / or [ | \\. # or an escape sequence | \[ # or a class, which has ( [^\]\\] # anything but \ or ] | \\. # or an escape sequence )* # many times \] )* # many times / # closing slash [a-zA-Z0-9]* # trailing flags """, next="div", ), ] + both_after, } def __init__(self): super().__init__(self.states, "reg") def prepare_js_for_gettext(js): """ Convert the JavaScript source `js` into something resembling C for xgettext. What actually happens is that all the regex literals are replaced with "REGEX". """ def escape_quotes(m): """Used in a regex to properly escape double quotes.""" s = m[0] if s == '"': return r"\"" else: return s lexer = JsLexer() c = [] for name, tok in lexer.lex(js): if name == "regex": # C doesn't grok regexes, and they aren't needed for gettext, # so just output a string instead. tok = '"REGEX"' elif name == "string": # C doesn't have single-quoted strings, so make all strings # double-quoted. if tok.startswith("'"): guts = re.sub(r"\\.|.", escape_quotes, tok[1:-1]) tok = '"' + guts + '"' elif name == "id": # C can't deal with Unicode escapes in identifiers. We don't # need them for gettext anyway, so replace them with something # innocuous tok = tok.replace("\\", "U") c.append(tok) return "".join(c)