gh-91513: Tidied up a test and did minor refactoring around test filename gener… (GH-93265)

This commit is contained in:
Vinay Sajip 2022-05-26 17:11:15 +01:00 committed by GitHub
parent da39719483
commit efc5d37671
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -540,6 +540,12 @@ class CustomLevelsAndFiltersTest(BaseTest):
handler.removeFilter(garr) handler.removeFilter(garr)
def make_temp_file(*args, **kwargs):
fd, fn = tempfile.mkstemp(*args, **kwargs)
os.close(fd)
return fn
class HandlerTest(BaseTest): class HandlerTest(BaseTest):
def test_name(self): def test_name(self):
h = logging.Handler() h = logging.Handler()
@ -554,8 +560,7 @@ class HandlerTest(BaseTest):
# but we can try instantiating them with various options # but we can try instantiating them with various options
if sys.platform in ('linux', 'darwin'): if sys.platform in ('linux', 'darwin'):
for existing in (True, False): for existing in (True, False):
fd, fn = tempfile.mkstemp() fn = make_temp_file()
os.close(fd)
if not existing: if not existing:
os.unlink(fn) os.unlink(fn)
h = logging.handlers.WatchedFileHandler(fn, encoding='utf-8', delay=True) h = logging.handlers.WatchedFileHandler(fn, encoding='utf-8', delay=True)
@ -609,8 +614,7 @@ class HandlerTest(BaseTest):
See Issue #27493. See Issue #27493.
""" """
fd, fn = tempfile.mkstemp() fn = make_temp_file()
os.close(fd)
os.unlink(fn) os.unlink(fn)
pfn = pathlib.Path(fn) pfn = pathlib.Path(fn)
cases = ( cases = (
@ -649,8 +653,7 @@ class HandlerTest(BaseTest):
self.deletion_time = None self.deletion_time = None
for delay in (False, True): for delay in (False, True):
fd, fn = tempfile.mkstemp('.log', 'test_logging-3-') fn = make_temp_file('.log', 'test_logging-3-')
os.close(fd)
remover = threading.Thread(target=remove_loop, args=(fn, del_count)) remover = threading.Thread(target=remove_loop, args=(fn, del_count))
remover.daemon = True remover.daemon = True
remover.start() remover.start()
@ -1596,8 +1599,7 @@ class ConfigFileTest(BaseTest):
os.remove(fn) os.remove(fn)
with self.check_no_resource_warning(): with self.check_no_resource_warning():
fd, fn = tempfile.mkstemp(".log", "test_logging-X-") fn = make_temp_file(".log", "test_logging-X-")
os.close(fd)
# Replace single backslash with double backslash in windows # Replace single backslash with double backslash in windows
# to avoid unicode error during string formatting # to avoid unicode error during string formatting
@ -1782,8 +1784,7 @@ class SocketHandlerTest(BaseTest):
self.root_logger.error('Nor this') self.root_logger.error('Nor this')
def _get_temp_domain_socket(): def _get_temp_domain_socket():
fd, fn = tempfile.mkstemp(prefix='test_logging_', suffix='.sock') fn = make_temp_file(prefix='test_logging_', suffix='.sock')
os.close(fd)
# just need a name - file can't be present, or we'll get an # just need a name - file can't be present, or we'll get an
# 'address already in use' error. # 'address already in use' error.
os.remove(fn) os.remove(fn)
@ -2135,8 +2136,7 @@ class EncodingTest(BaseTest):
def test_encoding_plain_file(self): def test_encoding_plain_file(self):
# In Python 2.x, a plain file object is treated as having no encoding. # In Python 2.x, a plain file object is treated as having no encoding.
log = logging.getLogger("test") log = logging.getLogger("test")
fd, fn = tempfile.mkstemp(".log", "test_logging-1-") fn = make_temp_file(".log", "test_logging-1-")
os.close(fd)
# the non-ascii data we write to the log. # the non-ascii data we write to the log.
data = "foo\x80" data = "foo\x80"
try: try:
@ -3227,8 +3227,7 @@ class ConfigDictTest(BaseTest):
os.remove(fn) os.remove(fn)
with self.check_no_resource_warning(): with self.check_no_resource_warning():
fd, fn = tempfile.mkstemp(".log", "test_logging-X-") fn = make_temp_file(".log", "test_logging-X-")
os.close(fd)
config = { config = {
"version": 1, "version": 1,
@ -4891,10 +4890,14 @@ class BasicConfigTest(unittest.TestCase):
async def log_record(): async def log_record():
logging.warning('hello world') logging.warning('hello world')
handler = None
log_filename = make_temp_file('.log', 'test-logging-taskname-')
self.addCleanup(os.remove, log_filename)
try: try:
encoding = 'utf-8' encoding = 'utf-8'
logging.basicConfig(filename='test.log', errors='strict', encoding=encoding, logging.basicConfig(filename=log_filename, errors='strict',
format='%(taskName)s - %(message)s', level=logging.WARNING) encoding=encoding, level=logging.WARNING,
format='%(taskName)s - %(message)s')
self.assertEqual(len(logging.root.handlers), 1) self.assertEqual(len(logging.root.handlers), 1)
handler = logging.root.handlers[0] handler = logging.root.handlers[0]
@ -4903,13 +4906,13 @@ class BasicConfigTest(unittest.TestCase):
with asyncio.Runner(debug=True) as runner: with asyncio.Runner(debug=True) as runner:
logging.logAsyncioTasks = True logging.logAsyncioTasks = True
runner.run(log_record()) runner.run(log_record())
with open(log_filename, encoding='utf-8') as f:
data = f.read().strip()
self.assertRegex(data, r'Task-\d+ - hello world')
finally: finally:
asyncio.set_event_loop_policy(None) asyncio.set_event_loop_policy(None)
handler.close() if handler:
with open('test.log', encoding='utf-8') as f: handler.close()
data = f.read().strip()
os.remove('test.log')
self.assertRegex(data, r'Task-\d+ - hello world')
def _test_log(self, method, level=None): def _test_log(self, method, level=None):
@ -5294,8 +5297,7 @@ class BaseFileTest(BaseTest):
def setUp(self): def setUp(self):
BaseTest.setUp(self) BaseTest.setUp(self)
fd, self.fn = tempfile.mkstemp(".log", "test_logging-2-") self.fn = make_temp_file(".log", "test_logging-2-")
os.close(fd)
self.rmfiles = [] self.rmfiles = []
def tearDown(self): def tearDown(self):