DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • Cutting P99 Latency From ~3.2s To ~650ms in a Policy‑Driven Authorization API (Python + MongoDB)
  • From Zero to Local AI in 10 Minutes With Ollama + Python

Trending

  • How to Save Money Using Custom LLMs for Specific Tasks
  • The Big Data Architecture Blueprint: Core Storage, Integration, and Governance Patterns
  • Spring AI Advisors: Chat Memory, Token Tracking, and Message Logging
  • How to Parse Large XML Files in PHP Without Running Out of Memory
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Leveraging LLMs for Software Testing

Leveraging LLMs for Software Testing

Explore how LLMs enhance Python testing by automating test case generation, improving test coverage, reducing maintenance, and supporting efficient workflows.

By 
Pradeesh Ashokan user avatar
Pradeesh Ashokan
·
Mar. 17, 25 · Analysis
Likes (2)
Comment
Save
Tweet
Share
3.2K Views

Join the DZone community and get the full member experience.

Join For Free

As software systems become more complex, traditional testing methods often fall short in keeping up with the fast-paced development cycles and changing user needs. Fortunately, advancements in machine learning and generative AI are bringing intelligent and adaptive testing strategies that improve test coverage and decrease maintenance efforts to speed up the entire testing process. 

This article details using large language models (LLMs) to test a Python codebase project.

Benefits of LLMs in Test Automation

Increased Efficiency and Speed

LLMs can greatly accelerate the testing process by automating tasks such as test case generation, execution, and analysis. This automation allows testing teams to concentrate on more strategic activities, such as exploratory testing and test planning.

Improved Test Coverage

LLMs can enhance test coverage by identifying edge cases and generating test scenarios that manual testing might overlook. This results in a more comprehensive and robust testing process, reducing the risk of defects being released into production.

Reducing Test Script Maintenance

LLMs can analyze code changes and automatically update test scripts. This process significantly minimizes manual effort and the potential for errors.

Test Case Generation for a User Story Using ChatGPT

The following Python code uses OpenAI's API to generate test cases for a given user story. It sets an API key, defines a generate_test_case.py function that creates a prompt using the user story and interacts with the GPT-4 model to generate test cases. 

This helps with the bootstrapping required for creating manual test cases.

Python
 
from openai import ChatCompletion

openai.api_key = "your-api-key"

def generate_test_case(user_story):
    prompt = f"Write test cases for: '{user_story}'"
    response = ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message['content']

user_story = "As a user, I want to reset my password to regain account access."
print(generate_test_case(user_story))


Pytest Case Generation for a Python Function Using ChatGPT

Pytest is Python's popular testing framework. The following Python code uses OpenAI's GPT API to generate pytest test cases for a calculate_bmi function, that calculates BMI based on weight and height and categorizes it ("Underweight," "Normal weight," etc.). 

Using the inspect module, the script extracts the function's source code and prepares a prompt asking GPT to generate parameterized test cases, including edge cases like invalid or zero inputs. This method is very effective in generating automated pytest cases, which can then be included as a separate test file in the project.

Python
 
import openai
import inspect

# Set up your API key
openai.api_key = "your-api-key-here"

# Calculate BMI function part of your app's feature
def calculate_bmi(weight, height):
    if height <= 0 or weight <= 0:
        raise ValueError("Height and weight must be greater than zero.")
    bmi = weight / (height ** 2)
    if bmi < 18.5:
        return "Underweight"
    elif 18.5 <= bmi < 24.9:
        return "Normal weight"
    elif 25 <= bmi < 29.9:
        return "Overweight"
    else:
        return "Obesity"


# Get the function source code as a string
function_code = inspect.getsource(calculate_bmi) 

# Define the prompt
prompt = f"""
Generate pytest test cases for the following Python function:
{function_code}
Include edge cases such as invalid inputs (zero or negative values), and use parameterized tests where possible.
"""

# Make the API call
response = openai.ChatCompletion.create(
    model="gpt-4",     
    messages=[
        {"role": "system", "content": "You are a Python testing assistant."},
        {"role": "user", "content": prompt}
    ],
    max_tokens=500,
    temperature=0.7
)

# Print the response
print(response['choices'][0]['message']['content'])


Pytest Cases Generation Without Passing Function Code

In some situations, sharing code directly may not be feasible due to privacy or security concerns. However, ChatGPT can still assist in these cases.

  • Function signatures. Using only the function's name, parameters, and return type, ChatGPT can infer its purpose and create relevant test cases.
  • Code descriptions. By providing a detailed description of the code's functionality, developers can guide ChatGPT to generate appropriate tests.
Python
 
import openai
import inspect
openai.api_key = "your-api-key-here"

signature = inspect.signature(calculate_bmi)
docstring = inspect.getdoc(calculate_bmi)

prompt = f"""
Generate pytest test cases for the following Python signature and docstring:
signature - {signature}
docstring - {docstring}
Include edge cases such as invalid inputs (zero or negative values), and use parameterized tests where possible.
"""

# Make the API call
response = openai.ChatCompletion.create(
    model="gpt-4",     
    messages=[
        {"role": "system", "content": "You are a Python testing assistant."},
        {"role": "user", "content": prompt}
    ],
    max_tokens=500,
    temperature=0.7
)

# Print the response
print(response['choices'][0]['message']['content'])


Conclusion

LLM-powered test automation represents a significant advancement in software quality assurance. While challenges exist, organizations that successfully implement these technologies gain substantial advantages in testing efficiency, coverage, and reliability. 

As AI capabilities evolve, we can expect even more sophisticated testing approaches that will further improve software quality and reduce manual effort.

API Software testing Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • Cutting P99 Latency From ~3.2s To ~650ms in a Policy‑Driven Authorization API (Python + MongoDB)
  • From Zero to Local AI in 10 Minutes With Ollama + Python

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook