Write a test for the following function. Make sure to include parametrisation and pytest. Also, mock the completion argument so that the test doesn't fail:
def yield_completion_for_flask(completion):
start_chunks_time = time.time()
l_chunks = []
for number, chunk in enumerate(completion):
# if the chunk is actually a string
if isinstance(chunk, str):
yield f"data: {chunk}\n"
# some chunk have no content field
else:
if len(chunk.choices) > 0 and hasattr(chunk.choices[0].delta, "content"):
content = chunk["choices"][0]["delta"]["content"]
if content.startswith("\n") and number == 0:
# remove the any leading newline character using regex
content = content.lstrip("\n")
_logger.debug(
f"Chunk received {round(time.time() - start_chunks_time),2} after query: {content}"
)
l_chunks.append(content)
# yield content
yield f"data: {content}\n"
code
_logger.info(
f"End of response from AzOAI. Total response time: {time.time() - start_chunks_time}"
)
_logger.info(
"LLM Response: %s" % "".join(l_chunks)
)
Assistant
Here's an example of how you can write tests for the yield_completion_for_flask function using pytest and parameterization:
python
import pytest
from unittest.mock import Mock
import time
from your_module import yield_completion_for_flask # Replace 'your_module' with the actual module name
@pytest.mark.parametrize("completion, expected_output", [
# Test case 1: completion is a list of strings
(["Hello, ", "world!"], ["data: Hello, \n", "data: world!\n"]),
# Test case 2: completion is a list of objects with content field
([Mock(choices=[Mock(delta=Mock(content="Hello, "))]), Mock(choices=[Mock(delta=Mock(content="world!"))])],
["data: Hello, \n", "data: world!\n"]),
# Test case 3: completion is a list of objects without content field
([Mock(choices=[Mock(delta=Mock())]), Mock(choices=[Mock(delta=Mock())])], []),
# Test case 4: completion is a list of objects with empty content field
([Mock(choices=[Mock(delta=Mock(content=""))]), Mock(choices=[Mock(delta=Mock(content=""))])],
["data: \n", "data: \n"]),
# Test case 5: completion is a list of objects with content field starting with newline character
([Mock(choices=[Mock(delta=Mock(content="\nHello, "))]), Mock(choices=[Mock(delta=Mock(content="world!"))])],
["data: Hello, \n", "data: world!\n"]),
])
def test_yield_completion_for_flask(caplog, completion, expected_output):
# Mock the logger to avoid logging messages during testing
caplog.set_level("ERROR")
# Call the function and convert the generator to a list
output = list(yield_completion_for_flask(completion))
# Assert the output
assert output == expected_output
def test_yield_completion_for_flask_with_time(caplog, monkeypatch):
# Mock the logger to avoid logging messages during testing
caplog.set_level("ERROR")
# Mock the time.time function to return a fixed value
start_time = 1643723400
monkeypatch.setattr(time, 'time', lambda: start_time)
# Call the function and convert the generator to a list
completion = [Mock(choices=[Mock(delta=Mock(content="Hello, "))]), Mock(choices=[Mock(delta=Mock(content="world!"))])]
output = list(yield_completion_for_flask(completion))
# Assert the output
assert output == ["data: Hello, \n", "data: world!\n"]
# Assert the log messages
assert f"End of response from AzOAI. Total response time: 0" in caplog.text
assert "LLM Response: Hello, world!" in caplog.text
In this code:
We use pytest.mark.parametrize to parameterize the test function with different inputs and expected outputs.
We use the Mock class from unittest.mock to mock the completion argument, which is expected to be a list of objects with certain attributes.
We use caplog to capture and assert the log messages.
We use monkeypatch to mock the time.time function and test the timing-related functionality.
We test the function with different scenarios, including when the completion is a list of strings, objects with content field, objects without content field, objects with empty content field, and objects with content field starting with newline character.
“Write a test for the following function. Make sure to include parametrisation and….” Conversation with llama-3.1-405b-instruct, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m850a4ep84rz3vvfytp9d7t7