簡體   English   中英

如何為此 Python 代碼編寫自動測試?

[英]How can I write automatic tests for this Python code?

在文件夾preprocessing中找到的我的腳本core.py需要一個字符串並清理它。 它是更大的 model 的一部分(請參閱最后一個導入,但這並不重要)。 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:
    ...

但我被困在這里。 我只想在我手動編寫的幾個不同的字符串上測試我的代碼。 是否可以這樣做,或者我只是像上面的簡單測試示例那樣編寫它?

這聽起來像是您可以通過參數化測試來解決的問題,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM