]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-71339: Use new assertion methods in the http tests (GH-129058) (GH-132500)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 22 May 2025 09:40:26 +0000 (11:40 +0200)
committerGitHub <noreply@github.com>
Thu, 22 May 2025 09:40:26 +0000 (09:40 +0000)
(cherry picked from commit 7076d076c27687140adc64ad495ea82f6eb5b3ce)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Lib/test/test_http_cookiejar.py
Lib/test/test_http_cookies.py
Lib/test/test_httplib.py
Lib/test/test_httpservers.py

index 6a7b907e3667f3b9d55f0c28a1a821334fe50ac1..15f04362e31693bb09dd884f2ac1ee60fe56ccb2 100644 (file)
@@ -6,6 +6,7 @@ import sys
 import re
 from test.support import os_helper
 from test.support import warnings_helper
+from test.support.testcase import ExtraAssertions
 import time
 import unittest
 import urllib.request
@@ -1436,7 +1437,7 @@ class CookieTests(unittest.TestCase):
         self.assertIsNone(cookie.expires)
 
 
-class LWPCookieTests(unittest.TestCase):
+class LWPCookieTests(unittest.TestCase, ExtraAssertions):
     # Tests taken from libwww-perl, with a few modifications and additions.
 
     def test_netscape_example_1(self):
@@ -1528,7 +1529,7 @@ class LWPCookieTests(unittest.TestCase):
         h = req.get_header("Cookie")
         self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
         self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
-        self.assertTrue(h.startswith("SHIPPING=FEDEX;"))
+        self.assertStartsWith(h, "SHIPPING=FEDEX;")
 
     def test_netscape_example_2(self):
         # Second Example transaction sequence:
index 7b3dc0fdaedc3bf07e00db8d7b7030f74ba260f4..37bb7fdddf65a7a5bd3b54b2e949b728f1901d80 100644 (file)
@@ -6,9 +6,10 @@ import doctest
 from http import cookies
 import pickle
 from test import support
