sort out all test folders into passable and TODOs

This commit is contained in:
Maxim Kurnikov
2019-01-30 22:43:09 +03:00
parent b1153204d7
commit c9e8fe53a5
20 changed files with 819 additions and 49 deletions

View File

@@ -1,6 +1,7 @@
from typing import Any
from django.utils.version import get_version as get_version
from .utils.version import get_version as get_version
VERSION: Any
__version__: str
def setup(set_prefix: bool = ...) -> None: ...

View File

@@ -2,6 +2,8 @@ from typing import Any
from django.utils.functional import LazyObject
ENVIRONMENT_VARIABLE: str = ...
# required for plugin to be able to distinguish this specific instance of LazySettings from others
class _DjangoConfLazyObject(LazyObject): ...
@@ -11,5 +13,8 @@ class LazySettings(_DjangoConfLazyObject):
settings: LazySettings = ...
class Settings: ...
class Settings:
def __init__(self, settings_module: str): ...
def is_overridden(self, setting: str) -> bool: ...
class UserSettingsHolder: ...

View File

@@ -0,0 +1,630 @@
"""
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@example.com'), ('Full Name', 'anotheremail@example.com')]
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
# 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")),
("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")),
("ia", gettext_noop("Interlingua")),
("id", gettext_noop("Indonesian")),
("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")),
("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")),
("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")),
("th", gettext_noop("Thai")),
("tr", gettext_noop("Turkish")),
("tt", gettext_noop("Tatar")),
("udm", gettext_noop("Udmurt")),
("uk", gettext_noop("Ukrainian")),
("ur", gettext_noop("Urdu")),
("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", "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 = "/"
# If you set this to True, Django will format dates, numbers and calendars
# according to user current locale.
USE_L10N = False
# Not-necessarily-technical managers of the site. They get broken link
# notifications and other various emails.
MANAGERS = ADMINS
# Default content type and charset to use for all HttpResponse objects, if a
# MIME type isn't manually specified. These are used to construct the
# Content-Type header.
DEFAULT_CONTENT_TYPE = "text/html"
DEFAULT_CHARSET = "utf-8"
# Encoding of files read from disk (template and initial SQL files).
FILE_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 = ""
# 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 = None
# 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",
"%m/%d/%Y",
"%m/%d/%y", # '2006-10-25', '10/25/2006', '10/25/06'
"%b %d %Y",
"%b %d, %Y", # 'Oct 25 2006', 'Oct 25, 2006'
"%d %b %Y",
"%d %b, %Y", # '25 Oct 2006', '25 Oct, 2006'
"%B %d %Y",
"%B %d, %Y", # 'October 25 2006', 'October 25, 2006'
"%d %B %Y",
"%d %B, %Y", # '25 October 2006', '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", "%H:%M:%S.%f", "%H:%M"] # '14:30:59' # '14:30:59.000200' # '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'
"%Y-%m-%d", # '2006-10-25'
"%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", # '10/25/2006'
"%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", # '10/25/06'
]
# 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 X-Frame-Options header value
X_FRAME_OPTIONS = "SAMEORIGIN"
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 non-RFC standard httpOnly flag (IE, FF3+, others)
SESSION_COOKIE_HTTPONLY = True
# Whether to set the flag restricting cookie leaks on cross-site requests.
# This can be 'Lax', 'Strict', or None 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 days a password reset link is valid for
PASSWORD_RESET_TIMEOUT_DAYS = 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",
]
AUTH_PASSWORD_VALIDATORS = []
###########
# SIGNING #
###########
SIGNING_BACKEND = "django.core.signing.TimestampSigner"
########
# CSRF #
########
# Dotted path to callable to be used as view when a request is
# rejected by the CSRF middleware.
CSRF_FAILURE_VIEW = "django.views.csrf.csrf_failure"
# Settings for CSRF cookie.
CSRF_COOKIE_NAME = "csrftoken"
CSRF_COOKIE_AGE = 60 * 60 * 24 * 7 * 52
CSRF_COOKIE_DOMAIN = None
CSRF_COOKIE_PATH = "/"
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = "Lax"
CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN"
CSRF_TRUSTED_ORIGINS = []
CSRF_USE_SESSIONS = False
############
# MESSAGES #
############
# Class to use as messages backend
MESSAGE_STORAGE = "django.contrib.messages.storage.fallback.FallbackStorage"
# Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within
# django.contrib.messages to avoid imports in this settings file.
###########
# LOGGING #
###########
# The callable to use to configure logging
LOGGING_CONFIG = "logging.config.dictConfig"
# Custom logging configuration.
LOGGING = {}
# Default exception reporter 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_BROWSER_XSS_FILTER = False
SECURE_CONTENT_TYPE_NOSNIFF = False
SECURE_HSTS_INCLUDE_SUBDOMAINS = False
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_REDIRECT_EXEMPT = []
SECURE_SSL_HOST = None
SECURE_SSL_REDIRECT = False

View File

@@ -41,10 +41,10 @@ class SessionBase:
def get_expire_at_browser_close(self) -> bool: ...
def flush(self) -> None: ...
def cycle_key(self) -> None: ...
def exists(self, session_key: Any) -> None: ...
def exists(self, session_key: str) -> None: ...
def create(self) -> None: ...
def save(self, must_create: bool = ...) -> None: ...
def delete(self, session_key: Optional[Any] = ...) -> None: ...
def load(self) -> None: ...
def load(self) -> Dict[str, Any]: ...
@classmethod
def clear_expired(cls) -> None: ...

View File

@@ -2,11 +2,10 @@ from typing import Type
from django.contrib.sessions.backends.base import SessionBase
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from django.http.response import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class SessionMiddleware(MiddlewareMixin):
SessionStore: Type[SessionBase] = ...
def process_request(self, request: HttpRequest) -> None: ...
def process_request(self, request: WSGIRequest) -> None: ...
def process_response(self, request: WSGIRequest, response: HttpResponse) -> HttpResponse: ...

View File

@@ -21,7 +21,7 @@ class BaseCache:
def get_backend_timeout(self, timeout: Any = ...) -> Optional[float]: ...
def make_key(self, key: Union[int, str], version: Optional[Union[int, str]] = ...) -> str: ...
def add(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> None: ...
def get(self, key: Any, default: Optional[Any] = ..., version: Optional[Any] = ...) -> None: ...
def get(self, key: Any, default: Optional[Any] = ..., version: Optional[Any] = ...) -> Any: ...
def set(self, key: Any, value: Any, timeout: Any = ..., version: Optional[Any] = ...) -> None: ...
def touch(self, key: Any, timeout: Any = ..., version: Optional[Any] = ...) -> None: ...
def delete(self, key: Any, version: Optional[Any] = ...) -> None: ...

View File

@@ -1,4 +1,4 @@
from typing import Dict, List, Optional, Union, Iterable, Sequence
from typing import Dict, List, Optional, Union, Iterable, Sequence, Protocol, Any
from django.db.models.base import Model
from django.db.models.query import QuerySet
@@ -8,13 +8,23 @@ class InvalidPage(Exception): ...
class PageNotAnInteger(InvalidPage): ...
class EmptyPage(InvalidPage): ...
class SupportsLen(Protocol):
def __len__(self) -> int: ...
class SupportsCount(Protocol):
def count(self) -> int: ...
class Paginator:
object_list: QuerySet = ...
per_page: int = ...
orphans: int = ...
allow_empty_first_page: bool = ...
def __init__(
self, object_list: Iterable, per_page: Union[int, str], orphans: int = ..., allow_empty_first_page: bool = ...
self,
object_list: Union[SupportsLen, SupportsCount],
per_page: Union[int, str],
orphans: int = ...,
allow_empty_first_page: bool = ...,
) -> None: ...
def validate_number(self, number: Optional[Union[float, str]]) -> int: ...
def get_page(self, number: Optional[int]) -> Page: ...

View File

@@ -2,10 +2,18 @@ from collections import OrderedDict
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, Union
from django.apps.config import AppConfig
from django.core.serializers.base import Serializer, Deserializer
from django.db.models.base import Model
from django.db.models.query import QuerySet
from .base import (
Serializer as Serializer,
Deserializer as Deserializer,
SerializerDoesNotExist as SerializerDoesNotExist,
SerializationError as SerializationError,
DeserializationError as DeserializationError,
M2MDeserializationError as M2MDeserializationError,
)
BUILTIN_SERIALIZERS: Any
class BadSerializer:

View File

@@ -28,6 +28,7 @@ from .fields import (
FilePathField as FilePathField,
BinaryField as BinaryField,
DurationField as DurationField,
BigAutoField as BigAutoField,
)
from .fields.related import (

View File

@@ -1,12 +1,15 @@
from typing import Any, List, Optional, Set, Tuple, Dict
from typing import Any, Dict, List, Optional, Set, Tuple, TypeVar, Union
from django.db.models.manager import Manager
class ModelBase(type): ...
_Self = TypeVar("_Self", bound="Model")
class Model(metaclass=ModelBase):
class DoesNotExist(Exception):
pass
_meta: Any
pk: Any = ...
objects: Manager[Model]
def __init__(self, *args, **kwargs) -> None: ...
@@ -19,9 +22,9 @@ class Model(metaclass=ModelBase):
force_insert: bool = ...,
force_update: bool = ...,
using: Optional[str] = ...,
update_fields: Optional[List[str]] = ...,
update_fields: Optional[Union[List[str], str]] = ...,
) -> None: ...
def refresh_from_db(self, using: None = ..., fields: Optional[List[str]] = ...) -> None: ...
def refresh_from_db(self: _Self, using: Optional[str] = ..., fields: Optional[List[str]] = ...) -> _Self: ...
def get_deferred_fields(self) -> Set[str]: ...
class ModelStateFieldsCacheDescriptor: ...

View File

@@ -16,6 +16,8 @@ class Field(RegisterLookupMixin):
help_text: str
db_table: str
remote_field: Field
model: Type[Model]
name: str
def __init__(
self,
verbose_name: Optional[str] = ...,
@@ -30,6 +32,9 @@ class Field(RegisterLookupMixin):
editable: bool = ...,
auto_created: bool = ...,
serialize: bool = ...,
unique_for_date: Optional[str] = ...,
unique_for_month: Optional[str] = ...,
unique_for_year: Optional[str] = ...,
choices: Optional[_FieldChoices] = ...,
help_text: str = ...,
db_column: Optional[str] = ...,
@@ -194,6 +199,7 @@ class DateField(DateTimeCheckMixin, Field):
auto_now: bool = ...,
auto_now_add: bool = ...,
primary_key: bool = ...,
max_length: Optional[int] = ...,
unique: bool = ...,
blank: bool = ...,
null: bool = ...,
@@ -267,3 +273,4 @@ class FilePathField(Field):
class BinaryField(Field): ...
class DurationField(Field): ...
class BigAutoField(AutoField): ...

View File

@@ -23,8 +23,13 @@ from django.db.models.fields.related_descriptors import (
ReverseOneToOneDescriptor as ReverseOneToOneDescriptor,
ForwardManyToOneDescriptor as ForwardManyToOneDescriptor,
ForwardOneToOneDescriptor as ForwardOneToOneDescriptor,
ManyToManyDescriptor as ManyToManyDescriptor,
)
from django.db.models.fields.reverse_related import (
ForeignObjectRel as ForeignObjectRel,
ManyToManyRel as ManyToManyRel,
ManyToOneRel as ManyToOneRel,
)
from django.db.models.fields.reverse_related import ForeignObjectRel as ForeignObjectRel
from django.db.models.query_utils import PathInfo, Q
if TYPE_CHECKING:
@@ -39,6 +44,8 @@ _FieldChoices = Iterable[Union[_Choice, _ChoiceNamedGroup]]
_ValidatorCallable = Callable[..., None]
_ErrorMessagesToOverride = Dict[str, Any]
RECURSIVE_RELATIONSHIP_CONSTANT: str = ...
class RelatedField(FieldCacheMixin, Field):
one_to_many: bool = ...
one_to_one: bool = ...
@@ -141,3 +148,5 @@ class ManyToManyField(RelatedField, Generic[_T]):
def set_attributes_from_rel(self) -> None: ...
def value_from_object(self, obj: Model) -> List[Model]: ...
def save_form_data(self, instance: Model, data: QuerySet) -> None: ...
def create_many_to_many_intermediary_model(field: Type[Field], klass: Type[Model]) -> Type[Model]: ...

View File

@@ -25,6 +25,7 @@ from django.db.models import Manager
_T = TypeVar("_T", bound=models.Model, covariant=True)
class QuerySet(Iterable[_T], Sized):
query: Query
def __init__(
self,
model: Optional[Type[models.Model]] = ...,
@@ -39,6 +40,7 @@ class QuerySet(Iterable[_T], Sized):
def __bool__(self) -> bool: ...
def __class_getitem__(cls, item: Type[_T]):
pass
def __getstate__(self) -> Dict[str, Any]: ...
@overload
def __getitem__(self, k: int) -> _T: ...
@overload
@@ -110,9 +112,10 @@ class QuerySet(Iterable[_T], Sized):
def __getattr__(self, item: str) -> Any: ...
class RawQuerySet(Iterable[_T], Sized):
query: RawQuery
def __init__(
self,
raw_query: RawQuery,
raw_query: Union[RawQuery, str],
model: Optional[Type[models.Model]] = ...,
query: Optional[Query] = ...,
params: Tuple[Any] = ...,

View File

@@ -15,13 +15,14 @@ from django.db.models.sql.where import WhereNode
JoinInfo = namedtuple("JoinInfo", ["final_field", "targets", "opts", "joins", "path", "transform_function"])
class RawQuery:
high_mark: None
low_mark: int
high_mark: Optional[int]
low_mark: Optional[int]
params: Union[Any] = ...
sql: str = ...
using: str = ...
extra_select: Dict[Any, Any] = ...
annotation_select: Dict[Any, Any] = ...
cursor: object = ...
def __init__(self, sql: str, using: str, params: Any = ...) -> None: ...
def chain(self, using: str) -> RawQuery: ...
def clone(self, using: str) -> RawQuery: ...

View File

@@ -1,9 +1,7 @@
# Stubs for django.http.response (Python 3.5)
import datetime
from io import BytesIO
from json import JSONEncoder
from typing import Any, Dict, Iterable, Iterator, List, Optional, overload, Tuple, Type, Union
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple, Type, Union, overload
import six
from django.core.handlers.wsgi import WSGIRequest
@@ -16,13 +14,17 @@ from django.urls import ResolverMatch
class BadHeaderError(ValueError): ...
class HttpResponseBase(six.Iterator):
status_code = ... # type: int
cookies = ... # type: SimpleCookie
closed = ... # type: bool
reason_phrase = ... # type: str
charset = ... # type: str
status_code: int = ...
cookies: SimpleCookie = ...
closed: bool = ...
reason_phrase: str = ...
charset: str = ...
def __init__(
self, content_type: str = None, status: int = None, reason: str = None, charset: str = None
self,
content_type: Optional[str] = ...,
status: Optional[int] = ...,
reason: Optional[str] = ...,
charset: Optional[str] = ...,
) -> None: ...
def serialize_headers(self) -> bytes: ...
def __setitem__(self, header: str, value: Union[str, bytes]) -> None: ...
@@ -37,13 +39,14 @@ class HttpResponseBase(six.Iterator):
def set_cookie(
self,
key: str,
value: str = "",
max_age: int = None,
expires: Union[str, datetime.datetime] = None,
path: str = "",
domain: str = None,
secure: bool = False,
httponly: bool = False,
value: str = ...,
max_age: Optional[int] = ...,
expires: Optional[Union[str, datetime.datetime]] = ...,
path: str = ...,
domain: Optional[str] = ...,
secure: bool = ...,
httponly: bool = ...,
samesite: str = ...,
) -> None: ...
def setdefault(self, key: str, value: str) -> None: ...
def set_signed_cookie(self, key: str, value: str, salt: str = "", **kwargs: Any) -> None: ...
@@ -143,9 +146,9 @@ class Http404(Exception): ...
class JsonResponse(HttpResponse):
def __init__(
self,
data: object,
data: Any,
encoder: Type[JSONEncoder] = ...,
safe: bool = True,
json_dumps_params: Dict[str, Any] = None,
safe: bool = ...,
json_dumps_params: Optional[Dict[str, Any]] = ...,
**kwargs: Any
) -> None: ...

View File

@@ -14,6 +14,7 @@ from .utils import (
override_script_prefix as override_script_prefix,
override_system_checks as override_system_checks,
ignore_warnings as ignore_warnings,
tag as tag,
)
from .client import Client as Client, RequestFactory as RequestFactory

View File

@@ -36,12 +36,12 @@ class RequestFactory:
errors: BytesIO = ...
def __init__(self, *, json_encoder: Any = ..., **defaults: Any) -> None: ...
def request(self, **request: Any) -> WSGIRequest: ...
def get(self, path: str, data: Any = ..., secure: bool = ..., **extra: Any) -> HttpResponseBase: ...
def get(self, path: str, data: Any = ..., secure: bool = ..., **extra: Any) -> WSGIRequest: ...
def post(
self, path: str, data: Any = ..., content_type: str = ..., secure: bool = ..., **extra: Any
) -> HttpResponseBase: ...
def head(self, path: str, data: Any = ..., secure: bool = ..., **extra: Any) -> HttpResponseBase: ...
def trace(self, path: str, secure: bool = ..., **extra: Any) -> HttpResponseBase: ...
) -> WSGIRequest: ...
def head(self, path: str, data: Any = ..., secure: bool = ..., **extra: Any) -> WSGIRequest: ...
def trace(self, path: str, secure: bool = ..., **extra: Any) -> WSGIRequest: ...
def options(
self,
path: str,
@@ -49,16 +49,16 @@ class RequestFactory:
content_type: str = ...,
secure: bool = ...,
**extra: Any
) -> HttpResponseBase: ...
) -> WSGIRequest: ...
def put(
self, path: str, data: Any = ..., content_type: str = ..., secure: bool = ..., **extra: Any
) -> HttpResponseBase: ...
) -> WSGIRequest: ...
def patch(
self, path: str, data: Any = ..., content_type: str = ..., secure: bool = ..., **extra: Any
) -> HttpResponseBase: ...
) -> WSGIRequest: ...
def delete(
self, path: str, data: Any = ..., content_type: str = ..., secure: bool = ..., **extra: Any
) -> HttpResponseBase: ...
) -> WSGIRequest: ...
def generic(
self,
method: str,
@@ -67,7 +67,7 @@ class RequestFactory:
content_type: Optional[str] = ...,
secure: bool = ...,
**extra: Any
) -> HttpResponseBase: ...
) -> WSGIRequest: ...
class Client(RequestFactory):
defaults: Dict[str, str]

View File

@@ -39,7 +39,7 @@ class TestContextDecorator:
def __exit__(self, exc_type: None, exc_value: None, traceback: None) -> None: ...
def decorate_class(self, cls: _TestClass) -> _TestClass: ...
def decorate_callable(self, func: Callable) -> Callable: ...
def __call__(self, decorated: _DecoratedTest) -> _DecoratedTest: ...
def __call__(self, decorated: _DecoratedTest) -> Any: ...
class override_settings(TestContextDecorator):
options: Dict[str, Any] = ...
@@ -109,6 +109,11 @@ def extend_sys_path(*paths: str) -> Iterator[None]: ...
@contextmanager
def captured_output(stream_name) -> Iterator[IO[str]]: ...
@contextmanager
def captured_stdin() -> Iterator[IO[str]]: ...
@contextmanager
def captured_stdout() -> Iterator[IO[str]]: ...
@contextmanager
def captured_stderr() -> Iterator[IO[str]]: ...
@contextmanager
def freeze_time(t: float) -> Iterator[None]: ...
def tag(*tags: str): ...

View File

@@ -1,10 +1,14 @@
from typing import Any, Dict, Optional, Tuple
from typing import Any, Dict, Iterable, Optional, Tuple
from django.db.models.sql.where import NothingNode
class Node:
default: str = ...
connector: str = ...
negated: bool = ...
def __init__(self, children: Optional[Node] = ..., connector: Optional[str] = ..., negated: bool = ...) -> None: ...
def __init__(
self, children: Optional[Iterable[Node, NothingNode]] = ..., connector: Optional[str] = ..., negated: bool = ...
) -> None: ...
def __deepcopy__(self, memodict: Dict[Any, Any]) -> Node: ...
def __len__(self) -> int: ...
def __bool__(self) -> bool: ...

View File

@@ -47,7 +47,15 @@ IGNORED_ERROR_PATTERNS = [
'has no attribute "vendor"',
'Argument 1 to "get_list_or_404" has incompatible type "List',
'error: "AdminRadioSelect" has no attribute "can_add_related"',
re.compile('Cannot determine type of \'(objects|stuff|specimens)\''),
'MockCompiler',
'SessionTestsMixin',
'Argument 1 to "Paginator" has incompatible type "ObjectList"',
'"Type[Morsel[Any]]" has no attribute "_reserved"',
'Argument 1 to "append" of "list"',
'Argument 1 to "bytes"',
'"full_clean" of "Model" does not return a value',
'"object" not callable',
re.compile('Cannot determine type of \'(objects|stuff|specimens|normal_manager)\''),
re.compile(r'"Callable\[\[(Any(, )?)+\], Any\]" has no attribute'),
re.compile(r'"HttpResponseBase" has no attribute "[A-Za-z_]+"'),
re.compile(r'Incompatible types in assignment \(expression has type "Tuple\[\]", '
@@ -62,6 +70,7 @@ IGNORED_ERROR_PATTERNS = [
# TODO: remove when form <-> model plugin support is added
re.compile(r'"Model" has no attribute "[A-Za-z_]+"'),
re.compile(r'Argument 1 to "get_object_or_404" has incompatible type "(str|Type\[CustomClass\])"'),
re.compile(r'"None" has no attribute "[a-zA-Z_0-9]+"'),
]
# Test folders to typecheck
@@ -198,6 +207,77 @@ TESTS_DIRS = [
# TODO: 'multiple_database',
'mutually_referential',
'nested_foreign_keys',
'no_models',
'null_fk',
'null_fk_ordering',
'null_queries',
'one_to_one',
'or_lookups',
'order_with_respect_to',
'ordering',
'pagination',
# TODO: 'postgres_tests',
# TODO: 'prefetch_related',
'project_template',
'properties',
'proxy_model_inheritance',
# TODO: 'proxy_models',
# TODO: 'queries',
'queryset_pickle',
'raw_query',
'redirects_tests',
# TODO: 'requests',
'reserved_names',
'resolve_url',
# TODO: 'responses',
'reverse_lookup',
'save_delete_hooks',
'schema',
# TODO: 'select_for_update',
'select_related',
'select_related_onetoone',
'select_related_regress',
# TODO: 'serializers',
# TODO: 'servers',
'sessions_tests',
'settings_tests'
'shell',
# TODO: 'shortcuts',
# TODO: 'signals',
'signed_cookies_tests',
# TODO: 'signing',
# TODO: 'sitemaps_tests',
'sites_framework',
# TODO: 'sites_tests',
# TODO: 'staticfiles_tests',
'str',
'string_lookup',
'swappable_models',
# TODO: 'syndication_tests',
# TODO: 'template_backends',
'template_loader',
# TODO: 'template_tests',
# TODO: 'test_client',
# TODO: 'test_client_regress',
'test_exceptions',
# TODO: 'test_runner',
'test_runner_apps',
# TODO: 'test_utils',
# TODO: 'timezones',
'transaction_hooks',
# TODO: 'transactions',
'unmanaged_models',
# TODO: 'update',
'update_only_fields',
'urlpatterns',
# TODO: 'urlpatterns_reverse',
'user_commands',
# TODO: 'utils_tests',
# TODO: 'validation',
'validators',
'version',
# TODO: 'view_tests',
# TODO: 'wsgi',
]