diff options
| author | Anton Samarchyan <anton.samarchyan@savoirfairelinux.com> | 2017-01-24 15:37:33 -0500 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2017-03-04 10:02:06 -0500 |
| commit | 86de930f413e0ad902e11d78ac988e6743202ea6 (patch) | |
| tree | 790dcc4c38125b619ffee76b5531155d0d8232f4 /django/test | |
| parent | 6ae1b04fb584db0fdb22b8e287784c4ed3ac62ac (diff) | |
Refs #27656 -- Updated remaining docstring verbs according to PEP 257.
Diffstat (limited to 'django/test')
| -rw-r--r-- | django/test/__init__.py | 4 | ||||
| -rw-r--r-- | django/test/client.py | 101 | ||||
| -rw-r--r-- | django/test/html.py | 6 | ||||
| -rw-r--r-- | django/test/runner.py | 26 | ||||
| -rw-r--r-- | django/test/selenium.py | 2 | ||||
| -rw-r--r-- | django/test/testcases.py | 159 | ||||
| -rw-r--r-- | django/test/utils.py | 44 |
7 files changed, 138 insertions, 204 deletions
diff --git a/django/test/__init__.py b/django/test/__init__.py index e3561f5ae7..4782d72184 100644 --- a/django/test/__init__.py +++ b/django/test/__init__.py @@ -1,6 +1,4 @@ -""" -Django Unit Test and Doctest framework. -""" +"""Django Unit Test framework.""" from django.test.client import Client, RequestFactory from django.test.testcases import ( diff --git a/django/test/client.py b/django/test/client.py index 87b59af363..947a1fb56f 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -36,9 +36,7 @@ JSON_CONTENT_TYPE_RE = re.compile(r'^application\/(vnd\..+\+)?json$') class RedirectCycleError(Exception): - """ - The test client has been asked to follow a redirect loop. - """ + """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 @@ -50,7 +48,7 @@ class FakePayload: A wrapper around BytesIO that restricts what can be read since data from the network can't be seeked 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. + that wouldn't work in real life. """ def __init__(self, content=None): self.__content = BytesIO() @@ -93,7 +91,7 @@ def closing_iterator_wrapper(iterable, close): 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. Ensures + 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): @@ -112,8 +110,8 @@ def conditional_content_removal(request, response): class ClientHandler(BaseHandler): """ - A HTTP Handler that can be used for testing purposes. Uses the WSGI - interface to compose requests, but returns the raw HttpResponse object with + A 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): @@ -146,8 +144,7 @@ class ClientHandler(BaseHandler): # later retrieved. response.wsgi_request = request - # We're emulating a WSGI server; we must call the close method - # on completion. + # 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) @@ -161,7 +158,7 @@ class ClientHandler(BaseHandler): def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ - Stores templates and contexts that are rendered. + Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. @@ -174,7 +171,7 @@ def store_rendered_templates(store, signal, sender, template, context, **kwargs) def encode_multipart(boundary, data): """ - Encodes multipart POST data from a dictionary of form values. + 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 @@ -326,8 +323,7 @@ class RequestFactory: return path.decode('iso-8859-1') def get(self, path, data=None, secure=False, **extra): - "Construct a GET request." - + """Construct a GET request.""" data = {} if data is None else data r = { 'QUERY_STRING': urlencode(data, doseq=True), @@ -337,8 +333,7 @@ class RequestFactory: def post(self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, **extra): - "Construct a POST request." - + """Construct a POST request.""" data = {} if data is None else data post_data = self._encode_data(data, content_type) @@ -346,8 +341,7 @@ class RequestFactory: secure=secure, **extra) def head(self, path, data=None, secure=False, **extra): - "Construct a HEAD request." - + """Construct a HEAD request.""" data = {} if data is None else data r = { 'QUERY_STRING': urlencode(data, doseq=True), @@ -356,7 +350,7 @@ class RequestFactory: return self.generic('HEAD', path, secure=secure, **r) def trace(self, path, secure=False, **extra): - "Construct a TRACE request." + """Construct a TRACE request.""" return self.generic('TRACE', path, secure=secure, **extra) def options(self, path, data='', content_type='application/octet-stream', @@ -367,26 +361,26 @@ class RequestFactory: def put(self, path, data='', content_type='application/octet-stream', secure=False, **extra): - "Construct a PUT request." + """Construct a PUT request.""" 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." + """Construct a PATCH request.""" 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." + """Construct a DELETE request.""" 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): - """Constructs an arbitrary HTTP request.""" + """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { @@ -434,16 +428,12 @@ class Client(RequestFactory): self.exc_info = None def store_exc_info(self, **kwargs): - """ - Stores exceptions when they are generated by a view. - """ + """Store exceptions when they are generated by a view.""" self.exc_info = sys.exc_info() @property def session(self): - """ - Obtains the current session variables. - """ + """Return the current session variables.""" engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: @@ -456,10 +446,10 @@ class Client(RequestFactory): def request(self, **request): """ - The master request method. Composes the environment dictionary - and passes to the handler, returning the result of the handler. - Assumes defaults for the query environment, which can be overridden - using the arguments to the 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) @@ -523,9 +513,7 @@ class Client(RequestFactory): got_request_exception.disconnect(dispatch_uid=exception_uid) def get(self, path, data=None, follow=False, secure=False, **extra): - """ - Requests a response from the server using GET. - """ + """Request a response from the server using GET.""" response = super().get(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) @@ -533,18 +521,14 @@ class Client(RequestFactory): def post(self, path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra): - """ - Requests a response from the server using POST. - """ + """Request a response from the server using POST.""" response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def head(self, path, data=None, follow=False, secure=False, **extra): - """ - Request a response from the server using HEAD. - """ + """Request a response from the server using HEAD.""" response = super().head(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) @@ -552,9 +536,7 @@ class Client(RequestFactory): def options(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): - """ - Request a response from the server using OPTIONS. - """ + """Request a response from the server using OPTIONS.""" response = super().options(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) @@ -562,9 +544,7 @@ class Client(RequestFactory): def put(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): - """ - Send a resource to the server using PUT. - """ + """Send a resource to the server using PUT.""" response = super().put(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) @@ -572,9 +552,7 @@ class Client(RequestFactory): def patch(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): - """ - Send a resource to the server using PATCH. - """ + """Send a resource to the server using PATCH.""" response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) @@ -582,18 +560,14 @@ class Client(RequestFactory): def delete(self, path, data='', content_type='application/octet-stream', follow=False, secure=False, **extra): - """ - Send a DELETE request to the server. - """ + """Send a DELETE request to the server.""" response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) return response def trace(self, path, data='', follow=False, secure=False, **extra): - """ - Send a TRACE request to the server. - """ + """Send a TRACE request to the server.""" response = super().trace(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, **extra) @@ -601,9 +575,9 @@ class Client(RequestFactory): def login(self, **credentials): """ - Sets the Factory to appear as if it has successfully logged into a site. + Set the Factory to appear as if it has successfully logged into a site. - Returns True if login is possible; False if the provided credentials + Return True if login is possible; False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate @@ -655,11 +629,7 @@ class Client(RequestFactory): self.cookies[session_cookie].update(cookie_data) def logout(self): - """ - Removes the authenticated user's cookies and session object. - - Causes the authenticated user to be logged out. - """ + """Log out the user by removing the cookies and session object.""" from django.contrib.auth import get_user, logout request = HttpRequest() @@ -683,8 +653,9 @@ class Client(RequestFactory): return response._json def _handle_redirects(self, response, **extra): - "Follows any redirects by requesting responses from the server using GET." - + """ + Follow any redirects by requesting responses from the server using GET. + """ response.redirect_chain = [] while response.status_code in (301, 302, 303, 307): response_url = response.url diff --git a/django/test/html.py b/django/test/html.py index 900aa3d3f0..726beb6e93 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -1,6 +1,4 @@ -""" -Comparing two html documents. -""" +"""Compare two HTML documents.""" import re @@ -214,7 +212,7 @@ class Parser(HTMLParser): def parse_html(html): """ - Takes a string that contains *valid* HTML and turns it into a Python object + Take a string that contains *valid* 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. diff --git a/django/test/runner.py b/django/test/runner.py index cb1893c56a..0255348854 100644 --- a/django/test/runner.py +++ b/django/test/runner.py @@ -253,9 +253,7 @@ class RemoteTestRunner: def default_test_processes(): - """ - Default number of test processes when using the --parallel option. - """ + """Default 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': @@ -389,9 +387,7 @@ class ParallelTestSuite(unittest.TestSuite): class DiscoverRunner: - """ - A Django test runner that uses unittest2 test discovery. - """ + """A Django test runner that uses unittest2 test discovery.""" test_suite = unittest.TestSuite parallel_test_suite = ParallelTestSuite @@ -566,9 +562,7 @@ class DiscoverRunner: return runner.run(suite) def teardown_databases(self, old_config, **kwargs): - """ - Destroys all the non-mirror databases. - """ + """Destroy all the non-mirror databases.""" _teardown_databases( old_config, verbosity=self.verbosity, @@ -593,7 +587,7 @@ class DiscoverRunner: A list of 'extra' tests may also be provided; these tests will be added to the test suite. - Returns the number of tests that failed. + Return the number of tests that failed. """ self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) @@ -623,15 +617,15 @@ def is_discoverable(label): def reorder_suite(suite, classes, reverse=False): """ - Reorders a test suite by test type. + Reorder a test suite by test type. `classes` is a sequence of types All tests of type classes[0] are placed first, then tests of type classes[1], etc. Tests with no match in classes are placed last. - If `reverse` is True, tests within classes are sorted in opposite order, - but test classes are not reversed. + If `reverse` is True, sort tests within classes in opposite order but + don't reverse test classes. """ class_count = len(classes) suite_class = type(suite) @@ -645,7 +639,7 @@ def reorder_suite(suite, classes, reverse=False): def partition_suite_by_type(suite, classes, bins, reverse=False): """ - Partitions a test suite by test type. Also prevents duplicated tests. + Partition a test suite by test type. Also prevent duplicated tests. classes is a sequence of types bins is a sequence of TestSuites, one more than classes @@ -670,9 +664,7 @@ def partition_suite_by_type(suite, classes, bins, reverse=False): def partition_suite_by_case(suite): - """ - Partitions a test suite by test case, preserving the order of tests. - """ + """Partition a test suite by test case, preserving the order of tests.""" groups = [] suite_class = type(suite) for test_type, test_group in itertools.groupby(suite, type): diff --git a/django/test/selenium.py b/django/test/selenium.py index 2b14678b23..9bf1e1038d 100644 --- a/django/test/selenium.py +++ b/django/test/selenium.py @@ -73,7 +73,7 @@ class SeleniumTestCase(LiveServerTestCase, metaclass=SeleniumTestCaseBase): @contextmanager def disable_implicit_wait(self): - """Context manager that disables the default implicit wait.""" + """Disable the default implicit wait.""" self.selenium.implicitly_wait(0) try: yield diff --git a/django/test/testcases.py b/django/test/testcases.py index b8d57378de..4be5baf4b8 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -43,8 +43,8 @@ __all__ = ('TestCase', 'TransactionTestCase', def to_list(value): """ - Puts value into a list if it's not already one. - Returns an empty list if value is None. + Put value into a list if it's not already one. Return an empty list if + value is None. """ if value is None: value = [] @@ -212,21 +212,22 @@ class SimpleTestCase(unittest.TestCase): return def _pre_setup(self): - """Performs any pre-test setup. This includes: - - * Creating a test client. - * Clearing the mail test outbox. + """ + Perform pre-test setup: + * Create a test client. + * Clear the mail test outbox. """ self.client = self.client_class() mail.outbox = [] def _post_teardown(self): - """Perform any post-test things.""" + """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. + A context manager that temporarily sets a setting and reverts to the + original value when exiting the context. """ return override_settings(**kwargs) @@ -240,12 +241,13 @@ class SimpleTestCase(unittest.TestCase): def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True): - """Asserts that a response redirected to a specific URL, and that the + """ + Assert that a response redirected to a specific URL and that the redirect URL can be loaded. - Note that assertRedirects won't work for external links since it uses - TestClient to do a request (use fetch_redirect_response=False to check - such links without fetching them). + Won't work for external links since it uses TestClient to do a request + (use fetch_redirect_response=False to check such links without fetching + them). """ if msg_prefix: msg_prefix += ": " @@ -349,8 +351,8 @@ class SimpleTestCase(unittest.TestCase): def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False): """ - Asserts that a response indicates that some content was retrieved - successfully, (i.e., the HTTP status code was as expected), and that + 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. @@ -368,8 +370,8 @@ class SimpleTestCase(unittest.TestCase): def assertNotContains(self, response, text, status_code=200, msg_prefix='', html=False): """ - Asserts that a response indicates that some content was retrieved - successfully, (i.e., the HTTP status code was as expected), and that + 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 occurs in the content of the response. """ text_repr, real_count, msg_prefix = self._assert_contains( @@ -379,7 +381,7 @@ class SimpleTestCase(unittest.TestCase): def assertFormError(self, response, form, field, errors, msg_prefix=''): """ - Asserts that a form used to render the response has a specific field + Assert that a form used to render the response has a specific field error. """ if msg_prefix: @@ -435,7 +437,7 @@ class SimpleTestCase(unittest.TestCase): def assertFormsetError(self, response, formset, form_index, field, errors, msg_prefix=''): """ - Asserts that a formset used to render the response has a specific error. + 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 @@ -538,7 +540,7 @@ class SimpleTestCase(unittest.TestCase): def assertTemplateUsed(self, response=None, template_name=None, msg_prefix='', count=None): """ - Asserts that the template with the provided name was used in rendering + 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._assert_template_used( @@ -567,7 +569,7 @@ class SimpleTestCase(unittest.TestCase): def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=''): """ - Asserts that the template with the provided name was NOT used in + 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._assert_template_used( @@ -590,7 +592,7 @@ class SimpleTestCase(unittest.TestCase): def assertRaisesMessage(self, expected_exception, expected_message, *args, **kwargs): """ - Asserts that expected_message is found in the the message of a raised + Assert that expected_message is found in the the message of a raised exception. Args: @@ -615,7 +617,7 @@ class SimpleTestCase(unittest.TestCase): def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=''): """ - Asserts that a form field behaves correctly with various inputs. + Assert that a form field behaves correctly with various inputs. Args: fieldclass: the class of the field to be tested. @@ -660,9 +662,9 @@ class SimpleTestCase(unittest.TestCase): def assertHTMLEqual(self, html1, html2, msg=None): """ - Asserts that two HTML snippets are semantically the same. + Assert that two HTML snippets are semantically the same. Whitespace in most cases is ignored, and attribute ordering is not - significant. The passed-in arguments must be valid HTML. + 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:') @@ -677,7 +679,7 @@ class SimpleTestCase(unittest.TestCase): self.fail(self._formatMessage(msg, standardMsg)) def assertHTMLNotEqual(self, html1, html2, msg=None): - """Asserts that two HTML snippets are not semantically equivalent.""" + """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:') @@ -700,7 +702,7 @@ class SimpleTestCase(unittest.TestCase): def assertJSONEqual(self, raw, expected_data, msg=None): """ - Asserts that the JSON fragments raw and expected_data are equal. + 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. """ @@ -717,7 +719,7 @@ class SimpleTestCase(unittest.TestCase): def assertJSONNotEqual(self, raw, expected_data, msg=None): """ - Asserts that the JSON fragments raw and expected_data are not equal. + 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. """ @@ -734,9 +736,9 @@ class SimpleTestCase(unittest.TestCase): def assertXMLEqual(self, xml1, xml2, msg=None): """ - Asserts that two XML snippets are semantically the same. - Whitespace in most cases is ignored, and attribute ordering is not - significant. The passed-in arguments must be valid XML. + 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) @@ -754,9 +756,9 @@ class SimpleTestCase(unittest.TestCase): def assertXMLNotEqual(self, xml1, xml2, msg=None): """ - Asserts that two XML snippets are not semantically equivalent. - Whitespace in most cases is ignored, and attribute ordering is not - significant. The passed-in arguments must be valid XML. + 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) @@ -795,12 +797,12 @@ class TransactionTestCase(SimpleTestCase): allow_database_queries = True def _pre_setup(self): - """Performs any pre-test setup. This includes: - - * If the class has an 'available_apps' attribute, restricting the app - registry to these applications, then firing post_migrate -- it must - run with the correct set of applications for the test case. - * If the class has a 'fixtures' attribute, installing these fixtures. + """ + 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: @@ -876,11 +878,11 @@ class TransactionTestCase(SimpleTestCase): return True def _post_teardown(self): - """Performs any post-test things. This includes: - - * Flushing the contents of the database, to leave a clean slate. If - the class has an 'available_apps' attribute, post_migrate isn't fired. - * Force-closing the connection, so the next test gets a clean cursor. + """ + 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() @@ -944,16 +946,13 @@ class TransactionTestCase(SimpleTestCase): def connections_support_transactions(): - """ - Returns True if all connections support transactions. - """ - return all(conn.features.supports_transactions - for conn in connections.all()) + """Return True if all connections support transactions.""" + return all(conn.features.supports_transactions for conn in connections.all()) class TestCase(TransactionTestCase): """ - Similar to TransactionTestCase, but uses `transaction.atomic()` to achieve + Similar to TransactionTestCase, but use `transaction.atomic()` to achieve test isolation. In most situations, TestCase should be preferred to TransactionTestCase as @@ -966,7 +965,7 @@ class TestCase(TransactionTestCase): """ @classmethod def _enter_atomics(cls): - """Helper method to open atomic blocks for multiple databases""" + """Open atomic blocks for multiple databases.""" atomics = {} for db_name in cls._databases_names(): atomics[db_name] = transaction.atomic(using=db_name) @@ -975,7 +974,7 @@ class TestCase(TransactionTestCase): @classmethod def _rollback_atomics(cls, atomics): - """Rollback atomic blocks opened through the previous method""" + """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) @@ -1014,7 +1013,7 @@ class TestCase(TransactionTestCase): @classmethod def setUpTestData(cls): - """Load initial data for the TestCase""" + """Load initial data for the TestCase.""" pass def _should_reload_connections(self): @@ -1050,7 +1049,7 @@ class TestCase(TransactionTestCase): class CheckCondition: - """Descriptor class for deferred condition checking""" + """Descriptor class for deferred condition checking.""" def __init__(self, *conditions): self.conditions = conditions @@ -1095,9 +1094,7 @@ def _deferredSkip(condition, reason): def skipIfDBFeature(*features): - """ - Skip a test if a database has at least one of the named 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) @@ -1105,9 +1102,7 @@ def skipIfDBFeature(*features): def skipUnlessDBFeature(*features): - """ - Skip a test unless a database has all the named 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) @@ -1115,9 +1110,7 @@ def skipUnlessDBFeature(*features): def skipUnlessAnyDBFeature(*features): - """ - Skip a test unless a database has any of the named 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) @@ -1126,11 +1119,9 @@ def skipUnlessAnyDBFeature(*features): class QuietWSGIRequestHandler(WSGIRequestHandler): """ - Just a regular WSGIRequestHandler except it doesn't log to the standard - output any of the requests received, so as to not clutter the output for - the tests' results. + 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 @@ -1147,17 +1138,14 @@ class FSFilesHandler(WSGIHandler): def _should_handle(self, path): """ - Checks if the path should be handled. Ignores the path if: - + 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): - """ - Returns the relative path to the file on disk for the given 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) @@ -1191,7 +1179,6 @@ 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 @@ -1204,7 +1191,6 @@ 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 @@ -1213,9 +1199,7 @@ class _MediaFilesHandler(FSFilesHandler): class LiveServerThread(threading.Thread): - """ - Thread for running a live http server while the tests are running. - """ + """Thread for running a live http server while the tests are running.""" def __init__(self, host, static_handler, connections_override=None): self.host = host @@ -1228,8 +1212,8 @@ class LiveServerThread(threading.Thread): def run(self): """ - Sets up the live server and databases, and then loops over handling - http requests. + 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 @@ -1263,14 +1247,14 @@ class LiveServerThread(threading.Thread): class LiveServerTestCase(TransactionTestCase): """ - Does basically the same as TransactionTestCase but also launches a live - http server in a separate thread so that the tests may use another testing + 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. - Note that it inherits from TransactionTestCase instead of TestCase because - the threads do not 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. + 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' server_thread_class = LiveServerThread @@ -1338,14 +1322,13 @@ class LiveServerTestCase(TransactionTestCase): class SerializeMixin: """ - Mixin to enforce serialization of TestCases that share a common resource. + 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. + Place it early in the MRO in order to isolate setUpClass()/tearDownClass(). """ - lockfile = None @classmethod diff --git a/django/test/utils.py b/django/test/utils.py index 88158e89d6..efd1b49c88 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -55,7 +55,8 @@ class Approximate: class ContextList(list): - """A wrapper that provides direct key access to context items contained + """ + A wrapper that provides direct key access to context items contained in a list of context objects. """ def __getitem__(self, key): @@ -93,8 +94,8 @@ class ContextList(list): def instrumented_test_render(self, context): """ - An instrumented Template render method, providing a signal - that can be intercepted by the test system Client + 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) @@ -157,9 +158,7 @@ def teardown_test_environment(): def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs): - """ - Create the test databases. - """ + """Create the test databases.""" test_databases, mirrored_aliases = get_unique_databases_and_mirrors() old_names = [] @@ -290,9 +289,7 @@ def get_unique_databases_and_mirrors(): def teardown_databases(old_config, verbosity, parallel=0, keepdb=False): - """ - Destroy all the non-mirror databases. - """ + """Destroy all the non-mirror databases.""" for connection, old_name, destroy in old_config: if destroy: if parallel > 1: @@ -387,10 +384,10 @@ class TestContextDecorator: class override_settings(TestContextDecorator): """ - Acts as either a decorator or a context manager. If it's a decorator it - takes a function and returns a wrapped function. If it's a contextmanager - it's used with the ``with`` statement. In either event entering/exiting - are called before and after, respectively, the function/block is executed. + 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. """ def __init__(self, **kwargs): self.options = kwargs @@ -444,7 +441,7 @@ class override_settings(TestContextDecorator): class modify_settings(override_settings): """ - Like override_settings, but makes it possible to append, prepend or remove + Like override_settings, but makes it possible to append, prepend, or remove items instead of redefining the entire list. """ def __init__(self, *args, **kwargs): @@ -492,7 +489,7 @@ class modify_settings(override_settings): class override_system_checks(TestContextDecorator): """ - Acts as a decorator. Overrides list of registered system checks. + 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. """ @@ -516,10 +513,10 @@ class override_system_checks(TestContextDecorator): def compare_xml(want, got): - """Tries 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. Comment nodes are not considered in the - comparison. Leading and trailing whitespace is ignored on both chunks. + """ + 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 and leading and trailing whitespace. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py """ @@ -794,9 +791,7 @@ def require_jinja2(test_func): class override_script_prefix(TestContextDecorator): - """ - Decorator or context manager to temporary override the script prefix. - """ + """Decorator or context manager to temporary override the script prefix.""" def __init__(self, prefix): self.prefix = prefix super().__init__() @@ -840,7 +835,6 @@ class isolate_apps(TestContextDecorator): `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) @@ -856,9 +850,7 @@ class isolate_apps(TestContextDecorator): def tag(*tags): - """ - Decorator to add tags to a test class or method. - """ + """Decorator to add tags to a test class or method.""" def decorator(obj): setattr(obj, 'tags', set(tags)) return obj |