+from test.support.testcase import ExtraAssertions
 
 
-class CookieTests(unittest.TestCase):
+class CookieTests(unittest.TestCase, ExtraAssertions):
 
     def test_basic(self):
         cases = [
@@ -180,7 +181,7 @@ class CookieTests(unittest.TestCase):
         C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')
         C['Customer']['expires'] = 0
         # can't test exact output, it always depends on current date/time
-        self.assertTrue(C.output().endswith('GMT'))
+        self.assertEndsWith(C.output(), 'GMT')
 
         # loading 'expires'
         C = cookies.SimpleCookie()
index 0c4214addb9baa8dcae8cf62e031bb49f65f28e8..84e99a156039a189009298b69806f000bbc7c590 100644 (file)
@@ -16,6 +16,7 @@ TestCase = unittest.TestCase
 from test import support
 from test.support import os_helper
 from test.support import socket_helper
+from test.support.testcase import ExtraAssertions
 
 support.requires_working_socket(module=True)
 
@@ -134,7 +135,7 @@ class FakeSocketHTTPConnection(client.HTTPConnection):
     def create_connection(self, *pos, **kw):
         return FakeSocket(*self.fake_socket_args)
 
-class HeaderTests(TestCase):
+class HeaderTests(TestCase, ExtraAssertions):
     def test_auto_headers(self):
         # Some headers are added automatically, but should not be added by
         # .request() if they are explicitly set.
@@ -273,7 +274,7 @@ class HeaderTests(TestCase):
         sock = FakeSocket('')
         conn.sock = sock
         conn.request('GET', '/foo')
-        self.assertTrue(sock.data.startswith(expected))
+        self.assertStartsWith(sock.data, expected)
 
         expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
                    b'Accept-Encoding: identity\r\n\r\n'
@@ -281,7 +282,7 @@ class HeaderTests(TestCase):
         sock = FakeSocket('')
         conn.sock = sock
         conn.request('GET', '/foo')
-        self.assertTrue(sock.data.startswith(expected))
+        self.assertStartsWith(sock.data, expected)
 
         expected = b'GET /foo HTTP/1.1\r\nHost: [fe80::]\r\n' \
                    b'Accept-Encoding: identity\r\n\r\n'
@@ -289,7 +290,7 @@ class HeaderTests(TestCase):
         sock = FakeSocket('')
         conn.sock = sock
         conn.request('GET', '/foo')
-        self.assertTrue(sock.data.startswith(expected))
+        self.assertStartsWith(sock.data, expected)
 
         expected = b'GET /foo HTTP/1.1\r\nHost: [fe80::]:81\r\n' \
                    b'Accept-Encoding: identity\r\n\r\n'
@@ -297,7 +298,7 @@ class HeaderTests(TestCase):
         sock = FakeSocket('')
         conn.sock = sock
         conn.request('GET', '/foo')
-        self.assertTrue(sock.data.startswith(expected))
+        self.assertStartsWith(sock.data, expected)
 
     def test_malformed_headers_coped_with(self):
         # Issue 19996
@@ -335,9 +336,9 @@ class HeaderTests(TestCase):
         self.assertIsNotNone(resp.getheader('obs-text'))
         self.assertIn('obs-text', resp.msg)
         for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
-            self.assertTrue(folded.startswith('text'))
+            self.assertStartsWith(folded, 'text')
             self.assertIn(' folded with space', folded)
-            self.assertTrue(folded.endswith('folded with tab'))
+            self.assertEndsWith(folded, 'folded with tab')
 
     def test_invalid_headers(self):
         conn = client.HTTPConnection('example.com')
@@ -537,7 +538,7 @@ class TransferEncodingTest(TestCase):
         return b''.join(body)
 
 
-class BasicTest(TestCase):
+class BasicTest(TestCase, ExtraAssertions):
     def test_dir_with_added_behavior_on_status(self):
         # see issue40084
         self.assertTrue({'description', 'name', 'phrase', 'value'} <= set(dir(HTTPStatus(404))))
@@ -989,8 +990,7 @@ class BasicTest(TestCase):
             sock = FakeSocket(body)
             conn.sock = sock
             conn.request('GET', '/foo', body)
-            self.assertTrue(sock.data.startswith(expected), '%r != %r' %
-                    (sock.data[:len(expected)], expected))
+            self.assertStartsWith(sock.data, expected)
 
     def test_send(self):
         expected = b'this is a test this is only a test'
@@ -1494,7 +1494,7 @@ class BasicTest(TestCase):
         conn.putrequest('GET', '/☃')
 
 
-class ExtendedReadTest(TestCase):
+class ExtendedReadTest(TestCase, ExtraAssertions):
     """
     Test peek(), read1(), readline()
     """
@@ -1553,7 +1553,7 @@ class ExtendedReadTest(TestCase):
                 # then unbounded peek
                 p2 = resp.peek()
                 self.assertGreaterEqual(len(p2), len(p))
-                self.assertTrue(p2.startswith(p))
+                self.assertStartsWith(p2, p)
                 next = resp.read(len(p2))
                 self.assertEqual(next, p2)
             else:
@@ -1578,7 +1578,7 @@ class ExtendedReadTest(TestCase):
             line = readline(limit)
             if line and line != b"foo":
                 if len(line) < 5:
-                    self.assertTrue(line.endswith(b"\n"))
+                    self.assertEndsWith(line, b"\n")
             all.append(line)
             if not line:
                 break
@@ -1687,7 +1687,7 @@ class Readliner:
             raise
 
 
-class OfflineTest(TestCase):
+class OfflineTest(TestCase, ExtraAssertions):
     def test_all(self):
         # Documented objects defined in the module should be in __all__
         expected = {"responses"}  # Allowlist documented dict() object
@@ -1773,7 +1773,7 @@ class OfflineTest(TestCase):
         ]
         for const in expected:
             with self.subTest(constant=const):
-                self.assertTrue(hasattr(client, const))
+                self.assertHasAttr(client, const)
 
 
 class SourceAddressTest(TestCase):
@@ -2241,7 +2241,7 @@ class HTTPResponseTest(TestCase):
         header = self.resp.getheader('No-Such-Header',default=42)
         self.assertEqual(header, 42)
 
