Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
WIP: testing
Stefan Krawczyk6f2df6d5a0b6
diff --git a/examples/test_case_creation/README.md b/examples/test_case_creation/README.mdnew file mode 100644index 00000000..4ceb8fe0--- /dev/null+++ b/examples/test_case_creation/README.md@@ -0,0 +1,26 @@+# Creating robust applications by creating test cases+This example shows you how you can easily create (integration) test cases for Burr your project.++With Burr it is easy to foster a test-driven development mindset when developing actions, which are the building blocks of your Burr+application.++## Motivation++With LLMs non-deterministic behavior can impact your application's behavior. It is important to create test cases to+ensure that your application is robust and behaves as expected; it is easy to tweak a prompt and break+a particular use case. This example shows you how you can create test cases+for your project from real traces, since part of the struggle is to create test cases that are representative of the+real-world behavior of your application -- Burr can make this process easier.++## Steps+1. Build your project with Burr.+2. Run your Burr application with tracking/persistence.+3. Find a trace that you want to create a test case for.+4. Note the partition_key, app_id, and sequence_id of the trace.+5. Create a test case using the `burr create-test-case` command passing the partition_key, app_id, and sequence_id as arguments.+6. Iterate on the test case until it is robust and representative of the real-world behavior of your application.+7. Profit.++## Testing Actions+In `test_application.py` you'll find examples tests for a simple action+that is found in `application.py`.diff --git a/examples/test_case_creation/application.py b/examples/test_case_creation/application.pynew file mode 100644index 00000000..a68630c2--- /dev/null+++ b/examples/test_case_creation/application.py@@ -0,0 +1,60 @@+from typing import Tuple++import openai++from burr.core import State+from burr.core.action import action++# This file is truncated to just the relevant parts for the example.++MODES = {+ "answer_question": "text",+ "generate_image": "image",+ "generate_code": "code",+ "unknown": "text",+}+++def _get_openai_client():+ return openai.Client()+++@action(reads=["prompt"], writes=["mode"])+def choose_mode(state: State) -> Tuple[dict, State]:+ prompt = (+ f"You are a chatbot. You've been prompted this: {state['prompt']}. "+ f"You have the capability of responding in the following modes: {', '.join(MODES)}. "+ "Please respond with *only* a single word representing the mode that most accurately "+ "corresponds to the prompt. For instance, if the prompt is 'draw a picture of a cat', "+ "the mode would be 'generate_image'. If the prompt is 'what is the capital of France', the mode would be 'answer_question'."+ "If none of these modes apply, please respond with 'unknown'."+ )++ result = _get_openai_client().chat.completions.create(+ model="gpt-4",+ messages=[+ {"role": "system", "content": "You are a helpful assistant"},+ {"role": "user", "content": prompt},+ ],+ )+ content = result.choices[0].message.content+ mode = content.lower()+ if mode not in MODES:+ mode = "unknown"+ result = {"mode": mode}+ return result, state.update(**result)+++@action(reads=["prompt", "chat_history"], writes=["response"])+def prompt_for_more(state: State) -> Tuple[dict, State]:+ result = {+ "response": {+ "content": "None of the response modes I support apply to your question. Please clarify?",+ "type": "text",+ "role": "assistant",+ }+ }+ return result, state.update(**result)+++# This file is truncated to just the relevant parts for the example.diff --git a/examples/test_case_creation/prompt_for_more.json b/examples/test_case_creation/prompt_for_more.jsonnew file mode 100644index 00000000..e09659dc--- /dev/null+++ b/examples/test_case_creation/prompt_for_more.json@@ -0,0 +1,19 @@+[+ {+ "action": "prompt_for_more",+ "name": "demo-test",+ "input_state": {+ "prompt": "",+ "chat_history": []+ },+ "expected_state": {+ "prompt": "",+ "chat_history": [],+ "response": {+ "content": "None of the response modes I support apply to your question. Please clarify?",+ "type": "text",+ "role": "assistant"+ }+ }+ }+]diff --git a/examples/test_case_creation/test-cases2.json b/examples/test_case_creation/test-cases2.jsonnew file mode 100644index 00000000..f69b0a0d--- /dev/null+++ b/examples/test_case_creation/test-cases2.json@@ -0,0 +1,19 @@+[+ {+ "action": "prompt_for_more2",+ "name": "demo-test2",+ "input_state": {+ "prompt": "",+ "chat_history": []+ },+ "expected_state": {+ "prompt": "",+ "chat_history": [],+ "response": {+ "content": "None of the response modes I support apply to your question. Please clarify?",+ "type": "text",+ "role": "assistant"+ }+ }+ }+]diff --git a/examples/test_case_creation/test_application.py b/examples/test_case_creation/test_application.pynew file mode 100644index 00000000..98c32d39--- /dev/null+++ b/examples/test_case_creation/test_application.py@@ -0,0 +1,96 @@+"""+This is an example test module showing how you can test an action in your application.++1. There is a very straightforward unit testing style approach.+2. There is a more complex approach that uses pytest_generate_tests to dynamically generate test cases.+"""+import json++import pytest+from application import prompt_for_more++from burr.core import state+++def test_prompt_for_more():+ """A basic test showing how to 'unit' test an action."""+ # set up state to pass in+ input_state = state.State(+ {+ "prompt": "",+ "chat_history": [],+ }+ )+ # Set up expected result and output state+ expected_state = state.State(+ {+ "prompt": "",+ "chat_history": [],+ "response": {+ "content": "None of the response modes I support apply to your question. Please clarify?",+ "type": "text",+ "role": "assistant",+ },+ }+ )+ result, output_state = prompt_for_more(input_state)+ # evaluate+ assert output_state == expected_state+ assert result == {+ "response": {+ "content": "None of the response modes I support apply to your question. Please clarify?",+ "type": "text",+ "role": "assistant",+ }+ }+++# one way to parameterize tests is to store the serialized state in a json file+# and then load it for the test.+def load_test_cases(file_name: str) -> tuple:+ """Load test cases from a json file."""+ with open(file_name, "r") as f:+ json_test_cases = json.load(f)+ test_cases = [(tc.get("input_state"), tc.get("expected_state")) for tc in json_test_cases]+ test_ids = [+ f"{tc.get('action', 'ACTION_MISSING')}-{tc.get('name', 'NAME_MISSING')}"+ for tc in json_test_cases+ ]+ return test_cases, test_ids+++# Define the pytest_generate_tests hook to generate test cases dynamically based on the+# contents of a file+def pytest_generate_tests(metafunc):+ """This function dynamically generates test cases based on the contents of a file."""++ # for each function that has the 'input_state' and 'expected_state' arguments:+ if "input_state" in metafunc.fixturenames and "expected_state" in metafunc.fixturenames:+ # gets all filenames from the 'file_name' marker+ file_names = [+ file_arg+ for m in metafunc.definition.own_markers+ if m.name == "file_name"+ for file_arg in m.args+ ]+ all_test_cases = []+ all_test_ids = []+ for file_name in file_names:+ test_cases, test_case_ids = load_test_cases(file_name)+ all_test_cases.extend(test_cases)+ all_test_ids.extend(test_case_ids)+ if not all_test_cases:+ raise ValueError(+ f"No test cases could be created for test {metafunc.definition.originalname}."+ )+ # Generate test cases based on the test_data list+ metafunc.parametrize("input_state,expected_state", all_test_cases, ids=all_test_ids)++[email protected]_name("prompt_for_more.json")+def test_prompt_for_more_from_file(input_state, expected_state):+ """Function for testing the action"""+ input_state = state.State(input_state)+ expected_state = state.State(expected_state)+ _, output_state = prompt_for_more(input_state) # exercising the action+ assert output_state == expected_state