Exemplo n.º 1
0
 def test_time_recorded(self):
     with captured_stderr() as stderr:
         call_command('test',
                      '--timing',
                      'sites',
                      testrunner='test_runner.tests.MockTestRunner')
     self.assertIn('Total run took', stderr.getvalue())
Exemplo n.º 2
0
 def test_command_help(self):
     with captured_stdout(), captured_stderr():
         # `call_command` bypasses the parser; by calling
         # `execute_from_command_line` with the help subcommand we
         # ensure that there are no issues with the parser itself.
         execute_from_command_line(
             ['django-admin', 'help', 'compilemessages'])
Exemplo n.º 3
0
 def test_no_parallel_spawn(self, *mocked_objects):
     with captured_stderr() as stderr:
         call_command(
             "test",
             testrunner="test_runner.tests.MockTestRunner",
         )
     self.assertEqual(stderr.getvalue(), "")
Exemplo n.º 4
0
 def test_parallel_spawn(self, *mocked_objects):
     with captured_stderr() as stderr:
         call_command(
             "test",
             "--parallel=auto",
             testrunner="test_runner.tests.MockTestRunner",
         )
     self.assertIn("parallel=1", stderr.getvalue())
Exemplo n.º 5
0
    def test_log_message(self):
        request = WSGIRequest(RequestFactory().get('/').environ)
        request.makefile = lambda *args, **kwargs: BytesIO()
        handler = WSGIRequestHandler(request, '192.168.0.2', None)

        with captured_stderr() as stderr:
            handler.log_message('GET %s %s', 'A', 'B')
        self.assertIn('] GET A B', stderr.getvalue())
Exemplo n.º 6
0
 def test_extra_tests_run_tests(self):
     runner = self.get_runner()
     with captured_stderr():
         with self.assertWarnsMessage(RemovedInDjango50Warning, self.msg):
             runner.run_tests(
                 test_labels=["test_runner_apps.sample.tests_sample.EmptyTestCase"],
                 extra_tests=[],
             )
    def test_log_message(self):
        request = WSGIRequest(RequestFactory().get('/').environ)
        request.makefile = lambda *args, **kwargs: BytesIO()
        handler = WSGIRequestHandler(request, '192.168.0.2', None)

        with captured_stderr() as stderr:
            handler.log_message('GET %s %s', 'A', 'B')
        self.assertIn('] GET A B', stderr.getvalue())
Exemplo n.º 8
0
 def test_parallel_auto(self, *mocked_objects):
     with captured_stderr() as stderr:
         call_command(
             'test',
             '--parallel=auto',
             testrunner='test_runner.tests.MockTestRunner',
         )
     self.assertIn('parallel=12', stderr.getvalue())
Exemplo n.º 9
0
 def test_timings_not_captured(self):
     runner = DiscoverRunner(timing=False)
     with captured_stderr() as stderr:
         with runner.time_keeper.timed('test'):
             pass
         runner.time_keeper.print_results()
     self.assertTrue(isinstance(runner.time_keeper, NullTimeKeeper))
     self.assertNotIn('test', stderr.getvalue())
Exemplo n.º 10
0
 def test_timings_captured(self):
     runner = DiscoverRunner(timing=True)
     with captured_stderr() as stderr:
         with runner.time_keeper.timed("test"):
             pass
         runner.time_keeper.print_results()
     self.assertIsInstance(runner.time_keeper, TimeKeeper)
     self.assertIn("test", stderr.getvalue())
Exemplo n.º 11
0
 def test_time_recorded(self):
     with captured_stderr() as stderr:
         call_command(
             "test",
             "--timing",
             "sites",
             testrunner="test_runner.tests.MockTestRunner",
         )
     self.assertIn("Total run took", stderr.getvalue())
Exemplo n.º 12
0
 def test_no_parallel_spawn(self, mocked_get_start_method,
                            mocked_cpu_count):
     mocked_get_start_method.return_value = 'spawn'
     with captured_stderr() as stderr:
         call_command(
             'test',
             testrunner='test_runner.tests.MockTestRunner',
         )
     self.assertEqual(stderr.getvalue(), '')
