From 47e940089d73e13a8f7f1d12344c2eb9bcaa3454 Mon Sep 17 00:00:00 2001 From: Scott Worley Date: Fri, 29 Dec 2023 16:33:39 -0800 Subject: [PATCH 1/1] --quiet controls fetch cache hit rate report too --- args.py | 5 +++-- fetch.py | 13 ++++++------- fetch_test.py | 5 ++++- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/args.py b/args.py index c550672..67d8c3f 100644 --- a/args.py +++ b/args.py @@ -94,7 +94,8 @@ def spec_from_commandline_args() -> Iterator[Spec]: layout = BesideIconLayout(texifier, args.image_size) else: raise ValueError(f'Unknown layout: {args.layout}') - with CachingFetcher(args.cache_path, args.timeout) as fetcher: + log = (lambda _: None) if args.quiet else _print_status + with CachingFetcher(args.cache_path, args.timeout, log) as fetcher: with open(args.out + '.tex', 'wb') as texout: yield Spec( args.url, @@ -106,4 +107,4 @@ def spec_from_commandline_args() -> Iterator[Spec]: layout, args.geometry, texout, - (lambda _: None) if args.quiet else _print_status) + log) diff --git a/fetch.py b/fetch.py index e998394..eb904a4 100644 --- a/fetch.py +++ b/fetch.py @@ -8,7 +8,7 @@ from abc import ABC, abstractmethod from contextlib import contextmanager from sys import stderr -from typing import IO, Iterator +from typing import Callable, Iterator import requests import requests_cache @@ -73,17 +73,16 @@ def DirectFetcher(timeout: int) -> Iterator[_SessionFetcher]: @contextmanager def CachingFetcher( - cache_path: str, - timeout: int, - report_stream: IO[str] = stderr) -> Iterator[_CachingFetcher]: + cache_path: str, + timeout: int, + log: Callable[[str], None] = lambda x: print(x, file=stderr), +) -> Iterator[_CachingFetcher]: with requests_cache.CachedSession(cache_path, cache_control=True) as session: fetcher = _CachingFetcher(session, timeout) yield fetcher if fetcher.request_count > 0: percent = 100.0 * fetcher.cache_hit_count / fetcher.request_count - print( - f"Fetch cache hits: {fetcher.cache_hit_count} ({percent:.1f}%)", - file=report_stream) + log(f"Fetch cache hits: {fetcher.cache_hit_count} ({percent:.1f}%)") class FakeFetcher(Fetcher): diff --git a/fetch_test.py b/fetch_test.py index 5f21fee..59a1514 100644 --- a/fetch_test.py +++ b/fetch_test.py @@ -45,7 +45,10 @@ class TestFetch(unittest.TestCase): def testCacheHitRateReport(self) -> None: buf = StringIO() - with CachingFetcher("testcachehitratereportwithcl", TIMEOUT, buf) as f: + + def log(msg: str) -> None: + print(msg, file=buf) + with CachingFetcher("testcachehitratereportwithcl", TIMEOUT, log) as f: for _ in range(7): f.fetch(f"http://localhost:{self._port}") self.assertEqual("Fetch cache hits: 6 (85.7%)\n", buf.getvalue()) -- 2.44.1