【问题标题】:How can I write automatic tests for this Python code?如何为此 Python 代码编写自动测试?
【发布时间】:2022-01-07 13:32:13
【问题描述】:

我在文件夹preprocessing 中找到的脚本core.py 接受一个字符串并清理它。它是更大模型的一部分(请参阅最后一个导入,但这并不重要)。在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:
    ...

但我被困在这里。我只想在我手动编写的几个不同的字符串上测试我的代码。可以这样写还是像上面的简单测试例子那样写?

【问题讨论】:

    标签: python class testing


    【解决方案1】:

    这听起来像是你可以通过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
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      相关资源
      最近更新 更多