From c36e9950ae2b64f1e4df3ea724803f4036a1a983 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Mon, 30 Dec 2019 17:51:09 -0800 Subject: [PATCH] tests: test TqdmConsole --- src/ocrmypdf/api.py | 10 +++++++- tests/test_api.py | 61 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 tests/test_api.py diff --git a/src/ocrmypdf/api.py b/src/ocrmypdf/api.py index cd8e2576..3270b25d 100644 --- a/src/ocrmypdf/api.py +++ b/src/ocrmypdf/api.py @@ -32,7 +32,15 @@ from .cli import parser class TqdmConsole: - """Wrapper to log messages in a way that is compatible with tqdm progress bar""" + """Wrapper to log messages in a way that is compatible with tqdm progress bar + + This routes log messages through tqdm so that it can print them above the + progress bar, and then refresh the progress bar, rather than overwriting + it which looks messy. + + For some reason Python 3.6 prints extra empty messages from time to time, + so we suppress those. + """ def __init__(self, file): self.file = file diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 00000000..fd09f262 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,61 @@ +# © 2019 James R. Barlow: github.com/jbarlow83 +# +# This file is part of OCRmyPDF. +# +# OCRmyPDF is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# OCRmyPDF is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with OCRmyPDF. If not, see . + +import logging +from io import StringIO + +import pytest +from tqdm import tqdm + +import ocrmypdf + + +def test_raw_console(): + bio = StringIO() + tqconsole = ocrmypdf.api.TqdmConsole(file=bio) + tqconsole.write("Test") + tqconsole.flush() + assert "Test" in bio.getvalue() + + +def test_tqdm_console(): + log = logging.getLogger() + log.setLevel(logging.INFO) + + formatter = logging.Formatter('%(message)s') + + bio = StringIO() + console = logging.StreamHandler(ocrmypdf.api.TqdmConsole(file=bio)) + console.setFormatter(formatter) + + log.addHandler(console) + + def before_pbar(message): + # Ensure that log messages appear before the progress bar, even when + # printed after the progress bar updates. + v = bio.getvalue() + pbar_start_marker = '|#' + return v.index(message) < v.index(pbar_start_marker) + + with tqdm(total=2, file=bio, disable=False) as pbar: + pbar.update() + msg = "1/2 above progress bar" + log.info(msg) + assert before_pbar(msg) + + log.info("done") + assert not before_pbar("done")