Exemplo n.º 13
0
 def test_buffer_mode_test_fail(self):
     runner = DiscoverRunner(buffer=True, verbose=0)
     with captured_stdout() as stdout, captured_stderr() as stderr:
         suite = runner.build_suite([
             'test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase.test_fail',
         ])
         runner.run_suite(suite)
     self.assertIn('Write to stderr.', stderr.getvalue())
     self.assertIn('Write to stdout.', stdout.getvalue())
Exemplo n.º 14
0
 def test_parallel_spawn(self, mocked_get_start_method, mocked_cpu_count):
     mocked_get_start_method.return_value = "spawn"
     with captured_stderr() as stderr:
         call_command(
             "test",
             "--parallel=auto",
             testrunner="test_runner.tests.MockTestRunner",
         )
     self.assertIn("parallel=1", stderr.getvalue())
    def test_ignore_fail(self, mock_enter, mock_exit):
        mock_enter.return_value = False
        mock_exit.return_value = None

        with captured_stderr() as stderr:
            result = call_command("command_lock", "--try", "--ignore-fail", "--", "true")

        self.assertIsNone(result)
        self.assertEqual(stderr.getvalue(), "Unable to acquire lock\n")
Exemplo n.º 16
0
 def test_system_exit(self):
     """ Exception raised in a command should raise CommandError with
         call_command, but SystemExit when run from command line
     """
     with self.assertRaises(CommandError):
         management.call_command('dance', example="raise")
     with captured_stderr() as stderr, self.assertRaises(SystemExit):
         management.ManagementUtility(['manage.py', 'dance', '--example=raise']).execute()
     self.assertIn("CommandError", stderr.getvalue())
Exemplo n.º 17
0
 def test_django_test_processes_parallel_default(self, *mocked_objects):
     for parallel in ['--parallel', '--parallel=auto']:
         with self.subTest(parallel=parallel):
             with captured_stderr() as stderr:
                 call_command(
                     'test',
                     parallel,
                     testrunner='test_runner.tests.MockTestRunner',
                 )
             self.assertIn('parallel=7', stderr.getvalue())
Exemplo n.º 18
0
 def test_buffer_mode_test_pass(self):
     runner = DiscoverRunner(buffer=True, verbosity=0)
     with captured_stdout() as stdout, captured_stderr() as stderr:
         suite = runner.build_suite([
             "test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase."
             "test_pass",
         ])
         runner.run_suite(suite)
     self.assertNotIn("Write to stderr.", stderr.getvalue())
     self.assertNotIn("Write to stdout.", stdout.getvalue())
Exemplo n.º 19
0
 def test_django_test_processes_parallel_default(self, *mocked_objects):
     for parallel in ["--parallel", "--parallel=auto"]:
         with self.subTest(parallel=parallel):
             with captured_stderr() as stderr:
                 call_command(
                     "test",
                     parallel,
                     testrunner="test_runner.tests.MockTestRunner",
                 )
             self.assertIn("parallel=7", stderr.getvalue())
Exemplo n.º 20
0
    def test_https(self):
        request = WSGIRequest(RequestFactory().get('/').environ)
        request.makefile = lambda *args, **kwargs: BytesIO()

        handler = WSGIRequestHandler(request, '192.168.0.2', None)

        with captured_stderr() as stderr:
            handler.log_message("GET %s %s", str('\x16\x03'), "4")
            self.assertIn(
                "You're accessing the development server over HTTPS, "
                "but it only supports HTTP.", stderr.getvalue())
Exemplo n.º 21
0
 def test_time_logging_runner(self):
     runner = TimeLoggingTestRunner()
     suite = runner.build_suite(
         ['test_project.tests.test_test_utils.TestUtils.test_status_signal_emitted'],
     )
     with captured_stdout() as stdout, captured_stderr() as stderr:
         runner.run_suite(suite)
     self.assertIn('slow tests (>0.0s)', stdout.getvalue())
     self.assertIn('Total slow tests detected: 1', stdout.getvalue())
     self.assertIn('Ran 1 test', stderr.getvalue())
     self.assertIn('OK', stderr.getvalue())
