如何为这个 Python 代码编写自动测试?

How can I write automatic tests for this Python code?

我的脚本 core.py 位于文件夹 preprocessing 中,它获取一个字符串并对其进行清理。它是更大模型的一部分(请参阅最后一个导入,但这并不重要)。在 app/core/preprocessing/constants 中找到的 dict_english 只是我用其他词替换的不常见英语单词的字典。

import string
from app.core.preprocessing.constants import dict_english
from app.core.generic.step import Step
from typing import Optional
from app.api.model.my_project_parameters import MyProjectParameters

class TextPreprocessingBase(Step[str, str]):
    def process(self, input_value: str, parameters: Optional[MyProjectParameters] = None) -> str:
        input_value = input_value.replace("'", '')
        input_value = input_value.replace("\"", '')
        printable = set(string.printable)
        filter(lambda x: x in printable, input_value)
        new_string=''.join(filter(lambda x: x in printable, input_value))
        return new_string

class TextPreprocessingEnglish(TextPreprocessingBase):
    def process(self, input_value: str, parameters: Optional[MyProjectParameters] = None) -> str:
        process_english = super().process(input_value, parameters)
        for word, initial in dict_english.items():
            process_english = process_english.replace(word.lower(), initial)
        return process_english

容易测试:

string_example= """ Random 'text' ✓"""

a = TextPreprocessingEnglish()
output = a.process(string_example)
print(output)

它打印:

Random text

但是我想写一些自动测试。我想:

import pytest
from app.core.preprocessing.core import TextPreprocessingBase, TextPreprocessingEnglish
class TestEnglishPreprocessing:
    @pytest.fixture(scope='class')
    def english_preprocessing:
    ...

但我被困在这里了。我只想在我手动编写的几个不同字符串上测试我的代码。是否可以那样做,或者我只是像上面的简单测试示例一样编写它?

这听起来像是可以通过 parametrizing 测试解决的问题,例如:

import pytest
from process import TextPreprocessingEnglish


@pytest.mark.parametrize(
    "input,expected",
    [
        (""" Random 'text' ✓""", "Random text"),
        (""" Some other 'text' ✓""", "Some other text"),
    ],
)
def test_process(input, expected):
    a = TextPreprocessingEnglish()
    output = a.process(input)
    assert output == expected