Building an Automated Test Cases Generator with Lyzr Automata
Published: 2024-04-10 06:39:12

In software development, testing is a crucial phase to ensure the quality and reliability of the product. Test cases play a significant role in this process by helping to identify potential issues and validate the functionality of the code. However, manually creating test cases can be time-consuming and error-prone. In this blog post, we’ll explore how to build an automated test cases generator using Lyzr Automata.

The goal is to develop a tool that automates the generation of test cases based on provided code snippets and descriptions. Users will be able to input their code and describe its functionality, and the tool will generate both positive and negative test cases using AI-powered text completion models.

**Code Walk-Through:**
**Imports and Environment Setup:**

```
import streamlit as st
from lyzr_automata.ai_models.openai import OpenAIModel
from lyzr_automata import Agent,Task
from lyzr_automata.pipelines.linear_sync_pipeline import LinearSyncPipeline
from PIL import Image
from dotenv import load_dotenv
import os

load_dotenv()
api = os.getenv("OPENAI_API_KEY")
```

load_dotenv() reads the .env file (assuming it exists) to retrieve the OpenAI API key stored as an environment variable.
api = os.getenv("OPENAI_API_KEY") retrieves the API key from the environment.

**OpenAI Model and Language Options:**

```
open_ai_text_completion_model = OpenAIModel(
    api_key=api,
    parameters={
        "model": "gpt-4-turbo-preview",
        "temperature": 0.2,
        "max_tokens": 1500,
    },
)
```
open_ai_text_completion_model creates an instance of the OpenAIModel class with the API key and sets parameters for the GPT-4 model:
Temperature: 0.2 (controls randomness in generated text)
Maximum tokens: 1500 (limits the output length)

**User Input:**

```
code = st.sidebar.text_area("Enter Your Code: ",height=200)
description = st.sidebar.text_input("Enter Code Description: ")
```

code = st.sidebar.text_area creates a text area in the sidebar for users to enter their code. It sets a height of 200 pixels and a label "Enter Your Code: ".
description = st.sidebar.text_input creates a text input field in the sidebar for users to provide a description of their code.

**Test Case Generation Function (test_cases):**

```
def test_cases(code,description):
    test_agent = Agent(
        role="Test Case expert",
        prompt_persona=f"You are a helpful assistant capable of generating software test cases from code."
    )

    task1 = Task(
        name="Generate Test Cases",
        model=open_ai_text_completion_model,
        agent=test_agent,
        instructions=f"You have to create test cases for given {code} and {description}. "
                     f"Generate positive and negative test cases both."
                     f"[!important] Only give test cases nothing else.",
    )

    output = LinearSyncPipeline(
        name="Test Case Details",
        completion_message="Test Cases Generated",
        tasks=[
            task1
        ],
    ).run()

    return output[0]['task_output']
```

This function takes code and description as input.
Inside the function:
test_agent creates an Agent object representing a "Test Case expert" with a prompt persona describing their expertise in generating test cases.
task1 defines a Task object named "Generate Test Cases":
It assigns the open_ai_text_completion_model, test_agent, and instructions to the task.
The instructions specify generating positive and negative test cases for the provided code and description, emphasizing returning only test cases.
LinearSyncPipeline creates a pipeline named "Test Case Details":
completion_message: "Test Cases Generated" (displayed after successful generation)
tasks: A list containing the single task1
.run() executes the pipeline, triggering test case generation using the OpenAI model.
output[0]['task_output'] retrieves the generated test cases from the first element (index 0) of the output list and returns it.

**Output:**

```
if st.sidebar.button("Generate"):
    tc = test_cases(code, description)
    st.markdown(tc)
```

Inside the if block:
tc = test_cases(code, description) calls the test_cases function to generate test cases based on the user's input code and description.
st.markdown(tc) displays the generated test cases as markdown text in the app.

Automating the generation of test cases can significantly improve the efficiency and effectiveness of software testing processes. With Lyzr Automata, we have developed a powerful tool that streamlines the creation of test cases, saving time and effort for developers and testers. This application can be further enhanced with additional features and integrations to cater to specific testing needs in different domains.

try it now: [https://lyzr-test-cases-generator.streamlit.app/](https://lyzr-test-cases-generator.streamlit.app/)

For more information explore the website: [Lyzr](https://www.lyzr.ai/)