Exemplo n.º 22
0
    def test_optparse_compatibility(self):
        """
        optparse should be supported during Django 1.8/1.9 releases.
        """
        out = StringIO()
        management.call_command('optparse_cmd', stdout=out)
        self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n")

        # Simulate command line execution
        with captured_stdout() as stdout, captured_stderr():
            management.execute_from_command_line(['django-admin', 'optparse_cmd'])
        self.assertEqual(stdout.getvalue(), "All right, let's dance Rock'n'Roll.\n")
Exemplo n.º 23
0
    def test_optparse_compatibility(self):
        """
        optparse should be supported during Django 1.8/1.9 releases.
        """
        out = StringIO()
        management.call_command('optparse_cmd', stdout=out)
        self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n")

        # Simulate command line execution
        with captured_stdout() as stdout, captured_stderr():
            management.execute_from_command_line(['django-admin', 'optparse_cmd'])
        self.assertEqual(stdout.getvalue(), "All right, let's dance Rock'n'Roll.\n")
Exemplo n.º 24
0
    def test_https(self):
        request = WSGIRequest(RequestFactory().get('/').environ)
        request.makefile = lambda *args, **kwargs: BytesIO()

        handler = WSGIRequestHandler(request, '192.168.0.2', None)

        with captured_stderr() as stderr:
            handler.log_message("GET %s %s", str('\x16\x03'), "4")
            self.assertIn(
                "You're accessing the developement server over HTTPS, "
                "but it only supports HTTP.",
                stderr.getvalue()
            )
Exemplo n.º 25
0
    def test_strips_underscore_headers(self):
        """WSGIRequestHandler ignores headers containing underscores.

        This follows the lead of nginx and Apache 2.4, and is to avoid
        ambiguity between dashes and underscores in mapping to WSGI environ,
        which can have security implications.
        """
        def test_app(environ, start_response):
            """A WSGI app that just reflects its HTTP environ."""
            start_response('200 OK', [])
            http_environ_items = sorted(
                '%s:%s' % (k, v) for k, v in environ.items()
                if k.startswith('HTTP_')
            )
            yield (','.join(http_environ_items)).encode('utf-8')

        rfile = BytesIO()
        rfile.write(b"GET / HTTP/1.0\r\n")
        rfile.write(b"Some-Header: good\r\n")
        rfile.write(b"Some_Header: bad\r\n")
        rfile.write(b"Other_Header: bad\r\n")
        rfile.seek(0)

        # WSGIRequestHandler closes the output file; we need to make this a
        # no-op so we can still read its contents.
        class UnclosableBytesIO(BytesIO):
            def close(self):
                pass

        wfile = UnclosableBytesIO()

        def makefile(mode, *a, **kw):
            if mode == 'rb':
                return rfile
            elif mode == 'wb':
                return wfile

        request = Stub(makefile=makefile)
        server = Stub(base_environ={}, get_app=lambda: test_app)

        # We don't need to check stderr, but we don't want it in test output
        with captured_stderr():
            # instantiating a handler runs the request as side effect
            WSGIRequestHandler(request, '192.168.0.2', server)

        wfile.seek(0)
        body = list(wfile.readlines())[-1]

        self.assertEqual(body, b'HTTP_SOME_HEADER:good')
Exemplo n.º 26
0
 def test_system_exit(self):
     """ Exception raised in a command should raise CommandError with
         call_command, but SystemExit when run from command line
     """
     with self.assertRaises(CommandError) as cm:
         management.call_command('dance', example="raise")
     self.assertEqual(cm.exception.returncode, 3)
     dance.Command.requires_system_checks = []
     try:
         with captured_stderr() as stderr, self.assertRaises(SystemExit) as cm:
             management.ManagementUtility(['manage.py', 'dance', '--example=raise']).execute()
         self.assertEqual(cm.exception.code, 3)
     finally:
         dance.Command.requires_system_checks = '__all__'
     self.assertIn("CommandError", stderr.getvalue())
