Настройка PyTest или удаление переменной - PullRequest
0 голосов
/ 31 мая 2018

Как я могу создать экземпляр переменной для каждого из моих PyTests?

В частности, я хочу каждый раз создавать новый объект StringIO().

Мой текущий код такой:

output = StringIO()

def info_to_string(text):
    output.write(text) 

def write_to_file(some_text):
    for row in some_text:
        info_to_string(row)

Мне нужно output настраивать каждый раз, когда появляется новое тестовое устройство.

Скопировать и вставить код для тестирования:

from io import StringIO
import pytest


output = StringIO()


def info_to_string(text):
    output.write(text)


def write_to_file(some_text):
    for row in some_text:
        info_to_string(row)


def test_1():
    write_to_file(['hello', 'there', 'what', 'is', 'up'])
    print(output)
    assert output.getvalue() == "hellotherewhatisup"


def test_2():
    write_to_file(['nothing', 'much'])
    assert output.getvalue() == "nothingmuch"
    #This will error as the output is "hellotherewhatisupnothingmuch" if run after test_1

ИтакМне понадобится новый output = stringIO() для каждого теста.

Ответы [ 3 ]

0 голосов
/ 31 мая 2018

Я думаю, что самый простой способ проверить операцию записи файла - это использовать tempfile .

Но как только StringIO упоминается как часть стратегии тестирования, я предлагаю разделить файлписать на две части.Это дает чистую точку входа для буфера StringIO.

from pathlib import Path

from io import StringIO
import pytest

# Separate your data export to 2 functions, one operating 
# with a filename, other with a file object. 
def to_file(filename, content):
    path = Path(filename)
    if not path.exists():
        path.touch()
    with path.open('a') as f_obj:    
        write_to_file(f_obj, content)  

# This is code under test. It must not be connected to your
# test code in any way, even if you have some version of "monkey-patching"
# in mind.     
def write_to_file(file_object, content):
    """Dump *content* list of strings to *filename* with *writer*."""
    for x in content:
       file_object.write(str(x))    

# This is test with StringIO buffer
def test_write_to_file_with_buffer():
    buffer = StringIO()
    # note you make several calls to write_to_file in one test, not across tests
    # this helps keep tests isolated/independent
    write_to_file(buffer, ['hello', 'there', 'what', 'is', 'up']) 
    write_to_file(buffer, ['nothing', 'much'])
    assert buffer.getvalue() == 'hellotherewhatisupnothingmuch'
0 голосов
/ 31 мая 2018

Если кто-нибудь увидит это в будущем, то, как я это сделал, создав класс, повторно инициализировав его для каждого прибора

class WriteToString:
    def __init__(self):
        self.output = StringIO()

    def info_to_string(self, text):
        self.output.write(text)


@pytest.fixture
def write_to_string():
    return WriteToString()

и изменив тесты на:

def test_2(write_to_string):
    write_to_file(['nothing', 'much'])
    assert write_to_string.output.getvalue() == "nothingmuch" 
0 голосов
/ 31 мая 2018

Я не уверен, что полностью понимаю ваши вопросы, но вы можете сделать что-то вроде ниже, которое будет создавать новый экземпляр StringIO каждый раз, когда вы передаете его в свою тестовую функцию.Если вы хотите каждый раз возвращать новую строку, я не думаю, что вы ищете фиксатор, а просто вызов универсальной функции, которая сделает всю работу за вас.

import pytest
from StringIO import StringIO

@pytest.fixture(scope='function')
def info_to_string():
    output = StringIO()
    output.write('blah')
    return output

def test_something(info_to_string):
    assert isinstance(info_to_string, StringIO)
    assert info_to_string.getvalue() == 'blah'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...