-class TunnelTests(TestCase):
+class TunnelTests(TestCase, ExtraAssertions):
     def setUp(self):
         response_text = (
             'HTTP/1.1 200 OK\r\n\r\n' # Reply to CONNECT
@@ -2415,8 +2415,7 @@ class TunnelTests(TestCase):
                 msg=f'unexpected number of send calls: {mock_send.mock_calls}')
         proxy_setup_data_sent = mock_send.mock_calls[0][1][0]
         self.assertIn(b'CONNECT destination.com', proxy_setup_data_sent)
-        self.assertTrue(
-                proxy_setup_data_sent.endswith(b'\r\n\r\n'),
+        self.assertEndsWith(proxy_setup_data_sent, b'\r\n\r\n',
                 msg=f'unexpected proxy data sent {proxy_setup_data_sent!r}')
 
     def test_connect_put_request(self):
index 540eba7513ca0e96dd6ef38008cda28ca52dd307..140798a927a041380be5022b412adb84fb9591fc 100644 (file)
@@ -33,6 +33,7 @@ from test import support
 from test.support import (
     is_apple, os_helper, requires_subprocess, threading_helper
 )
+from test.support.testcase import ExtraAssertions
 
 support.requires_working_socket(module=True)
 
@@ -66,7 +67,7 @@ class TestServerThread(threading.Thread):
         self.join()
 
 
-class BaseTestCase(unittest.TestCase):
+class BaseTestCase(unittest.TestCase, ExtraAssertions):
     def setUp(self):
         self._threads = threading_helper.threading_setup()
         os.environ = os_helper.EnvironmentVarGuard()
@@ -335,8 +336,7 @@ class RequestHandlerLoggingTestCase(BaseTestCase):
             self.con.request('GET', '/')
             self.con.getresponse()
 
-        self.assertTrue(
-            err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
+        self.assertEndsWith(err.getvalue(), '"GET / HTTP/1.1" 200 -\n')
 
     def test_err(self):
         self.con = http.client.HTTPConnection(self.HOST, self.PORT)
@@ -347,8 +347,8 @@ class RequestHandlerLoggingTestCase(BaseTestCase):
             self.con.getresponse()
 
         lines = err.getvalue().split('\n')
-        self.assertTrue(lines[0].endswith('code 404, message File not found'))
-        self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
+        self.assertEndsWith(lines[0], 'code 404, message File not found')
+        self.assertEndsWith(lines[1], '"ERROR / HTTP/1.1" 404 -')
 
 
 class SimpleHTTPServerTestCase(BaseTestCase):
@@ -550,7 +550,7 @@ class SimpleHTTPServerTestCase(BaseTestCase):
         response = self.request(attack_url)
         self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
         location = response.getheader('Location')
-        self.assertFalse(location.startswith('//'), msg=location)
+        self.assertNotStartsWith(location, '//')
         self.assertEqual(location, expected_location,
                 msg='Expected Location header to start with a single / and '
                 'end with a / as this is a directory redirect.')
@@ -573,7 +573,7 @@ class SimpleHTTPServerTestCase(BaseTestCase):
         # We're just ensuring that the scheme and domain make it through, if
         # there are or aren't multiple slashes at the start of the path that
         # follows that isn't important in this Location: header.
-        self.assertTrue(location.startswith('https://pypi.org/'), msg=location)
+        self.assertStartsWith(location, 'https://pypi.org/')
 
     def test_get(self):
         #constructs the path relative to the root directory of the HTTPServer
@@ -1074,7 +1074,7 @@ class AuditableBytesIO:
         return len(self.datas)
 
 
-class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
+class BaseHTTPRequestHandlerTestCase(unittest.TestCase, ExtraAssertions):
     """Test the functionality of the BaseHTTPServer.
 
        Test the support for the Expect 100-continue header.
@@ -1162,7 +1162,7 @@ class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
             b'Host: dummy\r\n'
             b'\r\n'
         )
-        self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
+        self.assertStartsWith(result[0], b'HTTP/1.1 400 ')
         self.verify_expected_headers(result[1:result.index(b'\r\n')])
         self.assertFalse(self.handler.get_called)