Exemplo n.º 27
0
 def test_suite_result_with_failure(self):
     cases = [
         (1, 'FailureTestCase'),
         (1, 'ErrorTestCase'),
         (0, 'ExpectedFailureTestCase'),
         (1, 'UnexpectedSuccessTestCase'),
     ]
     runner = DiscoverRunner(verbosity=0)
     for expected_failures, testcase in cases:
         with self.subTest(testcase=testcase):
             suite = runner.build_suite([
                 f'test_runner_apps.failures.tests_failures.{testcase}',
             ])
             with captured_stderr():
                 result = runner.run_suite(suite)
             failures = runner.suite_result(suite, result)
             self.assertEqual(failures, expected_failures)
Exemplo n.º 28
0
 def test_broken_pipe_errors(self):
     """WSGIServer handles broken pipe errors."""
     request = WSGIRequest(self.request_factory.get('/').environ)
     client_address = ('192.168.2.0', 8080)
     msg = f'- Broken pipe from {client_address}\n'
     tests = [
         BrokenPipeError,
         ConnectionAbortedError,
         ConnectionResetError,
     ]
     for exception in tests:
         with self.subTest(exception=exception):
             try:
                 server = WSGIServer(('localhost', 0), WSGIRequestHandler)
                 try:
                     raise exception()
                 except Exception:
                     with captured_stderr() as err:
                         with self.assertLogs('django.server', 'INFO') as cm:
                             server.handle_error(request, client_address)
                     self.assertEqual(err.getvalue(), '')
                     self.assertEqual(cm.records[0].getMessage(), msg)
             finally:
                 server.server_close()
Exemplo n.º 29
0
 def setUp(self):
     self.client.login(username='******', password='******')
     with captured_stderr() as self.docutils_stderr:
         self.response = self.client.get(
             reverse('django-admindocs-models-detail',
                     args=['admin_docs', 'person']))
Exemplo n.º 30
0
 def test_command_help(self):
     with captured_stdout(), captured_stderr():
         # `call_command` bypasses the parser; by calling
         # `execute_from_command_line` with the help subcommand we
         # ensure that there are no issues with the parser itself.
         execute_from_command_line(['django-admin', 'help', 'compilemessages'])
Exemplo n.º 31
0
 def setUp(self):
     self.client.login(username='******', password='******')
     with captured_stderr() as self.docutils_stderr:
         self.response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'person']))
Exemplo n.º 32
0
 def test_parse_rst_with_docstring_no_leading_line_feed(self):
     title, body, _ = parse_docstring('firstline\n\n    second line')
     with captured_stderr() as stderr:
         self.assertEqual(parse_rst(title, ''), '<p>firstline</p>\n')
         self.assertEqual(parse_rst(body, ''), '<p>second line</p>\n')
     self.assertEqual(stderr.getvalue(), '')
Exemplo n.º 33
0
 def setUp(self):
     self.client.force_login(self.superuser)
     with captured_stderr() as self.docutils_stderr:
         self.response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'Person']))
Exemplo n.º 34
0
 def test_parallel_invalid(self, *mocked_objects):
     with self.assertRaises(SystemExit), captured_stderr() as stderr:
         self.get_parser().parse_args(["--parallel", "unaccepted"])
     msg = "argument --parallel: 'unaccepted' is not an integer or the string 'auto'"
     self.assertIn(msg, stderr.getvalue())
Exemplo n.º 35
0
 def setUp(self):
     self.client.force_login(self.superuser)
     with captured_stderr() as self.docutils_stderr:
         self.response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'Person']))
Exemplo n.º 36
0
def is_es_online(connection_alias='default'):
    with captured_stderr():
        es = connections.get_connection(connection_alias)
        return es.ping()
Exemplo n.º 37
0
 def test_command_configuration_error(self):
     with captured_stderr() as stderr, self.assertRaises(SystemExit):
         ManagementUtility(['lisa-api-cli.py', 'configuration']).execute()
     self.assertIn("CommandError", stderr.getvalue())